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
cbde111c0f655d229f493e637c78b73524f2d37d
Fix wrong send method in SendMessageCommand
attemoi/MoistureBot
moisture-bot/MoistureBot.Commands/SendMessageCommand.cs
moisture-bot/MoistureBot.Commands/SendMessageCommand.cs
using System; using Mono.Options; using System.Collections.Generic; using System.Linq; namespace moisturebot.commands { public class SendMessageCommand : ICommand { public string[] Args { get; set; } public Boolean help; public Boolean user; public Boolean room; private OptionSet options; public SendMessageCommand() { options = new OptionSet () { { "h|help", "show this message", h => help = h != null }, { "u|user", "send message to user", u => user = u != null }, { "r|room", "send message to room", r => room = r != null } }; } public void WriteHelp() { ConsoleUtils.WriteHelp( "send message to user or room", "msg -user <user_id> <message>" + Environment.NewLine + " msg -room <room_id> <message>", options); } public bool Execute (IMoistureBot bot) { List<string> extra = options.Parse(Args); if (help || extra.Count < 2 || (!user && !room)) { WriteHelp (); return false; } if (!bot.IsConnected ()) { Console.WriteLine ("Not connected to Steam."); return false; } string chatId = extra.ElementAt (0); // get rest string message = string.Join (" ", extra.Skip (1)).Trim ('\"'); ulong id; try { id = UInt64.Parse(chatId); } catch { Console.WriteLine ("Invalid chat id!"); return false; } if (user) { Console.WriteLine ("Sending chat message to friend '{0}'...", id); bot.SendChatMessage (message, id); } if (room) { Console.WriteLine ("Sending chat message to room '{0}'...", id); bot.SendChatRoomMessage (message, id); } return false; } } }
using System; using Mono.Options; using System.Collections.Generic; using System.Linq; namespace moisturebot.commands { public class SendMessageCommand : ICommand { public string[] Args { get; set; } public Boolean help; public Boolean user; public Boolean room; private OptionSet options; public SendMessageCommand() { options = new OptionSet () { { "h|help", "show this message", h => help = h != null }, { "u|user", "send message to user", u => user = u != null }, { "r|room", "send message to room", r => room = r != null } }; } public void WriteHelp() { ConsoleUtils.WriteHelp( "send message to user or room", "msg -user <user_id> <message>" + Environment.NewLine + " msg -room <room_id> <message>", options); } public bool Execute (IMoistureBot bot) { List<string> extra = options.Parse(Args); if (help || extra.Count < 2 || (!user && !room)) { WriteHelp (); return false; } if (!bot.IsConnected ()) { Console.WriteLine ("Not connected to Steam."); return false; } string chatId = extra.ElementAt (0); // get rest string message = string.Join (" ", extra.Skip (1)).Trim ('\"'); ulong id; try { id = UInt64.Parse(chatId); } catch { Console.WriteLine ("Invalid chat id!"); return false; } if (user) { Console.WriteLine ("Sending chat message to friend '{0}'...", id); bot.SendChatMessage (message, id); } if (room) { Console.WriteLine ("Sending chat message to room '{0}'...", id); bot.SendChatMessage (message, id); } return false; } } }
mit
C#
374905cfda4d4d2060cdd52cd9d5939d4e9f28c6
Update processing pipeline to use CloudEvent SDK 2.1.0 #19
GoogleCloudPlatform/eventarc-samples,GoogleCloudPlatform/eventarc-samples,GoogleCloudPlatform/eventarc-samples,GoogleCloudPlatform/eventarc-samples,GoogleCloudPlatform/eventarc-samples
processing-pipelines/common/csharp/PubSubEventWriter.cs
processing-pipelines/common/csharp/PubSubEventWriter.cs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; using Google.Cloud.PubSub.V1; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace Common { public class PubSubEventWriter : IEventWriter { private readonly string _projectId; private readonly string[] _topicIds; private readonly ILogger _logger; public PubSubEventWriter(string projectId, string topicId, ILogger logger) { _projectId = projectId; _topicIds = topicId.Split(':'); _logger = logger; } public async Task Write(object eventData, HttpContext context) { PublisherClient publisher = null; foreach (var topicId in _topicIds) { var topicName = new TopicName(_projectId, topicId); publisher = await PublisherClient.CreateAsync(topicName); var message = JsonConvert.SerializeObject(eventData); _logger.LogInformation($"Publishing to topic '{topicId}' with message '{message}'"); await publisher.PublishAsync(message); } if (publisher != null) { await publisher.ShutdownAsync(TimeSpan.FromSeconds(10)); } } } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; using Google.Cloud.PubSub.V1; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Common { public class PubSubEventWriter : IEventWriter { private readonly string _projectId; private readonly string[] _topicIds; private readonly ILogger _logger; public PubSubEventWriter(string projectId, string topicId, ILogger logger) { _projectId = projectId; _topicIds = topicId.Split(':'); _logger = logger; } public async Task Write(object eventData, HttpContext context) { PublisherClient publisher = null; foreach (var topicId in _topicIds) { var topicName = new TopicName(_projectId, topicId); _logger.LogInformation($"Publishing to topic '{topicId}' with data '{eventData}"); publisher = await PublisherClient.CreateAsync(topicName); await publisher.PublishAsync((string)eventData); } if (publisher != null) { await publisher.ShutdownAsync(TimeSpan.FromSeconds(10)); } } } }
apache-2.0
C#
979b787804419baa0c45a2baf955516c34e7a4eb
Update for 1.129
Souper07/Autopilot,Souper07/Autopilot,Rynchodon/ARMS,Rynchodon/Autopilot,Rynchodon/ARMS,Rynchodon/Autopilot
Scripts/Utility/Attached/Piston.cs
Scripts/Utility/Attached/Piston.cs
using System; using Sandbox.Common.ObjectBuilders; using VRage.Game.ModAPI; namespace Rynchodon.Attached { public static class Piston { public class PistonBase : AttachableBlockUpdate { private readonly Logger myLogger; public PistonBase(IMyCubeBlock block) : base(block, AttachedGrid.AttachmentKind.Piston) { myLogger = new Logger("PistonBase", block); } protected override AttachableBlockBase GetPartner() { var builder = myBlock.GetObjectBuilder_Safe() as MyObjectBuilder_ExtendedPistonBase; if (builder == null) throw new NullReferenceException("builder"); if (builder.TopBlockId.HasValue) return GetPartner(builder.TopBlockId.Value); return null; } } public class PistonTop : AttachableBlockBase { private readonly Logger myLogger; public PistonTop(IMyCubeBlock block) : base(block, AttachedGrid.AttachmentKind.Piston) { myLogger = new Logger("PistonTop", block); } //protected override AttachableBlockPair GetPartner() //{ // var builder = myBlock.GetObjectBuilder_Safe() as MyObjectBuilder_PistonTop; // if (builder == null) // throw new NullReferenceException("builder"); // return GetPartner(builder.PistonBlockId); //} } } }
using System; using Sandbox.Common.ObjectBuilders; using VRage.Game.ModAPI; namespace Rynchodon.Attached { public static class Piston { public class PistonBase : AttachableBlockUpdate { private readonly Logger myLogger; public PistonBase(IMyCubeBlock block) : base(block, AttachedGrid.AttachmentKind.Piston) { myLogger = new Logger("PistonBase", block); } protected override AttachableBlockBase GetPartner() { var builder = myBlock.GetObjectBuilder_Safe() as MyObjectBuilder_ExtendedPistonBase; if (builder == null) throw new NullReferenceException("builder"); return GetPartner(builder.TopBlockId); } } public class PistonTop : AttachableBlockBase { private readonly Logger myLogger; public PistonTop(IMyCubeBlock block) : base(block, AttachedGrid.AttachmentKind.Piston) { myLogger = new Logger("PistonTop", block); } //protected override AttachableBlockPair GetPartner() //{ // var builder = myBlock.GetObjectBuilder_Safe() as MyObjectBuilder_PistonTop; // if (builder == null) // throw new NullReferenceException("builder"); // return GetPartner(builder.PistonBlockId); //} } } }
cc0-1.0
C#
62f6a4dbc17b4b12fc3a1f66690fab3926c0c333
Use the new ControllerUi
RagingBool/RagingBool.Carcosa
projects/RagingBool.Carcosa.Core_cs/Stage/PartyStage.cs
projects/RagingBool.Carcosa.Core_cs/Stage/PartyStage.cs
// [[[[INFO> // Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool) // // 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. // // For more information check https://github.com/RagingBool/RagingBool.Carcosa // ]]]] using Epicycle.Commons.Time; using RagingBool.Carcosa.Core.Workspace; using RagingBool.Carcosa.Devices; using RagingBool.Carcosa.Devices.Midi; namespace RagingBool.Carcosa.Core.Stage { internal sealed class PartyStage : IStage { private readonly IClock _clock; private readonly ILpd8 _controller; private readonly ISnark _snark; private readonly ControllerUi _controllerUi; public PartyStage(IClock clock, ICarcosaWorkspace workspace) { _clock = clock; _controller = new MidiLpd8(workspace.ControllerMidiInPort, workspace.ControllerMidiOutPort); _snark = new SerialSnark(_clock, workspace.SnarkSerialPortName, 12, 60); _controllerUi = new ControllerUi(_controller); } public void Start() { _controller.Connect(); _snark.Connect(); _controllerUi.Start(); } public void Update() { _controller.Update(); _snark.Update(); _controllerUi.Update(); } public void Stop() { _controllerUi.Stop(); _controller.Disconnect(); _snark.Disconnect(); } } }
// [[[[INFO> // Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool) // // 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. // // For more information check https://github.com/RagingBool/RagingBool.Carcosa // ]]]] using Epicycle.Commons.Time; using RagingBool.Carcosa.Core.Workspace; using RagingBool.Carcosa.Devices; using RagingBool.Carcosa.Devices.Midi; namespace RagingBool.Carcosa.Core.Stage { internal class PartyStage : IStage { private readonly IClock _clock; private readonly ILpd8 _controller; private readonly ISnark _snark; private int _lastController; public PartyStage(IClock clock, ICarcosaWorkspace workspace) { _clock = clock; _controller = new MidiLpd8(workspace.ControllerMidiInPort, workspace.ControllerMidiOutPort); _controller.OnButtonEvent += _controller_OnButtonEvent; _controller.OnControllerChange += _controller_OnControllerChange; _lastController = 255; _snark = new SerialSnark(_clock, workspace.SnarkSerialPortName, 12, 60); } public void Start() { _controller.Connect(); _snark.Connect(); } public void Update() { _controller.Update(); _snark.Update(); } public void Stop() { _controller.Disconnect(); _snark.Disconnect(); } void _controller_OnButtonEvent(object sender, ButtonEventArgs e) { if (e.ButtonEventType == ButtonEventType.Pressed) { _controller.SetKeyLightState(e.ButtonId, _lastController >= 128); } } void _controller_OnControllerChange(object sender, ControllerChangeEventArgs e) { _lastController = e.Value; _snark.SetChannel(e.ControllerId, e.Value); } } }
apache-2.0
C#
77d9483bf50886d9ba1cbaafbd6413b69eaf5a6f
Fix toolcommands
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Shell/Commands/ToolCommands.cs
WalletWasabi.Gui/Shell/Commands/ToolCommands.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Diagnostics; using AvalonStudio.Commands; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using ReactiveUI; using Splat; using System; using System.Composition; using System.IO; using System.Linq; using System.Reactive.Linq; using WalletWasabi.Gui.Controls.WalletExplorer; using WalletWasabi.Gui.Tabs; using WalletWasabi.Gui.Tabs.WalletManager; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Shell.Commands { internal class ToolCommands { [ImportingConstructor] public ToolCommands(CommandIconService commandIconService) { var walletManagerCommand = ReactiveCommand.Create(OnWalletManager); var settingsCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel())); var transactionBroadcasterCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel())); #if DEBUG var devToolsCommand = ReactiveCommand.Create(() => DevToolsExtensions.OpenDevTools((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow)); #endif Observable .Merge(walletManagerCommand.ThrownExceptions) .Merge(settingsCommand.ThrownExceptions) .Merge(transactionBroadcasterCommand.ThrownExceptions) #if DEBUG .Merge(devToolsCommand.ThrownExceptions) #endif .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => Logger.LogError(ex)); WalletManagerCommand = new CommandDefinition( "Wallet Manager", commandIconService.GetCompletionKindImage("WalletManager"), walletManagerCommand); SettingsCommand = new CommandDefinition( "Settings", commandIconService.GetCompletionKindImage("Settings"), settingsCommand); TransactionBroadcasterCommand = new CommandDefinition( "Transaction Broadcaster", commandIconService.GetCompletionKindImage("BroadcastTransaction"), transactionBroadcasterCommand); #if DEBUG DevToolsCommand = new CommandDefinition( "Dev Tools", commandIconService.GetCompletionKindImage("DevTools"), devToolsCommand); #endif } private void OnWalletManager() { var global = Locator.Current.GetService<Global>(); var walletManagerViewModel = IoC.Get<IShell>().GetOrCreateByType<WalletManagerViewModel>(); if (global.WalletManager.WalletDirectories.EnumerateWalletFiles().Any()) { walletManagerViewModel.SelectLoadWallet(); } else { walletManagerViewModel.SelectGenerateWallet(); } } [ExportCommandDefinition("Tools.WalletManager")] public CommandDefinition WalletManagerCommand { get; } [ExportCommandDefinition("Tools.Settings")] public CommandDefinition SettingsCommand { get; } [ExportCommandDefinition("Tools.BroadcastTransaction")] public CommandDefinition TransactionBroadcasterCommand { get; } #if DEBUG [ExportCommandDefinition("Tools.DevTools")] public CommandDefinition DevToolsCommand { get; } #endif } }
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Diagnostics; using AvalonStudio.Commands; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using ReactiveUI; using Splat; using System; using System.Composition; using System.IO; using System.Linq; using System.Reactive.Linq; using WalletWasabi.Gui.Controls.WalletExplorer; using WalletWasabi.Gui.Tabs; using WalletWasabi.Gui.Tabs.WalletManager; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Shell.Commands { internal class ToolCommands { [ImportingConstructor] public ToolCommands(CommandIconService commandIconService) { var walletManagerCommand = ReactiveCommand.Create(OnWalletManager); var settingsCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel())); var transactionBroadcasterCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel())); #if DEBUG var devToolsCommand = ReactiveCommand.Create(() => DevToolsExtensions.OpenDevTools((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow)); #endif Observable .Merge(walletManagerCommand.ThrownExceptions) .Merge(settingsCommand.ThrownExceptions) .Merge(transactionBroadcasterCommand.ThrownExceptions) #if DEBUG .Merge(devToolsCommand.ThrownExceptions) #endif .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => Logger.LogError(ex)); WalletManagerCommand = new CommandDefinition( "Wallet Manager", commandIconService.GetCompletionKindImage("WalletManager"), walletManagerCommand); SettingsCommand = new CommandDefinition( "Settings", commandIconService.GetCompletionKindImage("Settings"), settingsCommand); TransactionBroadcasterCommand = new CommandDefinition( "Transaction Broadcaster", commandIconService.GetCompletionKindImage("BroadcastTransaction"), transactionBroadcasterCommand); #if DEBUG DevToolsCommand = new CommandDefinition( "Dev Tools", commandIconService.GetCompletionKindImage("DevTools"), devToolsCommand); #endif } private void OnWalletManager() { var global = Locator.Current.GetService<Global>(); var walletManagerViewModel = IoC.Get<IShell>().GetOrCreateByType<WalletManagerViewModel>(); if (Directory.Exists(global.WalletsDir) && Directory.EnumerateFiles(global.WalletsDir).Any()) { walletManagerViewModel.SelectLoadWallet(); } else { walletManagerViewModel.SelectGenerateWallet(); } } [ExportCommandDefinition("Tools.WalletManager")] public CommandDefinition WalletManagerCommand { get; } [ExportCommandDefinition("Tools.Settings")] public CommandDefinition SettingsCommand { get; } [ExportCommandDefinition("Tools.BroadcastTransaction")] public CommandDefinition TransactionBroadcasterCommand { get; } #if DEBUG [ExportCommandDefinition("Tools.DevTools")] public CommandDefinition DevToolsCommand { get; } #endif } }
mit
C#
80184ac2e1f20e63482d3ea4a8dd999e2d1e5e94
Remove ScanForm methods
EasyPost/easypost-csharp,jmalatia/easypost-csharp,dmmatson/easypost-csharp,EasyPost/easypost-csharp,kendallb/easypost-async-csharp
EasyPost/ScanForm.cs
EasyPost/ScanForm.cs
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EasyPost { public class ScanForm : IResource { public string id { get; set; } public DateTime created_at { get; set; } public DateTime updated_at { get; set; } public List<string> tracking_codes { get; set; } public Address address { get; set; } public string form_url { get; set; } public string form_file_type { get; set; } public string mode { get; set; } } }
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EasyPost { public class ScanForm : IResource { public string id { get; set; } public DateTime created_at { get; set; } public DateTime updated_at { get; set; } public List<string> tracking_codes { get; set; } public Address address { get; set; } public string form_url { get; set; } public string form_file_type { get; set; } public string mode { get; set; } private static Client client = new Client(); /// <summary> /// Retrieve a ScanForm from its id. /// </summary> /// <param name="id">String representing a ScanForm. Starts with "sf_".</param> /// <returns>EasyPost.ScanForm instance.</returns> public static ScanForm Retrieve(string id) { Request request = new Request("scan_forms/{id}"); request.AddUrlSegment("id", id); return client.Execute<ScanForm>(request); } /// <summary> /// Create a ScanFrom for the given tracking codes. /// </summary> /// <param name="trackingCodes">List of tracking codes.</param> /// <returns>EasyPost.ScanForm instance.</returns> public static ScanForm Create(List<string> trackingCodes) { Request request = new Request("scan_forms", Method.POST); request.addBody(new List<Tuple<string, string>>() { new Tuple<string, string>("scan_form[tracking_codes]", string.Join(",", trackingCodes)) }); return client.Execute<ScanForm>(request); } /// <summary> /// Create a ScanForm for the given shipments. /// </summary> /// <param name="shipments">List of Shipment objects.</param> /// <returns>EasyPost.ScanForm instance.</returns> public static ScanForm Create(IEnumerable<Shipment> shipments) { return Create(shipments.Select(shipment => shipment.tracking_code).ToList()); } } }
mit
C#
49362a3fe83f3ff622501f74f76bb5e3baaf3454
Fix TracingAnnotationNames
vostok/core
Vostok.Core/Tracing/TracingAnnotationNames.cs
Vostok.Core/Tracing/TracingAnnotationNames.cs
namespace Vostok.Tracing { public static class TracingAnnotationNames { public const string Operation = "operation"; public const string Service = "service"; public const string Component = "component"; public const string Kind = "kind"; public const string ClusterStrategy = "cluster.strategy"; public const string ClusterStatus = "cluster.status"; public const string HttpUrl = "http.url"; public const string HttpCode = "http.code"; public const string HttpMethod = "http.method"; public const string HttpRequestContentLength = "http.requestContentLength"; public const string HttpResponseContentLength = "http.responseContentLength"; } }
namespace Vostok.Tracing { public static class TracingAnnotationNames { public const string OperationName = "operationName"; public const string ServiceName = "serviceName"; public const string Component = "component"; public const string Kind = "kind"; public const string ClusterStrategy = "cluster.strategy"; public const string ClusterStatus = "cluster.status"; public const string HttpUrl = "http.url"; public const string HttpCode = "http.code"; public const string HttpMethod = "http.method"; public const string HttpRequestContentLength = "http.requestContentLength"; public const string HttpResponseContentLength = "http.responseContentLength"; } }
mit
C#
284fc3bd935fc3eba81dab8fa8078336144c0e98
Update Store.SqlServer connection string constructor
once-ler/Store
Store.Storage.SqlServer/src/Client.cs
Store.Storage.SqlServer/src/Client.cs
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using Store.Models; using Store.Storage.Data; namespace Store.Storage.SqlServer { public class Client { public Client(DBContext _dbContext) { var fac = new Factory<SqlConnection>(); Func<DBContext, string> func = (DBContext _db) => _db.userId.Length == 0 || _db.password.Length == 0 ? string.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI;", _db.server, _db.database) : string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", _db.server, _db.database, _db.userId, _db.password); dbConnection = fac.Get(_dbContext, func); } protected string tryCatch(Action act) { try { act(); } catch (Exception e) { return e.Message; } return OperatonResult.Succeeded.ToString("F"); } public string runSql(string sql) { return tryCatch(() => { var runner = new CommandRunner(dbConnection); runner.Transact(new DbCommand[] { runner.BuildCommand(sql, null) }); }); } public IEnumerable<dynamic> runSqlDynamic(string sql) { var runner = new CommandRunner(dbConnection); return runner.ExecuteDynamic(sql, null); } protected DbConnection dbConnection; protected DBContext dbContext; protected enum OperatonResult { Succeeded = 1, Failed = 0 }; } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using Store.Models; using Store.Storage.Data; namespace Store.Storage.SqlServer { public class Client { public Client(DBContext _dbContext) { var fac = new Factory<SqlConnection>(); dbConnection = fac.Get(_dbContext); } protected string tryCatch(Action act) { try { act(); } catch (Exception e) { return e.Message; } return OperatonResult.Succeeded.ToString("F"); } internal string runSql(string sql) { return tryCatch(() => { var runner = new CommandRunner(dbConnection); runner.Transact(new DbCommand[] { runner.BuildCommand(sql, null) }); }); } internal IEnumerable<dynamic> runSqlDynamic(string sql) { var runner = new CommandRunner(dbConnection); return runner.ExecuteDynamic(sql, null); } protected DbConnection dbConnection; protected DBContext dbContext; protected enum OperatonResult { Succeeded = 1, Failed = 0 }; } }
mit
C#
71008d4db520c008be4ebca7947514a14ca10f00
Remove obsolete LoC
drew-r/Goose
GooseTest/Program.cs
GooseTest/Program.cs
using Goose; using NLua; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GooseTest { class Program { static void Main(string[] args) { VM vm = new VM(); vm.Compile("GooseFeatures", new string[]{ @" using System; namespace GooseInYourFaceWhatchaGonnaDo { public class MotherGoose { public MotherGoose() { Console.WriteLine(""Moo!""); } public string WhatsUpMotherGoose() { return ""Space and stuff""; } } }" }); vm.DoString("m = MotherGoose()"); Console.WriteLine(vm.DoString("return m:WhatsUpMotherGoose()")[0]); dynamic motherGoose = vm.DoString("return m")[0]; string whatsUp = motherGoose.WhatsUpMotherGoose(); Console.WriteLine(whatsUp); LuaFunction func = vm.DoString("return function(whatsUp) Console.WriteLine(whatsUp) end")[0] as LuaFunction; func.Call(whatsUp); Console.ReadLine(); } } }
using Goose; using NLua; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GooseTest { class Program { static void Main(string[] args) { VM vm = new VM(); vm.Compile("GooseFeatures", new string[]{ @" using System; namespace GooseInYourFaceWhatchaGonnaDo { public class MotherGoose { public MotherGoose() { Console.WriteLine(""Moo!""); } public string WhatsUpMotherGoose() { return ""Space and stuff""; } } }" }); vm.DoString("m = MotherGoose()"); Console.WriteLine(vm.DoString("return m:WhatsUpMotherGoose()")[0]); dynamic motherGoose = vm.DoString("return m")[0]; string whatsUp = motherGoose.WhatsUpMotherGoose(); Console.WriteLine(whatsUp); LuaFunction func = vm.DoString("return function(whatsUp) Console.WriteLine(whatsUp) end")[0] as LuaFunction; func.Call(whatsUp); vm.DoString("HelloWorld()"); Console.ReadLine(); } } }
mit
C#
04b6fa1483aae41933b885db5a2393073b2ccee8
fix slow bootstrap
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
Tweek.Drivers.Blob/BlobRulesDriver.cs
Tweek.Drivers.Blob/BlobRulesDriver.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using Engine.Drivers.Rules; using Newtonsoft.Json; using System.Text; namespace Tweek.Drivers.Blob { public class BlobRulesDriver : IRulesDriver, IDisposable { private readonly Uri _url; private readonly ISubject<Dictionary<string, RuleDefinition>> _subject; private readonly IDisposable _subscription; public BlobRulesDriver(Uri url, IWebClientFactory webClientFactory) { _url = url; _subject = new ReplaySubject<Dictionary<string, RuleDefinition>>(1); _subscription = Observable.Interval(TimeSpan.FromSeconds(30)) .StartWith(0) .SubscribeOn(TaskPoolScheduler.Default) .SelectMany(async _ => { using (var client = webClientFactory.Create()) { client.Encoding = Encoding.UTF8; return await client.DownloadStringTaskAsync(_url); } }) .DistinctUntilChanged() .Select(JsonConvert.DeserializeObject<Dictionary<string, RuleDefinition>>) .DistinctUntilChanged(new DictionaryEqualityComparer<string, RuleDefinition>(new RuleDefinitionComparer())) .Catch((Exception exception) => { Trace.TraceWarning($"Failed to update rules from {url}\r\n{exception}"); return Observable.Empty<Dictionary<string, RuleDefinition>>().Delay(TimeSpan.FromMinutes(1)); }) .Repeat() .Do(_subject) .Subscribe(x => OnRulesChange?.Invoke(x)); } public event Action<IDictionary<string, RuleDefinition>> OnRulesChange; public async Task<Dictionary<string, RuleDefinition>> GetAllRules() { return await _subject.FirstAsync(); } public void Dispose() { _subscription?.Dispose(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using Engine.Drivers.Rules; using Newtonsoft.Json; using System.Text; namespace Tweek.Drivers.Blob { public class BlobRulesDriver : IRulesDriver, IDisposable { private readonly Uri _url; private readonly ISubject<Dictionary<string, RuleDefinition>> _subject; private readonly IDisposable _subscription; public BlobRulesDriver(Uri url, IWebClientFactory webClientFactory) { _url = url; _subject = new ReplaySubject<Dictionary<string, RuleDefinition>>(1); _subscription = Observable.Interval(TimeSpan.FromSeconds(30)) .StartWith(0) .SelectMany(async _ => { using (var client = webClientFactory.Create()) { client.Encoding = Encoding.UTF8; return await client.DownloadStringTaskAsync(_url); } }) .DistinctUntilChanged() .Select(JsonConvert.DeserializeObject<Dictionary<string, RuleDefinition>>) .DistinctUntilChanged(new DictionaryEqualityComparer<string, RuleDefinition>(new RuleDefinitionComparer())) .Catch((Exception exception) => { Trace.TraceWarning($"Failed to update rules from {url}\r\n{exception}"); return Observable.Empty<Dictionary<string, RuleDefinition>>().Delay(TimeSpan.FromMinutes(1)); }) .Repeat() .Do(_subject) .Subscribe(x => OnRulesChange?.Invoke(x)); } public event Action<IDictionary<string, RuleDefinition>> OnRulesChange; public async Task<Dictionary<string, RuleDefinition>> GetAllRules() { return await _subject.FirstAsync(); } public void Dispose() { _subscription?.Dispose(); } } }
mit
C#
5e4a9d3489cef15d086ab458ade2b3cfaae95fd2
Update Week Model
morarj/ACStalkMarket,morarj/ACStalkMarket,morarj/ACStalkMarket
ACStalkMarket/ACStalkMarket/Models/Week.cs
ACStalkMarket/ACStalkMarket/Models/Week.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ACStalkMarket.Models { public class Week { public int Id { get; set; } public People People { get; set; } [Required] public int PeopleId { get; set; } public Town Town { get; set; } public int? TownId { get; set; } public WeekValues WeekValues { get; set; } [Required] public int WeekValuesId { get; set; } public WeekPattern WeekPattern { get; set; } [Required] [Display(Name = "Patrón")] public byte WeekPatternId { get; set; } [Required] [DataType(DataType.Date)] [Display(Name = "Fecha de Inicio")] // Must be monday public DateTime StartingDate { get; set; } [Required] [Range(0, byte.MaxValue)] [Display(Name = "Precio Inicial de los Turnips")] public byte TurnipStartingPrice { get; set; } [Required] [Range(0, int.MaxValue)] [Display(Name = "Inversión")] public int BellsInvestment { get; set; } [Required] [Display(Name = "Estado")] public bool WeekActive { get; set; } [Required] [Range(int.MinValue, int.MaxValue)] [Display(Name = "Ganancias")] public int Profit { get; set; } public void Map(Week week) { Id = week.Id; BellsInvestment = week.BellsInvestment; PeopleId = week.PeopleId; Profit = week.Profit; StartingDate = week.StartingDate; TownId = week.TownId; TurnipStartingPrice = week.TurnipStartingPrice; WeekActive = week.WeekActive; WeekPatternId = week.WeekPatternId; WeekValuesId = week.WeekValuesId; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ACStalkMarket.Models { public class Week { public int Id { get; set; } public People People { get; set; } [Required] public int PeopleId { get; set; } public Town Town { get; set; } public int? TownId { get; set; } public WeekValues WeekValues { get; set; } [Required] public int WeekValuesId { get; set; } public WeekPattern WeekPattern { get; set; } [Required] [Display(Name = "Patrón")] public byte WeekPatternId { get; set; } [Required] [DataType(DataType.Date)] [Display(Name = "Fecha de Inicio")] // Must be monday public DateTime StartingDate { get; set; } [Required] [Range(0, byte.MaxValue)] [Display(Name = "Precio Inicial de los Turnips")] public byte TurnipStartingPrice { get; set; } [Required] [Range(0, int.MaxValue)] [Display(Name = "Inversión")] public int BellsInvestment { get; set; } [Required] [Display(Name = "Estado")] public bool WeekActive { get; set; } [Required] [Range(0, int.MaxValue)] [Display(Name = "Ganancias")] public int Profit { get; set; } public void Map(Week week) { Id = week.Id; BellsInvestment = week.BellsInvestment; PeopleId = week.PeopleId; Profit = week.Profit; StartingDate = week.StartingDate; TownId = week.TownId; TurnipStartingPrice = week.TurnipStartingPrice; WeekActive = week.WeekActive; WeekPatternId = week.WeekPatternId; WeekValuesId = week.WeekValuesId; } } }
mit
C#
3bc99bdf93ec206b281011ceffe217db9b53996e
Add exception (only difference from default template)
abock/filed-bug-test-cases
Xamarin/bxc45742/ViewController.cs
Xamarin/bxc45742/ViewController.cs
using System; using AppKit; using Foundation; namespace UselessExceptions { public partial class ViewController : NSViewController { public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); throw new Exception ("USELESS"); // Do any additional setup after loading the view. } public override NSObject RepresentedObject { get { return base.RepresentedObject; } set { base.RepresentedObject = value; // Update the view, if already loaded. } } } }
using System; using AppKit; using Foundation; namespace UselessExceptions { public partial class ViewController : NSViewController { public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); // Do any additional setup after loading the view. } public override NSObject RepresentedObject { get { return base.RepresentedObject; } set { base.RepresentedObject = value; // Update the view, if already loaded. } } } }
mit
C#
77b0e1af90de739799f98927c7f5abe9c0c87aec
Add copyright to Vivek as requested in issue #215
l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto
Source/Shared/GlobalAssemblyInfo.cs
Source/Shared/GlobalAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: AssemblyInformationalVersion("1.3.0")]
using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: AssemblyInformationalVersion("1.3.0")]
bsd-3-clause
C#
afb1e89776fa9af0dc7a88927b04a103019c1164
Fix conversion bug in out dir provider
kzu/OctoFlow
src/OctoFlow.Console/DefaultProviders/OutDirProvider.cs
src/OctoFlow.Console/DefaultProviders/OutDirProvider.cs
/* Copyright 2014 Daniel Cazzulino 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 */ namespace OctoFlow { using CLAP; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; public class OutDirProvider : DefaultProvider { public override object GetDefault(VerbExecutionContext context) { var gitRoot = GitRepo.Find("."); if (string.IsNullOrEmpty(gitRoot)) return new DirectoryInfo(".").FullName; return gitRoot; } public override string Description { get { return "git repo root or current dir"; } } } }
/* Copyright 2014 Daniel Cazzulino 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 */ namespace OctoFlow { using CLAP; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; public class OutDirProvider : DefaultProvider { public override object GetDefault(VerbExecutionContext context) { var gitRoot = GitRepo.Find("."); if (string.IsNullOrEmpty(gitRoot)) return new DirectoryInfo("."); return gitRoot; } public override string Description { get { return "git repo root or current dir"; } } } }
apache-2.0
C#
5b38d3f71dccf2adddfb07e8b669837566ce847c
make DataGridView projected in provider
northwoodspd/UIA.Extensions,northwoodspd/UIA.Extensions
src/UIA.Extensions/AutomationProviders/Defaults/Tables/DataGridTableInformation.cs
src/UIA.Extensions/AutomationProviders/Defaults/Tables/DataGridTableInformation.cs
using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using UIA.Extensions.AutomationProviders.Interfaces.Tables; using UIA.Extensions.InternalExtensions; namespace UIA.Extensions.AutomationProviders.Defaults.Tables { public class DataGridTableInformation : TableInformation { protected readonly DataGridView DataGrid; public DataGridTableInformation(DataGridView dataGrid) { DataGrid = dataGrid; } public override Control Control { get { return DataGrid; } } public override List<string> Headers { get { return DataGrid.Columns.Select(HeaderTextOrColumnName).ToList(); } } public override List<RowInformation> Rows { get { return DataGrid.Rows.Select(DataGridRowInformation.FromRow).ToList(); } } public override bool CanSelectMultiple { get { return DataGrid.MultiSelect; } } public override int RowCount { get { return DataGrid.RowCount; } } public override int ColumnCount { get { return DataGrid.ColumnCount; } } private static string HeaderTextOrColumnName(DataGridViewColumn column) { return string.IsNullOrEmpty(column.HeaderText) ? column.Name : column.HeaderText; } } }
using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using UIA.Extensions.AutomationProviders.Interfaces.Tables; using UIA.Extensions.InternalExtensions; namespace UIA.Extensions.AutomationProviders.Defaults.Tables { public class DataGridTableInformation : TableInformation { private readonly DataGridView _dataGrid; public DataGridTableInformation(DataGridView dataGrid) { _dataGrid = dataGrid; } public override Control Control { get { return _dataGrid; } } public override List<string> Headers { get { return _dataGrid.Columns.Select(HeaderTextOrColumnName).ToList(); } } public override List<RowInformation> Rows { get { return _dataGrid.Rows.Select(DataGridRowInformation.FromRow).ToList(); } } public override bool CanSelectMultiple { get { return _dataGrid.MultiSelect; } } public override int RowCount { get { return _dataGrid.RowCount; } } public override int ColumnCount { get { return _dataGrid.ColumnCount; } } private static string HeaderTextOrColumnName(DataGridViewColumn column) { return string.IsNullOrEmpty(column.HeaderText) ? column.Name : column.HeaderText; } } }
mit
C#
900dfb6bab1861f0f9425452f04219ffd2c75120
fix minor bug
ravjotsingh9/DBLike
DBLike/ClientUI/Threads/FileSysWatchDog.cs
DBLike/ClientUI/Threads/FileSysWatchDog.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ClientUI.Threads { class FileSysWatchDog { Thread btnclicked; public void start() { btnclicked = new Thread(new ThreadStart(servicestart)); btnclicked.Start(); } public void stop() { btnclicked.Abort(); } private void servicestart() { DateTime lastedited = File.GetLastWriteTime(@"textDoc.txt"); while (true) { if (lastedited < File.GetLastWriteTime(@"textDoc.txt")) { lastedited = File.GetLastWriteTime(@"textDoc.txt"); MessageBox.Show("filechanged!"); break; } } btnclicked.Abort(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ClientUI.Threads { class FileSysWatchDog { Thread btnclicked; public void start() { btnclicked = new Thread(new ThreadStart(servicestart)); btnclicked.Start(); } public void stop() { btnclicked.Abort(); } private void servicestart() { DateTime lastedited = File.GetLastWriteTime(@"textDoc.txt"); while (true) { if (lastedited < File.GetLastWriteTime(@"textDoc.txt")) { lastedited = File.GetLastWriteTime(@"textDoc.txt"); MessageBox.Show("filechanged!"); break; } } btnclicked.Abort(); } } } }
apache-2.0
C#
54cdca9a7f51dad78a150c6e42af8b3789648074
Update Distributed Tenants Description. (#9820)
xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.Tenants/Manifest.cs
src/OrchardCore.Modules/OrchardCore.Tenants/Manifest.cs
using OrchardCore.Modules.Manifest; [assembly: Module( Name = "Tenants", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion )] [assembly: Feature( Id = "OrchardCore.Tenants", Name = "Tenants", Description = "Provides a way to manage tenants from the admin.", Category = "Infrastructure", DefaultTenantOnly = true )] [assembly: Feature( Id = "OrchardCore.Tenants.FileProvider", Name = "Static File Provider", Description = "Provides a way to serve independent static files for each tenant.", Category = "Infrastructure", DefaultTenantOnly = false )] [assembly: Feature( Id = "OrchardCore.Tenants.Distributed", Name = "Distributed Tenants", Description = "Keeps in sync tenants states, needs a distributed cache e.g. 'Redis Cache' and a stateless configuration, see: https://docs.orchardcore.net/en/dev/docs/reference/core/Shells/index.html", Category = "Distributed", DefaultTenantOnly = true )]
using OrchardCore.Modules.Manifest; [assembly: Module( Name = "Tenants", Author = ManifestConstants.OrchardCoreTeam, Website = ManifestConstants.OrchardCoreWebsite, Version = ManifestConstants.OrchardCoreVersion )] [assembly: Feature( Id = "OrchardCore.Tenants", Name = "Tenants", Description = "Provides a way to manage tenants from the admin.", Category = "Infrastructure", DefaultTenantOnly = true )] [assembly: Feature( Id = "OrchardCore.Tenants.FileProvider", Name = "Static File Provider", Description = "Provides a way to serve independent static files for each tenant.", Category = "Infrastructure", DefaultTenantOnly = false )] [assembly: Feature( Id = "OrchardCore.Tenants.Distributed", Name = "Distributed Tenants", Description = "Keeps in sync tenants states, needs a distributed cache e.g. 'Redis Cache'.", Category = "Distributed", DefaultTenantOnly = true )]
bsd-3-clause
C#
a99ba9192cd9be0fbab3d9730823cd5580b4888e
Fix for SOS2 calculator (for one element in array).
afish/MilpManager
Implementation/CompositeConstraints/SOS2Calculator.cs
Implementation/CompositeConstraints/SOS2Calculator.cs
using System; using System.Linq; using MilpManager.Abstraction; namespace MilpManager.Implementation.CompositeConstraints { public class SOS2Calculator : ICompositeConstraintCalculator { public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters, IVariable leftVariable, params IVariable[] rightVariable) { var zero = milpManager.FromConstant(0); var one = milpManager.FromConstant(1); var nonZeroes = new [] {leftVariable}.Concat(rightVariable).Select(v => v.Operation(OperationType.IsNotEqual, zero)).ToArray(); var nonZeroPairs = nonZeroes.Zip(nonZeroes.Skip(1), Tuple.Create).Select(pair => pair.Item1.Operation(OperationType.Conjunction, pair.Item2)).ToArray(); if (!nonZeroPairs.Any()) { nonZeroPairs = new[] {milpManager.FromConstant(0)}; } var nonZeroesCount = milpManager.Operation(OperationType.Addition, nonZeroes); milpManager.Set( ConstraintType.Equal, milpManager.Operation( OperationType.Disjunction, nonZeroesCount.Operation(OperationType.IsEqual, zero), nonZeroesCount.Operation(OperationType.IsEqual, one), milpManager.Operation(OperationType.Conjunction, nonZeroesCount.Operation(OperationType.IsEqual, milpManager.FromConstant(2)), milpManager.Operation(OperationType.Addition, nonZeroPairs).Operation(OperationType.IsEqual, one) ) ), one ); return leftVariable; } } }
using System; using System.Linq; using MilpManager.Abstraction; namespace MilpManager.Implementation.CompositeConstraints { public class SOS2Calculator : ICompositeConstraintCalculator { public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters, IVariable leftVariable, params IVariable[] rightVariable) { var zero = milpManager.FromConstant(0); var one = milpManager.FromConstant(1); var nonZeroes = new [] {leftVariable}.Concat(rightVariable).Select(v => v.Operation(OperationType.IsNotEqual, zero)).ToArray(); var nonZeroPairs = nonZeroes.Zip(nonZeroes.Skip(1), Tuple.Create).Select(pair => pair.Item1.Operation(OperationType.Conjunction, pair.Item2)).ToArray(); var nonZeroesCount = milpManager.Operation(OperationType.Addition, nonZeroes); milpManager.Set( ConstraintType.Equal, milpManager.Operation( OperationType.Disjunction, nonZeroesCount.Operation(OperationType.IsEqual, zero), nonZeroesCount.Operation(OperationType.IsEqual, one), milpManager.Operation(OperationType.Conjunction, nonZeroesCount.Operation(OperationType.IsEqual, milpManager.FromConstant(2)), milpManager.Operation(OperationType.Addition, nonZeroPairs).Operation(OperationType.IsEqual, one) ) ), one ); return leftVariable; } } }
mit
C#
7289da636f81c4bf4c307b42982cc308b3723d0e
Make integration test passed
alvachien/achihapi
test/hihapi.test/integrationtests/HomeDefineIntegrationTest.cs
test/hihapi.test/integrationtests/HomeDefineIntegrationTest.cs
using System; using System.Collections.Generic; using System.Text; using Xunit; using hihapi; using hihapi.Models; using System.Threading.Tasks; using System.Net.Http; using System.Net; namespace hihapi.test.integrationtests { public class HomeDefineIntegrationTest : BasicIntegrationTest { public HomeDefineIntegrationTest(CustomWebApplicationFactory<hihapi.Startup> factory) : base(factory) { } [Fact] public async Task TestCase1_UserA() { string token = await IdentityServerSetup.Instance.GetAccessTokenForUser(DataSetupUtility.UserA, DataSetupUtility.IntegrationTestPassword); var clientWithAuth = _factory.CreateClient(); clientWithAuth.SetBearerToken(token); // Step 1. Metadata request var metadata = await this._client.GetAsync("/api/$metadata"); Assert.Equal(HttpStatusCode.OK, metadata.StatusCode); var content = await metadata.Content.ReadAsStringAsync(); if (content.Length > 0) { // How to verify metadata? // TBD. } // Step 2. Read Home Defines - Non authority case var req1 = await this._client.GetAsync("/api/HomeDefines"); Assert.Equal(HttpStatusCode.Unauthorized, req1.StatusCode); // Step 3. Read Home Defines - Authority case var req2 = await clientWithAuth.GetAsync("/api/HomeDefines"); Assert.True(req2.IsSuccessStatusCode); } } }
using System; using System.Collections.Generic; using System.Text; using Xunit; using hihapi; using hihapi.Models; using System.Threading.Tasks; using System.Net.Http; using System.Net; namespace hihapi.test.integrationtests { public class HomeDefineIntegrationTest : BasicIntegrationTest { public HomeDefineIntegrationTest(CustomWebApplicationFactory<hihapi.Startup> factory) : base(factory) { } [Fact] public async Task TestCase1_UserA() { string token = await IdentityServerSetup.Instance.GetAccessTokenForUser(DataSetupUtility.UserA, DataSetupUtility.IntegrationTestPassword); var client = _factory.CreateClient(); client.SetBearerToken(token); // Step 1. Metadata request var metadata = await client.GetAsync("/api/$metadata"); Assert.Equal(HttpStatusCode.OK, metadata.StatusCode); var content = await metadata.Content.ReadAsStringAsync(); if (content.Length > 0) { // How to verify metadata? // TBD. } } } }
mit
C#
56837b3dceca9449e53b5f3095ecbaf5e2f75be3
rename test to more accurately suit its purpose
OlegKleyman/AlphaDev,OlegKleyman/AlphaDev,OlegKleyman/AlphaDev
tests/integration/AlphaDev.Web.Tests.Integration/Features/Authorization_feature.cs
tests/integration/AlphaDev.Web.Tests.Integration/Features/Authorization_feature.cs
using LightBDD.Framework; using LightBDD.Framework.Scenarios.Basic; using LightBDD.Framework.Scenarios.Extended; using LightBDD.XUnit2; namespace AlphaDev.Web.Tests.Integration.Features { [FeatureDescription( @"In order to not allow everyone to access the admin area As a user I want to only be allowed to access the admin area if I have the authority")] public partial class Authorization_feature { [Scenario] public void Redirect_unauthenticated_users_to_login_page() { Runner.RunScenario( _ => CommonSteps.Given_i_am_a_user(), _ => And_I_am_not_logged_in(), _=> When_I_visit_the_admin_area(), _=> Then_I_am_redirected_to_a_login_page()); } } }
using LightBDD.Framework; using LightBDD.Framework.Scenarios.Basic; using LightBDD.Framework.Scenarios.Extended; using LightBDD.XUnit2; namespace AlphaDev.Web.Tests.Integration.Features { [Label("FEAT-1")] [FeatureDescription( @"In order to not allow everyone to access the admin area As a user I want to only be allowed to access the admin area if I have the authority")] public partial class Authorization_feature { [Scenario] public void Template_basic_scenario() { Runner.RunScenario( _ => CommonSteps.Given_i_am_a_user(), _ => And_I_am_not_logged_in(), _=> When_I_visit_the_admin_area(), _=> Then_I_am_redirected_to_a_login_page()); } } }
unlicense
C#
5818e76c56b0a6a029b59f190e36f30512b27452
return FileChanges for commit details
ZanyGnu/GitRepoStats
RepoStats/Startup.cs
RepoStats/Startup.cs
 namespace RepoStats { using LibGit2Sharp; using Microsoft.Owin; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using Owin; using ProtoBuf; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Web.Http; public class Startup { public void Configuration(IAppBuilder app) { // Remap '/' to '.\defaults\'. // Turns on static files and default files. app.UseFileServer(new FileServerOptions() { RequestPath = PathString.Empty, FileSystem = new PhysicalFileSystem(@".\"), }); HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute("Default", "{controller}/{checkinID}", new { controller = "Checkin", checkinID = RouteParameter.Optional }); config.Formatters.XmlFormatter.UseXmlSerializer = true; config.Formatters.Remove(config.Formatters.JsonFormatter); // config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; app.UseWebApi(config); } } public class CheckinController : ApiController { public string guid = Guid.NewGuid().ToString(); public CheckinController() { } // Gets [HttpGet] public List<FileChanges> Get(string checkinId) { Repository repo = new Repository(ConfigurationManager.AppSettings["RepoRoot"]); //Commit commit = repo.Lookup<Commit>(checkinId); //return commit.Message; string patchDirectory = Path.Combine(repo.Info.Path, "patches"); List<FileChanges> fileChanges = null; string patchFileName = patchDirectory + "/" + checkinId + ".bin"; fileChanges = Serializer.Deserialize<List<FileChanges>>(File.OpenRead(patchFileName)); return fileChanges; } } }
 namespace RepoStats { using Microsoft.Owin; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using Owin; using System; using System.Web.Http; public class Startup { public void Configuration(IAppBuilder app) { // Remap '/' to '.\defaults\'. // Turns on static files and default files. app.UseFileServer(new FileServerOptions() { RequestPath = PathString.Empty, FileSystem = new PhysicalFileSystem(@".\"), }); HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute("Default", "{controller}/{checkinID}", new { controller = "Checkin", checkinID = RouteParameter.Optional }); config.Formatters.XmlFormatter.UseXmlSerializer = true; config.Formatters.Remove(config.Formatters.JsonFormatter); // config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; app.UseWebApi(config); } } public class CheckinController : ApiController { public CheckinController() { } // Gets [HttpGet] public String Get(string checkinId) { return "Hello world"; } } }
mit
C#
1ff410d40d5ccee7208a9c39b0faf754dea36e73
change to MachineName
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices/Session/SessionDetails.cs
src/PowerShellEditorServices/Session/SessionDetails.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Utility; using System; using System.Management.Automation; using System.Collections; namespace Microsoft.PowerShell.EditorServices.Session { /// <summary> /// Provides details about the current PowerShell session. /// </summary> public class SessionDetails { /// <summary> /// Gets the process ID of the current process. /// </summary> public int? ProcessId { get; private set; } /// <summary> /// Gets the name of the current computer. /// </summary> public string ComputerName { get; private set; } /// <summary> /// Gets the current PSHost instance ID. /// </summary> public Guid? InstanceId { get; private set; } /// <summary> /// Creates an instance of SessionDetails using the information /// contained in the PSObject which was obtained using the /// PSCommand returned by GetDetailsCommand. /// </summary> /// <param name="detailsObject"></param> public SessionDetails(PSObject detailsObject) { Validate.IsNotNull(nameof(detailsObject), detailsObject); Hashtable innerHashtable = detailsObject.BaseObject as Hashtable; this.ProcessId = (int)innerHashtable["processId"] as int?; this.ComputerName = innerHashtable["computerName"] as string; this.InstanceId = innerHashtable["instanceId"] as Guid?; } /// <summary> /// Gets the PSCommand that gathers details from the /// current session. /// </summary> /// <returns>A PSCommand used to gather session details.</returns> public static PSCommand GetDetailsCommand() { PSCommand infoCommand = new PSCommand(); infoCommand.AddScript( "@{ 'computerName' = if ([Environment]::MachineName) {[Environment]::MachineName} else {'localhost'}; 'processId' = $PID; 'instanceId' = $host.InstanceId }"); return infoCommand; } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Utility; using System; using System.Management.Automation; using System.Collections; namespace Microsoft.PowerShell.EditorServices.Session { /// <summary> /// Provides details about the current PowerShell session. /// </summary> public class SessionDetails { /// <summary> /// Gets the process ID of the current process. /// </summary> public int? ProcessId { get; private set; } /// <summary> /// Gets the name of the current computer. /// </summary> public string ComputerName { get; private set; } /// <summary> /// Gets the current PSHost instance ID. /// </summary> public Guid? InstanceId { get; private set; } /// <summary> /// Creates an instance of SessionDetails using the information /// contained in the PSObject which was obtained using the /// PSCommand returned by GetDetailsCommand. /// </summary> /// <param name="detailsObject"></param> public SessionDetails(PSObject detailsObject) { Validate.IsNotNull(nameof(detailsObject), detailsObject); Hashtable innerHashtable = detailsObject.BaseObject as Hashtable; this.ProcessId = (int)innerHashtable["processId"] as int?; this.ComputerName = innerHashtable["computerName"] as string; this.InstanceId = innerHashtable["instanceId"] as Guid?; } /// <summary> /// Gets the PSCommand that gathers details from the /// current session. /// </summary> /// <returns>A PSCommand used to gather session details.</returns> public static PSCommand GetDetailsCommand() { PSCommand infoCommand = new PSCommand(); infoCommand.AddScript( "@{ 'computerName' = if ($ExecutionContext.Host.Runspace.ConnectionInfo) {$ExecutionContext.Host.Runspace.ConnectionInfo.ComputerName} else {'localhost'}; 'processId' = $PID; 'instanceId' = $host.InstanceId }"); return infoCommand; } } }
mit
C#
323aa05d7fd2549150de89226d802886ed756127
fix multi-targeting error
dansiegel/Prism.Plugin.Popups,dansiegel/Prism.Plugin.Popups
src/Prism.Plugin.Popups/PopupRegistrationExtensions.cs
src/Prism.Plugin.Popups/PopupRegistrationExtensions.cs
using System; using System.Reflection; using Prism.Behaviors; using Prism.Ioc; using Prism.Navigation; using Rg.Plugins.Popup.Contracts; using Rg.Plugins.Popup.Services; namespace Prism.Plugin.Popups { public static class PopupRegistrationExtensions { public static void RegisterPopupNavigationService<TService>(this IContainerRegistry containerRegistry) where TService : PopupPageNavigationService { containerRegistry.RegisterInstance<IPopupNavigation>(PopupNavigation.Instance); containerRegistry.Register<INavigationService, TService>(PrismApplicationBase.NavigationServiceName); containerRegistry.RegisterSingleton<IPageBehaviorFactory, PopupPageBehaviorFactory>(); if (IsDryIocContainer(containerRegistry)) containerRegistry.Register<INavigationService, TService>(); } public static void RegisterPopupNavigationService(this IContainerRegistry containerRegistry) => containerRegistry.RegisterPopupNavigationService<PopupPageNavigationService>(); public static bool IsDryIocContainer(IContainerRegistry containerRegistry) { var regType = containerRegistry.GetType(); var propInfo = regType.GetRuntimeProperty("Instance"); #if NETSTANDARD1_0 return propInfo?.PropertyType.FullName.Equals("DryIoc.IContainer", StringComparison.OrdinalIgnoreCase) ?? false; #else return propInfo?.PropertyType.FullName.Equals("DryIoc.IContainer", StringComparison.InvariantCultureIgnoreCase) ?? false; #endif } } }
using System; using System.Reflection; using Prism.Behaviors; using Prism.Ioc; using Prism.Navigation; using Rg.Plugins.Popup.Contracts; using Rg.Plugins.Popup.Services; namespace Prism.Plugin.Popups { public static class PopupRegistrationExtensions { public static void RegisterPopupNavigationService<TService>(this IContainerRegistry containerRegistry) where TService : PopupPageNavigationService { containerRegistry.RegisterInstance<IPopupNavigation>(PopupNavigation.Instance); containerRegistry.Register<INavigationService, TService>(PrismApplicationBase.NavigationServiceName); containerRegistry.RegisterSingleton<IPageBehaviorFactory, PopupPageBehaviorFactory>(); if (IsDryIocContainer(containerRegistry)) containerRegistry.Register<INavigationService, TService>(); } public static void RegisterPopupNavigationService(this IContainerRegistry containerRegistry) => containerRegistry.RegisterPopupNavigationService<PopupPageNavigationService>(); public static bool IsDryIocContainer(IContainerRegistry containerRegistry) { var regType = containerRegistry.GetType(); var propInfo = regType.GetRuntimeProperty("Instance"); return propInfo?.PropertyType.FullName.Equals("DryIoc.IContainer", StringComparison.InvariantCultureIgnoreCase) ?? false; } } }
mit
C#
33405b8f26420fd930dfcd50c7d217b077003f11
Fix typo
lukeryannetnz/quartznet-dynamodb,lukeryannetnz/quartznet-dynamodb
src/QuartzNET-DynamoDB/DataModel/DynamoTriggerGroup.cs
src/QuartzNET-DynamoDB/DataModel/DynamoTriggerGroup.cs
using System; using System.Collections.Generic; using Amazon.DynamoDBv2.Model; using Quartz.DynamoDB.DataModel.Storage; namespace Quartz.DynamoDB.DataModel { /// <summary> /// A wrapper class for a Quartz Trigger Group instance that can be serialized and stored in Amazon DynamoDB. /// </summary> public class DynamoTriggerGroup : IInitialisableFromDynamoRecord, IConvertibleToDynamoRecord, IDynamoTableType { public string Name { get; set; } public DynamoTriggerGroupState State { get; set; } public string DynamoTableName { get { return DynamoConfiguration.TriggerGroupTableName; } } public Dictionary<string, AttributeValue> Key { get { return new Dictionary<string, AttributeValue> { { "Name", new AttributeValue (){ S = Name } } }; } } public Dictionary<string, AttributeValue> ToDynamo() { Dictionary<string, AttributeValue> record = new Dictionary<string, AttributeValue>(); record.Add("Name", AttributeValueHelper.StringOrNull(Name)); record.Add("State", AttributeValueHelper.StringOrNull(State.ToString())); return record; } public void InitialiseFromDynamoRecord(Dictionary<string, AttributeValue> record) { Name = record["Name"].S; State = (DynamoTriggerGroupState)Enum.Parse(typeof(DynamoTriggerGroupState), record["State"].S); } } }
using System; using System.Collections.Generic; using Amazon.DynamoDBv2.Model; using Quartz.DynamoDB.DataModel.Storage; namespace Quartz.DynamoDB.DataModel /// <summary> /// A wrapper class for a Quartz Trigger Group instance that can be serialized and stored in Amazon DynamoDB. /// </summary> public class DynamoTriggerGroup : IInitialisableFromDynamoRecord, IConvertibleToDynamoRecord, IDynamoTableType { public string Name { get; set; } public DynamoTriggerGroupState State { get; set; } public string DynamoTableName { get { return DynamoConfiguration.TriggerGroupTableName; } } public Dictionary<string, AttributeValue> Key { get { return new Dictionary<string, AttributeValue> { { "Name", new AttributeValue (){ S = Name } } }; } } public Dictionary<string, AttributeValue> ToDynamo() { Dictionary<string, AttributeValue> record = new Dictionary<string, AttributeValue>(); record.Add("Name", AttributeValueHelper.StringOrNull(Name)); record.Add("State", AttributeValueHelper.StringOrNull(State.ToString())); return record; } public void InitialiseFromDynamoRecord(Dictionary<string, AttributeValue> record) { Name = record["Name"].S; State = (DynamoTriggerGroupState)Enum.Parse(typeof(DynamoTriggerGroupState), record["State"].S); } } }
apache-2.0
C#
b72752945b501430e86b11c92eeb23782f1e8786
Align test class name with file name
atifaziz/A1,atifaziz/A1
A1.Tests/ColRowTests.cs
A1.Tests/ColRowTests.cs
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace A1.Tests { using Xunit; public class ColRowTests { [Fact] public void InitEmpty() { var colrow = new ColRow(); Assert.Equal(0, colrow.Col); Assert.Equal(0, colrow.Row); } [Theory] [InlineData(12, 34)] [InlineData(45, 67)] [InlineData(67, 89)] public void Init(int col, int row) { var colrow = new ColRow(col, row); Assert.Equal(col, colrow.Col); Assert.Equal(row, colrow.Row); } [Theory] [InlineData("A1" , 0, 0)] [InlineData("B1" , 1, 0)] [InlineData("C1" , 2, 0)] [InlineData("A5" , 0, 4)] [InlineData("B5" , 1, 4)] [InlineData("C5" , 2, 4)] [InlineData("AA1" , 26, 0)] [InlineData("AB2" , 27, 1)] [InlineData("AC3" , 28, 2)] [InlineData("ABC43", 730, 42)] [InlineData("DEF43", 2839, 42)] [InlineData("GHI43", 4948, 42)] public void ParseA1(string s, int col, int row) { var colrow = ColRow.ParseA1(s); Assert.Equal(col, colrow.Col); Assert.Equal(row, colrow.Row); } } }
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace A1.Tests { using Xunit; public class ColRowTest { [Fact] public void InitEmpty() { var colrow = new ColRow(); Assert.Equal(0, colrow.Col); Assert.Equal(0, colrow.Row); } [Theory] [InlineData(12, 34)] [InlineData(45, 67)] [InlineData(67, 89)] public void Init(int col, int row) { var colrow = new ColRow(col, row); Assert.Equal(col, colrow.Col); Assert.Equal(row, colrow.Row); } [Theory] [InlineData("A1" , 0, 0)] [InlineData("B1" , 1, 0)] [InlineData("C1" , 2, 0)] [InlineData("A5" , 0, 4)] [InlineData("B5" , 1, 4)] [InlineData("C5" , 2, 4)] [InlineData("AA1" , 26, 0)] [InlineData("AB2" , 27, 1)] [InlineData("AC3" , 28, 2)] [InlineData("ABC43", 730, 42)] [InlineData("DEF43", 2839, 42)] [InlineData("GHI43", 4948, 42)] public void ParseA1(string s, int col, int row) { var colrow = ColRow.ParseA1(s); Assert.Equal(col, colrow.Col); Assert.Equal(row, colrow.Row); } } }
apache-2.0
C#
79799c4dd8e910e6c372302ac3a499aec1b6e6e3
Remove unused namespaces
peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype
src/Glimpse.Common/_SystemWeb/Glimpse.cs
src/Glimpse.Common/_SystemWeb/Glimpse.cs
#if SystemWeb using Microsoft.Extensions.DependencyInjection; namespace Glimpse { public static class Glimpse { public static GlimpseServiceCollectionBuilder Start() { return Start(new ServiceCollection()); } public static GlimpseServiceCollectionBuilder Start(IServiceCollection serviceProvider) { return serviceProvider.AddGlimpse(); } public static GlimpseServiceCollectionBuilder Start(bool autoRegisterComponents) { return Start(new ServiceCollection(), autoRegisterComponents); } public static GlimpseServiceCollectionBuilder Start(IServiceCollection serviceProvider, bool autoRegisterComponents) { return serviceProvider.AddGlimpse(autoRegisterComponents); } } } #endif
#if SystemWeb using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; namespace Glimpse { public static class Glimpse { public static GlimpseServiceCollectionBuilder Start() { return Start(new ServiceCollection()); } public static GlimpseServiceCollectionBuilder Start(IServiceCollection serviceProvider) { return serviceProvider.AddGlimpse(); } public static GlimpseServiceCollectionBuilder Start(bool autoRegisterComponents) { return Start(new ServiceCollection(), autoRegisterComponents); } public static GlimpseServiceCollectionBuilder Start(IServiceCollection serviceProvider, bool autoRegisterComponents) { return serviceProvider.AddGlimpse(autoRegisterComponents); } } } #endif
mit
C#
f00d6549d400f32f00ebcc63426a7e52a7c0cd86
solve chain searching for Slot by provider extension
furore-fhir/spark,furore-fhir/spark,furore-fhir/spark
src/Spark.Engine/Model/SparkModelInfo.cs
src/Spark.Engine/Model/SparkModelInfo.cs
using System; using Hl7.Fhir.Model; using System.Collections.Generic; using System.Linq; using static Hl7.Fhir.Model.ModelInfo; namespace Spark.Engine.Model { public static class SparkModelInfo { public static List<SearchParamDefinition> SparkSearchParameters = ModelInfo.SearchParameters.Union( new List<SearchParamDefinition>() { new SearchParamDefinition() {Resource = "Composition", Name = "custodian", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.custodian" }, XPath = "f:Composition/f:custodian", Expression = "Composition.custodian", Target = new ResourceType[] { ResourceType.Organization} } , new SearchParamDefinition() {Resource = "Composition", Name = "eventdetail", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.event.detail" }, XPath = "f:Composition/f:event/f:detail", Expression = "Composition.event.detail", Target = Enum.GetValues(typeof(ResourceType)).Cast<ResourceType>().ToArray() } , new SearchParamDefinition() {Resource = "Encounter", Name = "serviceprovider", Description = @"Organization that provides the Encounter services.", Type = SearchParamType.Reference, Path = new[] {"Encounter.serviceProvider"}, XPath = "f:Encounter/f:serviceProvider",Expression = "Encounter.serviceProvider", Target = new ResourceType[] { ResourceType.Organization} } , new SearchParamDefinition() {Resource = "Slot", Name = "provider", Description = @"Search Slot by provider extension", Type = SearchParamType.Reference, Path = new string[] { @"Slot.extension(url=http://fhir.blackpear.com/era/Slot/provider).valueReference" }, Target = new ResourceType[] { ResourceType.Organization}} }).ToList(); } }
using System; using Hl7.Fhir.Model; using System.Collections.Generic; using System.Linq; using static Hl7.Fhir.Model.ModelInfo; namespace Spark.Engine.Model { public static class SparkModelInfo { public static List<SearchParamDefinition> SparkSearchParameters = ModelInfo.SearchParameters.Union( new List<SearchParamDefinition>() { new SearchParamDefinition() {Resource = "Composition", Name = "custodian", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.custodian" }, XPath = "f:Composition/f:custodian", Expression = "Composition.custodian", Target = new ResourceType[] { ResourceType.Organization} } , new SearchParamDefinition() {Resource = "Composition", Name = "eventdetail", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.event.detail" }, XPath = "f:Composition/f:event/f:detail", Expression = "Composition.event.detail", Target = Enum.GetValues(typeof(ResourceType)).Cast<ResourceType>().ToArray() } , new SearchParamDefinition() {Resource = "Encounter", Name = "serviceprovider", Description = @"Organization that provides the Encounter services.", Type = SearchParamType.Reference, Path = new[] {"Encounter.serviceProvider"}, XPath = "f:Encounter/f:serviceProvider",Expression = "Encounter.serviceProvider", Target = new ResourceType[] { ResourceType.Organization} } , new SearchParamDefinition() {Resource = "Slot", Name = "provider", Description = @"Search Slot by provider extension", Type = SearchParamType.Reference, Path = new string[] { @"Slot.extension(url=http://fhir.blackpear.com/era/Slot/provider).valueReference" } } }).ToList(); } }
bsd-3-clause
C#
4175affe0900b0d50bc1bfdb91e924d88ca243d0
Change MOTD button text to "MOTD *updated*" on new MOTD.
fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game
game/client/ui/shell/motd.cs
game/client/ui/shell/motd.cs
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ if(!isObject(MOTDconn)) { new HttpObject(MOTDconn); $MOTD::Text = ""; } function MotdWindow::onAdd(%this) { %this.refresh(); } function MotdWindow::onWake(%this) { %this.setMotd(); } function MotdWindow::refresh(%this) { $MOTD::Text = ""; MotdText.setText("--- FETCHING http://ethernet.wasted.ch/motd ---\n"); MOTDconn.get("ethernet.wasted.ch:80", "/motd"); } function MotdWindow::setMotd() { //echo("MotdWindow::setMotd()"); if($MOTD::Text $= "") return; MotdText.setText($MOTD::Text); if(MotdWindow.isAwake()) { RootMenuMotdButton.setText("MOTD"); hilightControl(RootMenuMotdButton, false); $Pref::MOTD::Text = $MOTD::Text; } else if($MOTD::Text !$= $Pref::MOTD::Text) { RootMenuMotdButton.setText("MOTD *updated*"); hilightControl(RootMenuMotdButton, true); } } // To prevent console spam function MotdWindow::onAddedAsWindow(%this) { } // To prevent console spam function MotdWindow::onRemovedAsWindow(%this) { } //------------------------------------------------------------------------------ function MOTDconn::onLine(%this, %line) { //error("MOTDconn::onLine()"); $MOTD::Text = $MOTD::Text @ %line @ "\n"; } function MOTDconn::onDNSResolved(%this) { //error("MOTDconn::onDNSResolved()"); MotdText.addText("--- HOST FOUND ---\n", true); } function MOTDconn::onDNSFailed(%this) { //error("MOTDconn::onDNSFailed()"); MotdText.addText("--- HOST NOT FOUND ---\n", true); } function MOTDconn::onConnected(%this) { //error("MOTDconn::onConnected()"); MotdText.addText("--- BEGIN TRANSMISSION ---\n", true); } function MOTDconn::onConnectFailed(%this) { //error("MOTDconn::onConnectFailed()"); MotdText.addText("--- CONNECTION FAILED ---\n", true); } function MOTDconn::onDisconnect(%this) { //error("MOTDconn::onDisconnect()"); if($MOTD::Text $= "") MotdText.addText("\n--- TRANSMISSION EMPTY ---", true); else MotdWindow.setMotd(); }
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ if(!isObject(MOTDconn)) { new HttpObject(MOTDconn); $MOTD::Text = ""; } function MotdWindow::onAdd(%this) { %this.refresh(); } function MotdWindow::onWake(%this) { %this.setMotd(); } function MotdWindow::refresh(%this) { $MOTD::Text = ""; MotdText.setText("--- FETCHING http://ethernet.wasted.ch/motd ---\n"); MOTDconn.get("ethernet.wasted.ch:80", "/motd"); } function MotdWindow::setMotd() { //echo("MotdWindow::setMotd()"); if($MOTD::Text $= "") return; MotdText.setText($MOTD::Text); if(MotdWindow.isAwake()) { hilightControl(RootMenuMotdButton, false); $Pref::MOTD::Text = $MOTD::Text; } else if($MOTD::Text !$= $Pref::MOTD::Text) { hilightControl(RootMenuMotdButton, true); } } // To prevent console spam function MotdWindow::onAddedAsWindow(%this) { } // To prevent console spam function MotdWindow::onRemovedAsWindow(%this) { } //------------------------------------------------------------------------------ function MOTDconn::onLine(%this, %line) { //error("MOTDconn::onLine()"); $MOTD::Text = $MOTD::Text @ %line @ "\n"; } function MOTDconn::onDNSResolved(%this) { //error("MOTDconn::onDNSResolved()"); MotdText.addText("--- HOST FOUND ---\n", true); } function MOTDconn::onDNSFailed(%this) { //error("MOTDconn::onDNSFailed()"); MotdText.addText("--- HOST NOT FOUND ---\n", true); } function MOTDconn::onConnected(%this) { //error("MOTDconn::onConnected()"); MotdText.addText("--- BEGIN TRANSMISSION ---\n", true); } function MOTDconn::onConnectFailed(%this) { //error("MOTDconn::onConnectFailed()"); MotdText.addText("--- CONNECTION FAILED ---\n", true); } function MOTDconn::onDisconnect(%this) { //error("MOTDconn::onDisconnect()"); if($MOTD::Text $= "") MotdText.addText("\n--- TRANSMISSION EMPTY ---", true); else MotdWindow.setMotd(); }
lgpl-2.1
C#
8046ae1a2e5eab8bfcc61d8c46e6a8024b8df1f1
Move from implicit to explicit serialisation of object members
wyldphyre/KaomojiTray
KaomojiTray/KaomojiTrayApplicationContext.cs
KaomojiTray/KaomojiTrayApplicationContext.cs
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.Serialization; namespace KaomojiTray { class KaomojiTrayApplicationContext : SystemTrayApplicationContext { public KaomojiLibrary Library { get; private set; } public KaomojiTrayApplicationContext() : base() { SetIconImage(KaomojiTray.Properties.Resources.Close_16); var Assembly = System.Reflection.Assembly.GetExecutingAssembly(); using (var StreamReader = new StreamReader(Assembly.GetManifestResourceStream(Assembly.GetName().Name + ".kaomoji.json"))) { this.Library = Newtonsoft.Json.JsonConvert.DeserializeObject<KaomojiLibrary>(StreamReader.ReadToEnd()); } this.IconClickEvent += KaomojiTrayApplicationContext_IconClickEvent; AddMenuItem("Exit", null, ExitMenuItemClick); } void KaomojiTrayApplicationContext_IconClickEvent() { ShowPicker(); } private void ShowPicker() { var Window = new MainWindow(); Window.Title = "Kaomoji Library"; Window.LoadLibrary(Library); Window.Show(); } private void ExitMenuItemClick(object sender, EventArgs e) { ExitApplication(); } } [DataContract] public class KaomojiLibrary { [DataMember] public List<KaomojiCategory> category { get; set; } } [DataContract] public class KaomojiCategory { [DataMember] public string id { get; set; } [DataMember] public List<KaomojiSection> sections { get; set; } } [DataContract] public class KaomojiSection { [DataMember] public string id { get; set; } [DataMember] public List<string> kaomoji { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; namespace KaomojiTray { class KaomojiTrayApplicationContext : SystemTrayApplicationContext { public KaomojiLibrary Library { get; private set; } public KaomojiTrayApplicationContext() : base() { SetIconImage(KaomojiTray.Properties.Resources.Close_16); var Assembly = System.Reflection.Assembly.GetExecutingAssembly(); using (var StreamReader = new StreamReader(Assembly.GetManifestResourceStream(Assembly.GetName().Name + ".kaomoji.json"))) { this.Library = Newtonsoft.Json.JsonConvert.DeserializeObject<KaomojiLibrary>(StreamReader.ReadToEnd()); } this.IconClickEvent += KaomojiTrayApplicationContext_IconClickEvent; AddMenuItem("Exit", null, ExitMenuItemClick); } void KaomojiTrayApplicationContext_IconClickEvent() { ShowPicker(); } private void ShowPicker() { var Window = new MainWindow(); Window.Title = "Kaomoji Library"; Window.LoadLibrary(Library); Window.Show(); } private void ExitMenuItemClick(object sender, EventArgs e) { ExitApplication(); } } public class KaomojiLibrary { public List<KaomojiCategory> category { get; set; } } public class KaomojiCategory { public string id { get; set; } public List<KaomojiSection> sections { get; set; } } public class KaomojiSection { public string id { get; set; } public List<string> kaomoji { get; set; } } }
apache-2.0
C#
b1f75b16d417105d8c2e16aed6cda9e16345a72f
Update model
sakapon/Bellona.Analysis
Samples/ColorsSample/ColorsWpf/AppModel.cs
Samples/ColorsSample/ColorsWpf/AppModel.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using Bellona.Clustering; namespace ColorsWpf { public class AppModel { public ColorCluster[] ColorClusters { get; private set; } public AppModel() { var colors = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static) .Where(p => p.PropertyType == typeof(Color)) .Select(p => (Color)p.GetValue(null)) .Where(c => c.A == 255) // Exclude Transparent. .ToArray(); var model = new ClusteringModel<Color>(c => new double[] { c.R, c.G, c.B }); model.Train(colors); ColorClusters = model.Clusters .Select(c => c.Records .Select(r => new ColorInfo(r.Element)) .OrderBy(ci => ci.Color.GetHue()) .ToArray()) .Select((cs, i) => new ColorCluster { Id = i, Colors = cs }) .OrderBy(cc => cc.Colors.Average(c => c.Color.GetHue())) .ToArray(); } } public struct ColorCluster { public int Id { get; set; } public ColorInfo[] Colors { get; set; } } [DebuggerDisplay(@"\{{Color}\}")] public class ColorInfo { public Color Color { get; private set; } public string Name { get { return Color.Name; } } public string RGB { get { return string.Format("#{0:X2}{1:X2}{2:X2}", Color.R, Color.G, Color.B); } } public ColorInfo(Color color) { Color = color; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using Bellona.Clustering; namespace ColorsWpf { public class AppModel { public ColorInfo[][] ColorClusters { get; private set; } public AppModel() { var colors = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static) .Where(p => p.PropertyType == typeof(Color)) .Select(p => (Color)p.GetValue(null)) .Where(c => c.A == 255) // Exclude Transparent. .ToArray(); var model = new ClusteringModel<Color>(c => new double[] { c.R, c.G, c.B }); model.Train(colors); ColorClusters = model.Clusters .Select(c => c.Records .Select(r => new ColorInfo(r.Element)) .OrderBy(ci => ci.Color.GetHue()) .ToArray()) .OrderBy(cs => cs.Average(c => c.Color.GetHue())) .ToArray(); } } [DebuggerDisplay(@"\{{Color}\}")] public class ColorInfo { public Color Color { get; private set; } public string RGB { get { return string.Format("#{0:X2}{1:X2}{2:X2}", Color.R, Color.G, Color.B); } } public ColorInfo(Color color) { Color = color; } } }
mit
C#
2385711b1377e2fb23cbf9f0f1b2d28b067d18e8
Fix Travis CI
lecaillon/Evolve
test/Evolve.Test.Utilities/PostgreSqlDockerContainer.cs
test/Evolve.Test.Utilities/PostgreSqlDockerContainer.cs
namespace Evolve.Test.Utilities { public class PostgreSqlDockerContainer : IDockerContainer { private DockerContainer _container; public string Id => _container.Id; public string ExposedPort => "5432"; public string HostPort => "5433"; public string DbName => "my_database"; public string DbPwd => "Password12!"; // AppVeyor public string DbUser => "postgres"; public bool Start() { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "postgres", Tag = "alpine", Name = "postgres-evolve", Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort }).Build(); return _container.Start(); } public void Remove() => _container.Remove(); public bool Stop() => _container.Stop(); public void Dispose() => _container.Dispose(); } }
namespace Evolve.Test.Utilities { public class PostgreSqlDockerContainer : IDockerContainer { private DockerContainer _container; public string Id => _container.Id; public string ExposedPort => "5432"; public string HostPort => "5432"; public string DbName => "my_database"; public string DbPwd => "Password12!"; // AppVeyor public string DbUser => "postgres"; public bool Start() { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "postgres", Tag = "alpine", Name = "postgres-evolve", Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort }).Build(); return _container.Start(); } public void Remove() => _container.Remove(); public bool Stop() => _container.Stop(); public void Dispose() => _container.Dispose(); } }
mit
C#
36a3ade83e36ad736d85fc3acf29232eb0db935b
Make LuaDirectory readonly.
YuvalItzchakov/aerospike-client-csharp
AerospikeDemo/LuaExample.cs
AerospikeDemo/LuaExample.cs
/******************************************************************************* * Copyright 2012-2014 by Aerospike. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. ******************************************************************************/ using System; using System.IO; using Aerospike.Client; namespace Aerospike.Demo { public class LuaExample { private static readonly string LuaDirectory; static LuaExample() { // Adjust path for whether using x64/x86 or AnyCPU compile target. string dir = @"..\..\..\udf"; if (! Directory.Exists(dir)) { dir = @"..\..\udf"; } LuaDirectory = dir; #if (! LITE) LuaConfig.PackagePath = LuaDirectory + @"\?.lua"; #endif } public static void Register(AerospikeClient client, Policy policy, string packageName) { string path = LuaDirectory + Path.DirectorySeparatorChar + packageName; RegisterTask task = client.Register(policy, path, packageName, Language.LUA); task.Wait(); } } }
/******************************************************************************* * Copyright 2012-2014 by Aerospike. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. ******************************************************************************/ using System; using System.IO; using Aerospike.Client; namespace Aerospike.Demo { public class LuaExample { private static string LuaDirectory = @"..\..\udf"; static LuaExample() { // Adjust path for whether using x64/x86 or AnyCPU compile target. string dir = @"..\..\..\udf"; if (! Directory.Exists(dir)) { dir = @"..\..\udf"; } LuaDirectory = dir; #if (! LITE) LuaConfig.PackagePath = LuaDirectory + @"\?.lua"; #endif } public static void Register(AerospikeClient client, Policy policy, string packageName) { string path = LuaDirectory + Path.DirectorySeparatorChar + packageName; RegisterTask task = client.Register(policy, path, packageName, Language.LUA); task.Wait(); } } }
apache-2.0
C#
24c20c64633c6d9e790d7d34871b50af3d40f9cf
Update tests/Fractions.Tests/FractionSpecs/Sqrt/Method_Sqrt.cs
danm-de/Fractions,danm-de/Fractions
tests/Fractions.Tests/FractionSpecs/Sqrt/Method_Sqrt.cs
tests/Fractions.Tests/FractionSpecs/Sqrt/Method_Sqrt.cs
using System; using FluentAssertions; using NUnit.Framework; using Tests.Fractions; namespace Fractions.Tests.FractionSpecs.Sqrt { [TestFixture] public class If_the_Sqrt_function_is_called : Spec { [Test] public void Sqrt_Of_1_Shall_Be_1() { Fraction.One.Sqrt() .Should().Be(1); } [Test] public void Sqrt_Of_MinusOne_Shall_Be_Fail() { Action act = () => Fraction.MinusOne.Sqrt(); act.Should().Throw<OverflowException>() .WithMessage("Cannot calculate square root from a negative number"); } private static IEnumerable<TestCaseData> TestCases { get { yield return new TestCaseData(0.001); yield return new TestCaseData(5); yield return new TestCaseData(4.54854751); yield return new TestCaseData(9999999855487); yield return new TestCaseData(99999998554865557); yield return new TestCaseData(Math.PI); } } [Test,TestCaseSource(nameof(TestCases))] public void Should_the_result_be_equal_to_Math_Sqrt(double value) { var expected = Math.Sqrt(value); var actual = Fraction.FromDouble(value).Sqrt(); actual.ToDouble().Should().Be(expected); }``` } }
using System; using FluentAssertions; using NUnit.Framework; using Tests.Fractions; namespace Fractions.Tests.FractionSpecs.Sqrt { [TestFixture] public class If_the_Sqrt_function_is_called : Spec { [Test] public void Sqrt_Of_1_Shall_Be_1() { Fraction.One.Sqrt() .Should().Be(1); } [Test] public void Sqrt_Of_MinusOne_Shall_Be_Fail() { Action act = () => Fraction.MinusOne.Sqrt(); act.Should().Throw<OverflowException>() .WithMessage("Cannot calculate square root from a negative number"); } private bool SqrtCompareToDouble(double testValue) { var fractionSqrt = Fraction.FromDouble(testValue).Sqrt(); var doubleSqrt = Math.Sqrt(testValue); return fractionSqrt.ToDouble() == doubleSqrt; } [Test] public void Sqrt_Of_values() { SqrtCompareToDouble(0.001).Should().BeTrue(); SqrtCompareToDouble(5).Should().BeTrue(); SqrtCompareToDouble(4.54854751).Should().BeTrue(); SqrtCompareToDouble(9999999855487).Should().BeTrue(); SqrtCompareToDouble(99999998554865557).Should().BeTrue(); SqrtCompareToDouble(Math.PI).Should().BeTrue(); } } }
bsd-2-clause
C#
e33e8759b88c3ae2a103d5a63843fd7ba40ab301
change order and naming [#136060481]
revaturelabs/revashare-svc-webapi
revashare-svc-webapi/revashare-svc-webapi.Client/Controllers/DriverController.cs
revashare-svc-webapi/revashare-svc-webapi.Client/Controllers/DriverController.cs
using revashare_svc_webapi.Logic.Interfaces; using revashare_svc_webapi.Logic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace revashare_svc_webapi.Client.Controllers { [RoutePrefix("driver")] public class DriverController : ApiController { private readonly IDriverRepository repo; public DriverController(IDriverRepository repo) { this.repo = repo; } [HttpPut] [Route("updatevehicle")] public HttpResponseMessage UpdateVehicleInfo([FromBody]VehicleDTO vehicle) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.UpdateVehicleInfo(vehicle)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("reportrider")] public HttpResponseMessage ReportRider([FromBody]FlagDTO flag) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.ReportRider(flag)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("setavailability")] public HttpResponseMessage SetAvailability([FromBody]RideDTO ride) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.SetAvailability(ride)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPut] [Route("updatedriverprofile")] public HttpResponseMessage UpdateDriverProfile([FromBody] UserDTO driver) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.UpdateDriverProfile(driver)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("schedule")] public HttpResponseMessage ScheduleRide([FromBody]RideDTO ride) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.ScheduleRide(ride)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("cancel")] public HttpResponseMessage CancelRide([FromBody]RideDTO ride) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.CancelRide(ride)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } } }
using revashare_svc_webapi.Logic.Interfaces; using revashare_svc_webapi.Logic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace revashare_svc_webapi.Client.Controllers { [RoutePrefix("driver")] public class DriverController : ApiController { private readonly IDriverRepository repo; public DriverController(IDriverRepository repo) { this.repo = repo; } [HttpPost] [Route("report")] public HttpResponseMessage Post([FromBody]FlagDTO flag) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.ReportRider(flag)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPut] [Route("update/vehicle")] public HttpResponseMessage Put([FromBody]VehicleDTO vehicle) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.UpdateVehicleInfo(vehicle)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("schedule")] public HttpResponseMessage ScheduleRide([FromBody]RideDTO ride) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.ScheduleRide(ride)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("cancel")] public HttpResponseMessage CancelRide([FromBody]RideDTO ride) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.CancelRide(ride)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpPost] [Route("addcar")] public HttpResponseMessage AddCar([FromBody]VehicleDTO vehicle) { try { return Request.CreateResponse(HttpStatusCode.OK, this.repo.AddVehicle(vehicle)); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); } } // DELETE: api/Driver/5 public void Delete(int id) { } [HttpPut] [Route("update-driver-profile")] public HttpResponseMessage UpdateDriverProfile([FromBody] UserDTO driver) { return Request.CreateResponse(HttpStatusCode.OK, this.repo.ModifyDriverProfile(driver)); } } }
mit
C#
09ef5453aefc60eed7c68b43dfebe73030101698
make CoapStack subclass of LayerStack
IntelliTect/CoAP.NET,martindevans/CoAP.NET,smeshlink/CoAP.NET
CoAP.NET/Stack/CoapStack.cs
CoAP.NET/Stack/CoapStack.cs
/* * Copyright (c) 2011-2014, Longxiang He <helongxiang@smeshlink.com>, * SmeshLink Technology Co. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY. * * This file is part of the CoAP.NET, a CoAP framework in C#. * Please see README for more information. */ using CoAP.Net; using CoAP.Server; namespace CoAP.Stack { /// <summary> /// Builds up the stack of CoAP layers /// that process the CoAP protocol. /// </summary> public class CoapStack : LayerStack { public CoapStack(ICoapConfig config) { this.AddLast("Observe", new ObserveLayer(config)); this.AddLast("Blockwise", new BlockwiseLayer(config)); this.AddLast("Token", new TokenLayer(config)); this.AddLast("Reliability", new ReliabilityLayer(config)); } } }
/* * Copyright (c) 2011-2014, Longxiang He <helongxiang@smeshlink.com>, * SmeshLink Technology Co. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY. * * This file is part of the CoAP.NET, a CoAP framework in C#. * Please see README for more information. */ using CoAP.Net; namespace CoAP.Stack { /// <summary> /// Builds up the stack of CoAP layers /// that process the CoAP protocol. /// </summary> public class CoapStack { private LayerStack _stack = new LayerStack(); public CoapStack(ICoapConfig config) { _stack.AddLast("Observe", new ObserveLayer(config)); _stack.AddLast("Blockwise", new BlockwiseLayer(config)); _stack.AddLast("Token", new TokenLayer(config)); _stack.AddLast("Reliability", new ReliabilityLayer(config)); } public LayerStack Layers { get { return _stack; } } public void SendRequest(Request request) { _stack.SendRequest(request); } public void SendResponse(Exchange exchange, Response response) { _stack.SendResponse(exchange, response); } public void SendEmptyMessage(Exchange exchange, EmptyMessage message) { _stack.SendEmptyMessage(exchange, message); } public void ReceiveRequest(Exchange exchange, Request request) { _stack.ReceiveRequest(exchange, request); } public void ReceiveResponse(Exchange exchange, Response response) { _stack.ReceiveResponse(exchange, response); } public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) { _stack.ReceiveEmptyMessage(exchange, message); } } }
bsd-3-clause
C#
2509f4ce5061793f15821e04e9513b86509d7990
Increase Cassandra delay after startup
lecaillon/Evolve
test/Evolve.Test.Utilities/CassandraDockerContainer.cs
test/Evolve.Test.Utilities/CassandraDockerContainer.cs
using System; namespace Evolve.Test.Utilities { public class CassandraDockerContainer { private DockerContainer _container; public string Id => _container.Id; public string ExposedPort => "9042"; public string HostPort => "9042"; public string ClusterName => "evolve"; public string DataCenter => "dc1"; public TimeSpan DelayAfterStartup => TimeSpan.FromMinutes(1); public bool Start(bool fromScratch = false) { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "cassandra", Tag = "latest", Name = "cassandra-evolve", Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort, DelayAfterStartup = DelayAfterStartup, RemovePreviousContainer = fromScratch }).Build(); return _container.Start(); } public void Remove() => _container.Remove(); public bool Stop() => _container.Stop(); public void Dispose() => _container?.Dispose(); } }
using System; namespace Evolve.Test.Utilities { public class CassandraDockerContainer { private DockerContainer _container; public string Id => _container.Id; public string ExposedPort => "9042"; public string HostPort => "9042"; public string ClusterName => "evolve"; public string DataCenter => "dc1"; public TimeSpan DelayAfterStartup => TimeSpan.FromSeconds(45); public bool Start(bool fromScratch = false) { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "cassandra", Tag = "latest", Name = "cassandra-evolve", Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort, DelayAfterStartup = DelayAfterStartup, RemovePreviousContainer = fromScratch }).Build(); return _container.Start(); } public void Remove() => _container.Remove(); public bool Stop() => _container.Stop(); public void Dispose() => _container?.Dispose(); } }
mit
C#
c3b7050b73a730bfaadfc96ee664aeaad5568b5d
Implement testable functionality of BlobNode
turtle-box-games/leaf-csharp
Leaf/Leaf/Nodes/BlobNode.cs
Leaf/Leaf/Nodes/BlobNode.cs
using System; using System.IO; namespace Leaf.Nodes { /// <summary> /// Node that stores arbitrary binary data. /// Stores the data as an array of bytes. /// </summary> public class BlobNode : Node { private byte[] _bytes; /// <summary> /// Retrieve the ID for the type of node. /// This can be used to identify, serialize, and cast a node to its type. /// The value returned by this property is <see cref="NodeId.Blob"/>. /// </summary> public override NodeId TypeId { get { return NodeId.Blob; } } /// <summary> /// Gets and sets the value of the node. /// </summary> public byte[] Bytes { get { return _bytes; } set { if(value == null) throw new ArgumentNullException(); _bytes = value; } } /// <summary> /// Creates a new node. /// </summary> /// <param name="bytes">Byte array of the data to store in the node.</param> public BlobNode(byte[] bytes) { if(bytes == null) throw new ArgumentNullException("bytes"); _bytes = bytes; } /// <summary> /// Creates a new node by reading its contents from a stream. /// </summary> /// <param name="reader">Reader used to pull data from the stream.</param> /// <returns>Newly constructed node.</returns> internal BlobNode Read(BinaryReader reader) { throw new NotImplementedException(); } /// <summary> /// Writes the contents of the node to a stream. /// </summary> /// <param name="writer">Writer used to put data in the stream.</param> internal override void Write(BinaryWriter writer) { throw new NotImplementedException(); } } }
using System; using System.IO; namespace Leaf.Nodes { /// <summary> /// Node that stores arbitrary binary data. /// Stores the data as an array of bytes. /// </summary> public class BlobNode : Node { /// <summary> /// Retrieve the ID for the type of node. /// This can be used to identify, serialize, and cast a node to its type. /// The value returned by this property is <see cref="NodeId.Blob"/>. /// </summary> public override NodeId TypeId { get { throw new NotImplementedException(); } } /// <summary> /// Gets and sets the value of the node. /// </summary> public byte[] Bytes { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Creates a new node. /// </summary> /// <param name="bytes">Byte array of the data to store in the node.</param> public BlobNode(byte[] bytes) { throw new NotImplementedException(); } /// <summary> /// Creates a new node by reading its contents from a stream. /// </summary> /// <param name="reader">Reader used to pull data from the stream.</param> /// <returns>Newly constructed node.</returns> internal BlobNode Read(BinaryReader reader) { throw new NotImplementedException(); } /// <summary> /// Writes the contents of the node to a stream. /// </summary> /// <param name="writer">Writer used to put data in the stream.</param> internal override void Write(BinaryWriter writer) { throw new NotImplementedException(); } } }
mit
C#
24f7991c72b6aceef0200c0e6e72a8c2120a85da
Update MSDN documentation linl
ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp
source/Htc.Vita.Core/Interop/Windows.User32.cs
source/Htc.Vita.Core/Interop/Windows.User32.cs
using System; using System.Runtime.InteropServices; namespace Htc.Vita.Core.Interop { internal static partial class Windows { /** * https://msdn.microsoft.com/en-us/library/windows/desktop/aa376868.aspx * https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-exitwindowsex */ [Flags] internal enum ExitType : uint { /* EWX_LOGOFF */ Logoff = 0x00000000, /* EWX_SHUTDOWN */ Shutdown = 0x00000001, /* EWX_REBOOT */ Reboot = 0x00000002, /* EWX_FORCE */ Force = 0x00000004, /* EWX_POWEROFF */ Poweroff = 0x00000008, /* EWX_FORCEIFHUNG */ ForceIfHung = 0x00000010, /* EWX_QUICKRESOLVE */ QuickResolve = 0x00000020, /* EWX_RESTARTAPPS */ RestartApps = 0x00000040, /* EWX_HYBRID_SHUTDOWN */ HybridShutdown = 0x00400000, /* EWX_BOOTOPTIONS */ BootOptions = 0x01000000 } /** * https://msdn.microsoft.com/en-us/library/windows/desktop/aa376868.aspx * https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-exitwindowsex */ [DllImport(Libraries.WindowsUser32, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool ExitWindowsEx( /* _In_ UINT */ [In] ExitType uFlags, /* _In_ DWORD */ [In] int dwReason ); } }
using System; using System.Runtime.InteropServices; namespace Htc.Vita.Core.Interop { internal static partial class Windows { /** * https://msdn.microsoft.com/en-us/library/windows/desktop/aa376868.aspx */ [Flags] internal enum ExitType : uint { /* EWX_LOGOFF */ Logoff = 0x00000000, /* EWX_SHUTDOWN */ Shutdown = 0x00000001, /* EWX_REBOOT */ Reboot = 0x00000002, /* EWX_FORCE */ Force = 0x00000004, /* EWX_POWEROFF */ Poweroff = 0x00000008, /* EWX_FORCEIFHUNG */ ForceIfHung = 0x00000010, /* EWX_QUICKRESOLVE */ QuickResolve = 0x00000020, /* EWX_RESTARTAPPS */ RestartApps = 0x00000040, /* EWX_HYBRID_SHUTDOWN */ HybridShutdown = 0x00400000, /* EWX_BOOTOPTIONS */ BootOptions = 0x01000000 } /** * https://msdn.microsoft.com/en-us/library/windows/desktop/aa376868.aspx */ [DllImport(Libraries.WindowsUser32, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool ExitWindowsEx( /* _In_ UINT */ [In] ExitType uFlags, /* _In_ DWORD */ [In] int dwReason ); } }
mit
C#
159a2a65f18451e2061b9610ca3cd003fb601a9b
fix the attribute name to expandJournal
DimensionDataCBUSydney/Compute.Api.Client,samuelchong/Compute.Api.Client
ComputeClient/Compute.Contracts/Drs/ExpandJournalType.cs
ComputeClient/Compute.Contracts/Drs/ExpandJournalType.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DD.CBU.Compute.Api.Contracts.Drs { /// [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34283")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types")] [System.Xml.Serialization.XmlRootAttribute("expandJournal", Namespace = "urn:didata.com:api:cloud:types", IsNullable = true)] public partial class ExpandJournalType { private int sizeGbField; private string idField; /// public int sizeGb { get { return this.sizeGbField; } set { this.sizeGbField = value; } } /// [System.Xml.Serialization.XmlAttributeAttribute()] public string id { get { return this.idField; } set { this.idField = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DD.CBU.Compute.Api.Contracts.Drs { /// [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34283")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:didata.com:api:cloud:types", IsNullable = true)] public partial class ExpandJournalType { private int sizeGbField; private string idField; /// public int sizeGb { get { return this.sizeGbField; } set { this.sizeGbField = value; } } /// [System.Xml.Serialization.XmlAttributeAttribute()] public string id { get { return this.idField; } set { this.idField = value; } } } }
mit
C#
57963d8b79f25af27eeecbff53d9141b0c451c5d
Fix test breakage caused by renamed emoji in Unicode 13
neosmart/unicode.net,neosmart/unicode.net,neosmart/unicode.net,neosmart/unicode.net,neosmart/unicode.net
tests/SingleEmojiTests.cs
tests/SingleEmojiTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using NeoSmart.Unicode; namespace UnicodeTests { [TestClass] public class SingleEmojiTests { [TestMethod] public void TestSingleEmojiSame() { Assert.IsFalse(Emoji.AbButtonBloodType == null); Assert.IsFalse(null == Emoji.AbButtonBloodType); Assert.IsFalse(Emoji.AbButtonBloodType == Emoji.Person); #pragma warning disable CS1718 // Comparison made to same variable Assert.IsTrue(Emoji.AbButtonBloodType == Emoji.AbButtonBloodType); #pragma warning restore CS1718 // Comparison made to same variable } [TestMethod] public void TestSingleEmojiNotSame() { Assert.IsTrue(Emoji.AbButtonBloodType != null); Assert.IsTrue(null != Emoji.AbButtonBloodType); Assert.IsTrue(Emoji.AbButtonBloodType != Emoji.Person); #pragma warning disable CS1718 // Comparison made to same variable Assert.IsFalse(Emoji.AbButtonBloodType != Emoji.AbButtonBloodType); #pragma warning restore CS1718 // Comparison made to same variable } [TestMethod] public void TestSingleEmojiEquality() { Assert.IsFalse(Emoji.AbButtonBloodType.Equals(null)); Assert.IsTrue(Emoji.AbButtonBloodType.Equals(Emoji.AbButtonBloodType)); Assert.IsFalse(Equals(Emoji.AbButtonBloodType, null)); Assert.IsTrue(Equals(Emoji.AbButtonBloodType, Emoji.AbButtonBloodType)); } [TestMethod] public void TestSingleEmojiCompareTo() { Assert.IsFalse(Emoji.AbButtonBloodType.CompareTo(Emoji.AbButtonBloodType) != 0); } [TestMethod] public void UnicodeSortOrder() { // While the unicode sequence for the Thinking Face emoji is U+1F914 and the sequence for // Zipper Mouth Face is U+1F910, the Thinking Face emoji should always come directly before // it in a sorted list. Assert.IsTrue(Emoji.ThinkingFace.Sequence > Emoji.ZipperMouthFace.Sequence); Assert.IsTrue(Emoji.ThinkingFace < Emoji.ZipperMouthFace); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using NeoSmart.Unicode; namespace UnicodeTests { [TestClass] public class SingleEmojiTests { [TestMethod] public void TestSingleEmojiSame() { Assert.IsFalse(Emoji.AbButtonBloodType == null); Assert.IsFalse(null == Emoji.AbButtonBloodType); Assert.IsFalse(Emoji.AbButtonBloodType == Emoji.Adult); #pragma warning disable CS1718 // Comparison made to same variable Assert.IsTrue(Emoji.AbButtonBloodType == Emoji.AbButtonBloodType); #pragma warning restore CS1718 // Comparison made to same variable } [TestMethod] public void TestSingleEmojiNotSame() { Assert.IsTrue(Emoji.AbButtonBloodType != null); Assert.IsTrue(null != Emoji.AbButtonBloodType); Assert.IsTrue(Emoji.AbButtonBloodType != Emoji.Adult); #pragma warning disable CS1718 // Comparison made to same variable Assert.IsFalse(Emoji.AbButtonBloodType != Emoji.AbButtonBloodType); #pragma warning restore CS1718 // Comparison made to same variable } [TestMethod] public void TestSingleEmojiEquality() { Assert.IsFalse(Emoji.AbButtonBloodType.Equals(null)); Assert.IsTrue(Emoji.AbButtonBloodType.Equals(Emoji.AbButtonBloodType)); Assert.IsFalse(Equals(Emoji.AbButtonBloodType, null)); Assert.IsTrue(Equals(Emoji.AbButtonBloodType, Emoji.AbButtonBloodType)); } [TestMethod] public void TestSingleEmojiCompareTo() { Assert.IsFalse(Emoji.AbButtonBloodType.CompareTo(Emoji.AbButtonBloodType) != 0); } [TestMethod] public void UnicodeSortOrder() { // While the unicode sequence for the Thinking Face emoji is U+1F914 and the sequence for // Zipper Mouth Face is U+1F910, the Thinking Face emoji should always come directly before // it in a sorted list. Assert.IsTrue(Emoji.ThinkingFace.Sequence > Emoji.ZipperMouthFace.Sequence); Assert.IsTrue(Emoji.ThinkingFace < Emoji.ZipperMouthFace); } } }
mit
C#
33424e5d5b0b6fc5033505e10d69862926711f44
Read config env
okaram/azure-website,okaram/azure-website
read-config.cshtml
read-config.cshtml
<!DOCTYPE html> <html> <head> </head> <body> <p>Salutation: @Environment.GetEnvironmentVariable("APPSETTING_Salutation")</p> <p>Salutation: </p> </body> </html>
<!DOCTYPE html> <html> <head> </head> <body> <p>Salutation: @Environment.GetEnvironmentVariable("APPSETTINGS_Salutation")</p> <p>Salutation: </p> </body> </html>
unlicense
C#
46aea17f17e56eac44ef610a68c547885b4d3542
Update Vector2.cs
elacy/PopulationSimulator
PopSim.Logic/Vector2.cs
PopSim.Logic/Vector2.cs
using System; namespace PopSim.Logic { public class Vector2 { public Vector2(double x, double y) { X = x; Y = y; IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon; } public bool IsZero { get; private set; } public double X { get; private set; } public double Y { get; private set; } public Vector2 Add(Vector2 vector2) { return new Vector2(X + vector2.X,Y + vector2.Y); } public double GetDistance(Vector2 vector2) { return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y)); } private static double Squared(double value) { return Math.Pow(value, 2); } public double AngleBetween(Vector2 vector2) { return Math.Atan2(vector2.Y - Y, vector2.X - X); } public Vector2 GetDirection(Vector2 destination) { var angle = AngleBetween(destination); RetVector = new Vector2(Math.Cos(angle),Math.Sin(angle)); RetVector = RetVector.UnitVector(); return RetVector; } public Vector2 ScalarMultiply(double multiplier) { return new Vector2(X*multiplier,Y*multiplier); } public double VectorMagnitude() { return Math.Sqrt(X*X + Y*Y); } public Vector2 UnitVector() { return new Vector2( X / VectorMagnitude(), Y / VectorMagnitude()) } } }
using System; namespace PopSim.Logic { public class Vector2 { public Vector2(double x, double y) { X = x; Y = y; IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon; } public bool IsZero { get; private set; } public double X { get; private set; } public double Y { get; private set; } public Vector2 Add(Vector2 vector2) { return new Vector2(X + vector2.X,Y + vector2.Y); } public double GetDistance(Vector2 vector2) { return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y)); } private static double Squared(double value) { return Math.Pow(value, 2); } public double AngleBetween(Vector2 vector2) { return Math.Atan2(vector2.Y - Y, vector2.X - X); } public Vector2 GetDirection(Vector2 destination) { var angle = AngleBetween(destination); return new Vector2(Math.Cos(angle),Math.Sin(angle)); } public Vector2 ScalarMultiply(double multiplier) { RetVector = new Vector2(X*multiplier,Y*multiplier); RetVector = RetVector.UnitVector(); return RetVector; } public double VectorMagnitude() { return Math.Sqrt(X*X + Y*Y); } public Vector2 UnitVector() { return new Vector2( X / VectorMagnitude(), Y / VectorMagnitude()) } } }
mit
C#
1e51b63041282e26b3073935a8d3fcd0352a33bd
Optimize CellInfo.GetHashCode
AVPolyakov/SharpLayout
SharpLayout/CellInfo.cs
SharpLayout/CellInfo.cs
using System; namespace SharpLayout { public struct CellInfo: IEquatable<CellInfo> { public int RowIndex { get; } public int ColumnIndex { get; } public CellInfo(int rowIndex, int columnIndex) { RowIndex = rowIndex; ColumnIndex = columnIndex; } public CellInfo(Row row, Column column) : this(row.Index, column.Index) { } public CellInfo(Cell cell) : this(cell.RowIndex, cell.ColumnIndex) { } public static implicit operator CellInfo(Cell cell) => new CellInfo(cell); public bool Equals(CellInfo other) { return RowIndex == other.RowIndex && ColumnIndex == other.ColumnIndex; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is CellInfo info && Equals(info); } public override int GetHashCode() { unchecked { return (RowIndex * 397) ^ ColumnIndex; } } } }
using System; namespace SharpLayout { public struct CellInfo: IEquatable<CellInfo> { public int RowIndex { get; } public int ColumnIndex { get; } public CellInfo(int rowIndex, int columnIndex) { RowIndex = rowIndex; ColumnIndex = columnIndex; } public CellInfo(Row row, Column column) : this(row.Index, column.Index) { } public CellInfo(Cell cell) : this(cell.RowIndex, cell.ColumnIndex) { } public static implicit operator CellInfo(Cell cell) => new CellInfo(cell); public bool Equals(CellInfo other) => Tuple.Equals(other.Tuple); public override int GetHashCode() => Tuple.GetHashCode(); public override bool Equals(object obj) { if (obj is CellInfo) return Equals((CellInfo) obj); return false; } private Tuple<int, int> Tuple => System.Tuple.Create(RowIndex, ColumnIndex); } }
mit
C#
4c349774226b4395a55797bf7a646a27841ec916
Add Setting Class to LibraryContext.
Programazing/Open-School-Library,Programazing/Open-School-Library
src/Open-School-Library/Data/LibraryContext.cs
src/Open-School-Library/Data/LibraryContext.cs
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Open_School_Library.Models.DatabaseModels; namespace Open_School_Library.Data { public class LibraryContext : DbContext { public LibraryContext(DbContextOptions<LibraryContext> options) : base(options) { } public DbSet<Student> Students { get; set; } public DbSet<Teacher> Teachers { get; set; } public DbSet<Book> Books { get; set; } public DbSet<Genre> Genres { get; set; } public DbSet<Dewey> Deweys { get; set; } public DbSet<Setting> Settings { get; set; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Open_School_Library.Models.DatabaseModels; namespace Open_School_Library.Data { public class LibraryContext : DbContext { public LibraryContext(DbContextOptions<LibraryContext> options) : base(options) { } public DbSet<Student> Students { get; set; } public DbSet<Teacher> Teachers { get; set; } public DbSet<Book> Books { get; set; } public DbSet<Genre> Genres { get; set; } public DbSet<Dewey> Deweys { get; set; } } }
mit
C#
2acc73d54c43bdf35070d81f137eae7f53be77e9
Remove leftover unused stack variable
elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net,UdiBen/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,RossLieberman/NEST,elastic/elasticsearch-net,cstlaurent/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,adam-mccoy/elasticsearch-net
src/Nest/CommonAbstractions/Infer/Field/FieldResolver.cs
src/Nest/CommonAbstractions/Infer/Field/FieldResolver.cs
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace Nest { public class FieldResolver { private readonly IConnectionSettingsValues _settings; private readonly ConcurrentDictionary<Field, string> Fields = new ConcurrentDictionary<Field, string>(); private readonly ConcurrentDictionary<PropertyName, string> Properties = new ConcurrentDictionary<PropertyName, string>(); public FieldResolver(IConnectionSettingsValues settings) { settings.ThrowIfNull(nameof(settings)); this._settings = settings; } public string Resolve(Field field) { if (field.IsConditionless()) return null; if (!field.Name.IsNullOrEmpty()) return field.Name; string f; if (this.Fields.TryGetValue(field, out f)) return f; f = this.Resolve(field.Expression, field.Property); this.Fields.TryAdd(field, f); return f; } public string Resolve(PropertyName property) { if (property.IsConditionless()) return null; if (!property.Name.IsNullOrEmpty()) { if (property.Name.Contains(".")) throw new ArgumentException("Property names cannot contain dots."); return property.Name; } string f; if (this.Properties.TryGetValue(property, out f)) return f; f = this.Resolve(property.Expression, property.Property, true); this.Properties.TryAdd(property, f); return f; } private string Resolve(Expression expression, MemberInfo member, bool toLastToken = false) { var visitor = new FieldExpressionVisitor(_settings); var name = expression != null ? visitor.Resolve(expression, toLastToken) : member != null ? visitor.Resolve(member) : null; if (name == null) throw new ArgumentException("Could not resolve a name from the given Expression or MemberInfo."); return name; } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace Nest { public class FieldResolver { private readonly IConnectionSettingsValues _settings; private readonly ConcurrentDictionary<Field, string> Fields = new ConcurrentDictionary<Field, string>(); private readonly ConcurrentDictionary<PropertyName, string> Properties = new ConcurrentDictionary<PropertyName, string>(); protected Stack<string> Stack { get; set;} public FieldResolver(IConnectionSettingsValues settings) { settings.ThrowIfNull(nameof(settings)); this._settings = settings; } public string Resolve(Field field) { if (field.IsConditionless()) return null; if (!field.Name.IsNullOrEmpty()) return field.Name; string f; if (this.Fields.TryGetValue(field, out f)) return f; f = this.Resolve(field.Expression, field.Property); this.Fields.TryAdd(field, f); return f; } public string Resolve(PropertyName property) { if (property.IsConditionless()) return null; if (!property.Name.IsNullOrEmpty()) { if (property.Name.Contains(".")) throw new ArgumentException("Property names cannot contain dots."); return property.Name; } string f; if (this.Properties.TryGetValue(property, out f)) return f; f = this.Resolve(property.Expression, property.Property, true); this.Properties.TryAdd(property, f); return f; } private string Resolve(Expression expression, MemberInfo member, bool toLastToken = false) { var visitor = new FieldExpressionVisitor(_settings); var name = expression != null ? visitor.Resolve(expression, toLastToken) : member != null ? visitor.Resolve(member) : null; if (name == null) throw new ArgumentException("Could not resolve a name from the given Expression or MemberInfo."); return name; } } }
apache-2.0
C#
8378bf2b89b379517b93f29d10b635355379e64b
Fix Cancel button URL in DeleteForward
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
SupportManager.Web/Areas/Teams/Home/DeleteForward.cshtml
SupportManager.Web/Areas/Teams/Home/DeleteForward.cshtml
@model SupportManager.Web.Areas.Teams.Home.DeleteForward.Result @{ ViewBag.Title = "Delete scheduled forward"; } <h2>Delete scheduled forward</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Forwarding information</h4> <hr /> <div class="alert alert-info"> Please verify the information below before confirming delete. </div> <table class="table"> <thead> <tr> <th class="w-10"></th> <th class="w-25">User</th> <th class="w-25">Phonenumber</th> <th class="w-40">When</th> </tr> </thead> <tbody> <tr> <td></td> <td>@Html.Display(m => m.UserName)</td> <td>@Html.Display(m => m.PhoneNumber)</td> <td>@Html.Display(m => m.When)</td> </tr> </tbody> </table> </div> @Html.Input(m => m.Id); <div class="form-group"> <div class="col-md-12"> <input type="submit" value="Delete" class="btn btn-danger" /> @Html.ActionLink("Cancel", "Home", null, null, new {@class = "btn btn-default"}) </div> </div> }
@model SupportManager.Web.Areas.Teams.Home.DeleteForward.Result @{ ViewBag.Title = "Delete scheduled forward"; } <h2>Delete scheduled forward</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Forwarding information</h4> <hr /> <div class="alert alert-info"> Please verify the information below before confirming delete. </div> <table class="table"> <thead> <tr> <th class="w-10"></th> <th class="w-25">User</th> <th class="w-25">Phonenumber</th> <th class="w-40">When</th> </tr> </thead> <tbody> <tr> <td></td> <td>@Html.Display(m => m.UserName)</td> <td>@Html.Display(m => m.PhoneNumber)</td> <td>@Html.Display(m => m.When)</td> </tr> </tbody> </table> </div> @Html.Input(m => m.Id); <div class="form-group"> <div class="col-md-12"> <input type="submit" value="Delete" class="btn btn-danger" /> @Html.ActionLink("Cancel", "Details", null, null, new {@class = "btn btn-default"}) </div> </div> }
mit
C#
6e2451adcb67551b950fb14c90c110c35e1dc728
Fix rendering of TextInput after programmatic focus (#554)
lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows
ReactWindows/ReactNative/Views/TextInput/ReactTextBox.cs
ReactWindows/ReactNative/Views/TextInput/ReactTextBox.cs
using ReactNative.UIManager; using System.Threading; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace ReactNative.Views.TextInput { class ReactTextBox : TextBox { private int _eventCount; public ReactTextBox() { SizeChanged += OnSizeChanged; } public int CurrentEventCount { get { return _eventCount; } } public bool ClearTextOnFocus { get; set; } public bool SelectTextOnFocus { get; set; } public int IncrementEventCount() { return Interlocked.Increment(ref _eventCount); } protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); if (ClearTextOnFocus) { Text = ""; } if (SelectTextOnFocus) { SelectionStart = 0; SelectionLength = Text.Length; } } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { this.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( this.GetTag(), Text, e.NewSize.Width, e.NewSize.Height, IncrementEventCount())); } } }
using ReactNative.UIManager; using System.Threading; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace ReactNative.Views.TextInput { class ReactTextBox : TextBox { private int _eventCount; public ReactTextBox() { SizeChanged += OnSizeChanged; } public int CurrentEventCount { get { return _eventCount; } } public bool ClearTextOnFocus { get; set; } public bool SelectTextOnFocus { get; set; } public int IncrementEventCount() { return Interlocked.Increment(ref _eventCount); } protected override void OnGotFocus(RoutedEventArgs e) { if (ClearTextOnFocus) { Text = ""; } if (SelectTextOnFocus) { SelectionStart = 0; SelectionLength = Text.Length; } } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { this.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( this.GetTag(), Text, e.NewSize.Width, e.NewSize.Height, IncrementEventCount())); } } }
mit
C#
c8b6841ef16e40670a89ba8a84aa21b2d066e9a3
Allow KeepAlive controller Ping method to be requested by non local requests (#10126)
abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS
src/Umbraco.Web/Editors/KeepAliveController.cs
src/Umbraco.Web/Editors/KeepAliveController.cs
using System.Runtime.Serialization; using System.Web.Http; using Umbraco.Web.WebApi; namespace Umbraco.Web.Editors { public class KeepAliveController : UmbracoApiController { [HttpHead] [HttpGet] public KeepAlivePingResult Ping() { return new KeepAlivePingResult { Success = true, Message = "I'm alive!" }; } } public class KeepAlivePingResult { [DataMember(Name = "success")] public bool Success { get; set; } [DataMember(Name = "message")] public string Message { get; set; } } }
using System.Runtime.Serialization; using System.Web.Http; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Editors { public class KeepAliveController : UmbracoApiController { [OnlyLocalRequests] [HttpGet] public KeepAlivePingResult Ping() { return new KeepAlivePingResult { Success = true, Message = "I'm alive!" }; } } public class KeepAlivePingResult { [DataMember(Name = "success")] public bool Success { get; set; } [DataMember(Name = "message")] public string Message { get; set; } } }
mit
C#
731cc172fa0f9dd047e5284085cc64d093e5f2f8
Remove help box from the folders settings list
PhannGor/unity3d-rainbow-folders
Assets/Plugins/RainbowFolders/Editor/Scripts/Settings/RainbowFoldersSettingsEditor.cs
Assets/Plugins/RainbowFolders/Editor/Scripts/Settings/RainbowFoldersSettingsEditor.cs
/* * 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 Borodar.ReorderableList; using UnityEditor; namespace Borodar.RainbowFolders.Editor.Settings { [CustomEditor(typeof (RainbowFoldersSettings))] public class RainbowFoldersSettingsEditor : UnityEditor.Editor { private const string PROP_NAME_FOLDERS = "Folders"; private SerializedProperty _foldersProperty; protected void OnEnable() { _foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS); } public override void OnInspectorGUI() { serializedObject.Update(); ReorderableListGUI.Title("Rainbow Folders"); ReorderableListGUI.ListField(_foldersProperty); serializedObject.ApplyModifiedProperties(); } } }
/* * 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 Borodar.ReorderableList; using UnityEditor; namespace Borodar.RainbowFolders.Editor.Settings { [CustomEditor(typeof (RainbowFoldersSettings))] public class RainbowFoldersSettingsEditor : UnityEditor.Editor { private const string PROP_NAME_FOLDERS = "Folders"; private SerializedProperty _foldersProperty; protected void OnEnable() { _foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS); } public override void OnInspectorGUI() { EditorGUILayout.HelpBox("Please set your custom folder icons by specifying:\n\n" + "- Folder Name\n" + "Icon will be applied to all folders with the same name\n\n" + "- Folder Path\n" + "Icon will be applied to a single folder. The path format: Assets/SomeFolder/YourFolder", MessageType.Info); serializedObject.Update(); ReorderableListGUI.Title("Rainbow Folders"); ReorderableListGUI.ListField(_foldersProperty); serializedObject.ApplyModifiedProperties(); } } }
apache-2.0
C#
88c613d735ad2e53262d2599a7f515756790b285
add comments in Global.asax to explain what the code does
ServiceStack/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,assaframan/MoviesRestForAppHarbor,assaframan/MoviesRestForAppHarbor,assaframan/MoviesRestForAppHarbor,zhaokunfay/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples
src/RedisStackOverflow/RedisStackOverflow/Global.asax.cs
src/RedisStackOverflow/RedisStackOverflow/Global.asax.cs
using System; using Funq; using RedisStackOverflow.ServiceInterface; using ServiceStack.Redis; using ServiceStack.WebHost.Endpoints; namespace RedisStackOverflow { public class AppHost : AppHostBase { public AppHost() : base("Redis StackOverflow", typeof(QuestionsService).Assembly) { } public override void Configure(Container container) { //Show StackTrace in Web Service Exceptions SetConfig(new EndpointHostConfig { DebugMode = true }); //Register any dependencies you want injected into your services container.Register<IRedisClientsManager>(c => new PooledRedisClientManager()); container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>())); } } public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { new AppHost().Init(); } } }
using System; using Funq; using RedisStackOverflow.ServiceInterface; using ServiceStack.Redis; using ServiceStack.WebHost.Endpoints; namespace RedisStackOverflow { public class AppHost : AppHostBase { public AppHost() : base("Redis StackOverflow", typeof(QuestionsService).Assembly) { } public override void Configure(Container container) { SetConfig(new EndpointHostConfig { DebugMode = true }); container.Register<IRedisClientsManager>(c => new PooledRedisClientManager()); container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>())); } } public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { new AppHost().Init(); } } }
bsd-3-clause
C#
1b9ca507b1eaaa80be4b8fbe89aff431f270fb67
Fix build break
kzu/System.Diagnostics.Tracer
src/System.Diagnostics.Tracer/Properties/AssemblyInfo.cs
src/System.Diagnostics.Tracer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("System.Diagnostics.Tracer")] [assembly: AssemblyProduct("System.Diagnostics.Tracer")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: InternalsVisibleTo("System.Diagnostics.Tracer.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010027dae7b9c059832ce5c6555903c9ca7b39acb047f61d7515b2eee5ccd68b27bf4301b29c2c01e12f0a1a98dd3608a1d5591944bfb831f5e3a89b94bd81eda2fe15a8731bcf1a675052be7f116183f253822f8760fb8c487c38d2dc0dd8e68aeeeb5b6ca739b883a0b443897a39e79e6abab4789852e9f25fa02069f741c364f0")] [assembly: AssemblyVersion(ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + ".0")] [assembly: AssemblyFileVersion (ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch)] [assembly: AssemblyInformationalVersion(ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch + "-" + ThisAssembly.Git.Branch + "+" + ThisAssembly.Git.Commit)]
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("System.Diagnostics.Tracer")] [assembly: AssemblyProduct("System.Diagnostics.Tracer")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: InternalsVisibleTo("System.Diagnostics.Tracer.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010027dae7b9c059832ce5c6555903c9ca7b39acb047f61d7515b2eee5ccd68b27bf4301b29c2c01e12f0a1a98dd3608a1d5591944bfb831f5e3a89b94bd81eda2fe15a8731bcf1a675052be7f116183f253822f8760fb8c487c38d2dc0dd8e68aeeeb5b6ca739b883a0b443897a39e79e6abab4789852e9f25fa02069f741c364f0")] [assembly: AssemblyVersion(ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + ".0)] [assembly: AssemblyFileVersion (ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch)] [assembly: AssemblyInformationalVersion(ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch + "-" + ThisAssembly.Git.Branch + "+" + ThisAssembly.Git.Commit)]
mit
C#
91974a69f5204aa458cd481a0c6ba94d97499b23
Update IReadOnlyUserGroup.cs
abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS
src/Umbraco.Core/Models/Membership/IReadOnlyUserGroup.cs
src/Umbraco.Core/Models/Membership/IReadOnlyUserGroup.cs
namespace Umbraco.Cms.Core.Models.Membership; /// <summary> /// A readonly user group providing basic information /// </summary> public interface IReadOnlyUserGroup { string? Name { get; } string? Icon { get; } int Id { get; } int? StartContentId { get; } int? StartMediaId { get; } /// <summary> /// The alias /// </summary> string Alias { get; } // This is set to return true as default to avoid breaking changes. bool HasAccessToAllLanguages => true; /// <summary> /// The set of default permissions /// </summary> /// <remarks> /// By default each permission is simply a single char but we've made this an enumerable{string} to support a more /// flexible permissions structure in the future. /// </remarks> IEnumerable<string>? Permissions { get; set; } IEnumerable<string> AllowedSections { get; } IEnumerable<int> AllowedLanguages => Enumerable.Empty<int>(); public bool HasAccessToLanguage( int languageId) => HasAccessToAllLanguages || AllowedLanguages.Contains(languageId); }
namespace Umbraco.Cms.Core.Models.Membership; /// <summary> /// A readonly user group providing basic information /// </summary> public interface IReadOnlyUserGroup { string? Name { get; } string? Icon { get; } int Id { get; } int? StartContentId { get; } int? StartMediaId { get; } /// <summary> /// The alias /// </summary> string Alias { get; } // This is set to return true as default to avoid breaking changes. bool HasAccessToAllLanguages => true; /// <summary> /// The set of default permissions /// </summary> /// <remarks> /// By default each permission is simply a single char but we've made this an enumerable{string} to support a more /// flexible permissions structure in the future. /// </remarks> IEnumerable<string>? Permissions { get; set; } IEnumerable<string> AllowedSections { get; } IEnumerable<int> AllowedLanguages => Enumerable.Empty<int>(); public bool HasAccessToLanguage( int languageId) => HasAccessToAllLanguages || AllowedLanguages.Any() is false || AllowedLanguages.Contains(languageId); }
mit
C#
75b636fd61d3363ef92157740914575be5a5ebc5
Add Trello provider (not yet working)
Bigsby/Xamarin.Forms.OAuth
src/Xamarin.Forms.OAuth/Providers/TrelloOAuthProvider.cs
src/Xamarin.Forms.OAuth/Providers/TrelloOAuthProvider.cs
using System.Collections.Generic; namespace Xamarin.Forms.OAuth.Providers { public sealed class TrelloOAuthProvider : OAuthProvider { private const string _redirectUrl = "https://trelloResponse.com"; public TrelloOAuthProvider(string clientId, string clientSecret, params string[] scopes) : base(new OAuthProviderDefinition( "Trello", "https://trello.com/1/authorize", "https://trello.com/1/OAuthGetAccessToken", "https://api.trello.com/1/members/me", clientId, clientSecret, _redirectUrl, scopes) { RequiresCode = true, }) { } internal override string GetAuthorizationUrl() { return BuildUrl(Definition.AuthorizeUrl, new KeyValuePair<string, string>[] { }); } } }
namespace Xamarin.Forms.OAuth.Providers { public sealed class TrelloOAuthProvider : OAuthProvider { private const string _redirectUrl = "https://trelloResponse.com"; public TrelloOAuthProvider(string clientId, string clientSecret, params string[] scopes) : base(new OAuthProviderDefinition( "Trello", "https://trello.com/1/authorize", "https://trello.com/1/OAuthGetAccessToken", "https://api.trello.com/1/members/me", clientId, clientSecret, _redirectUrl, scopes) { RequiresCode = true, }) { } internal override string GetAuthorizationUrl() { return base.GetAuthorizationUrl(); } } }
mit
C#
0aeb2b93f514b91553a818d148d59bba38f9c232
change resource name variable to private
takenet/blip-sdk-csharp
src/Take.Blip.Builder/Variables/BaseResourceVariableProvider.cs
src/Take.Blip.Builder/Variables/BaseResourceVariableProvider.cs
using Lime.Protocol; using Lime.Protocol.Network; using Lime.Protocol.Serialization; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Take.Blip.Client; namespace Take.Blip.Builder.Variables { public class BaseResourceVariableProvider : IVariableProvider { private readonly ISender _sender; private readonly IDocumentSerializer _documentSerializer; private readonly string _resourceName; public VariableSource Source => throw new NotImplementedException(); public BaseResourceVariableProvider(ISender sender, IDocumentSerializer documentSerializer, string resourceName) { _sender = sender; _documentSerializer = documentSerializer; _resourceName = resourceName ?? throw new ArgumentNullException(nameof(resourceName)); } public async Task<string> GetVariableAsync(string name, IContext context, CancellationToken cancellationToken) { try { var resourceCommandResult = await ExecuteGetResourceCommandAsync(name, cancellationToken); if (resourceCommandResult.Status != CommandStatus.Success) { return null; } if (!resourceCommandResult.Resource.GetMediaType().IsJson) { return resourceCommandResult.Resource.ToString(); } return _documentSerializer.Serialize(resourceCommandResult.Resource); } catch (LimeException ex) when (ex.Reason.Code == ReasonCodes.COMMAND_RESOURCE_NOT_FOUND) { return null; } } private async Task<Command> ExecuteGetResourceCommandAsync(string name, CancellationToken cancellationToken) { // We are sending the command directly here because the Extension requires us to know the type. var getResourceCommand = new Command() { Uri = new LimeUri($"/{_resourceName}/{Uri.EscapeDataString(name)}"), Method = CommandMethod.Get, }; var resourceCommandResult = await _sender.ProcessCommandAsync( getResourceCommand, cancellationToken); return resourceCommandResult; } } }
using Lime.Protocol; using Lime.Protocol.Network; using Lime.Protocol.Serialization; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Take.Blip.Client; namespace Take.Blip.Builder.Variables { public class BaseResourceVariableProvider : IVariableProvider { private readonly ISender _sender; private readonly IDocumentSerializer _documentSerializer; protected readonly string _resourceName; public VariableSource Source => throw new NotImplementedException(); public BaseResourceVariableProvider(ISender sender, IDocumentSerializer documentSerializer, string resourceName) { _sender = sender; _documentSerializer = documentSerializer; _resourceName = resourceName ?? throw new ArgumentNullException(nameof(resourceName)); } public async Task<string> GetVariableAsync(string name, IContext context, CancellationToken cancellationToken) { try { var resourceCommandResult = await ExecuteGetResourceCommandAsync(name, cancellationToken); if (resourceCommandResult.Status != CommandStatus.Success) { return null; } if (!resourceCommandResult.Resource.GetMediaType().IsJson) { return resourceCommandResult.Resource.ToString(); } return _documentSerializer.Serialize(resourceCommandResult.Resource); } catch (LimeException ex) when (ex.Reason.Code == ReasonCodes.COMMAND_RESOURCE_NOT_FOUND) { return null; } } private async Task<Command> ExecuteGetResourceCommandAsync(string name, CancellationToken cancellationToken) { // We are sending the command directly here because the Extension requires us to know the type. var getResourceCommand = new Command() { Uri = new LimeUri($"/{_resourceName}/{Uri.EscapeDataString(name)}"), Method = CommandMethod.Get, }; var resourceCommandResult = await _sender.ProcessCommandAsync( getResourceCommand, cancellationToken); return resourceCommandResult; } } }
apache-2.0
C#
c5b233a19934274b6d8dfe1c73f841b8485c4d5a
Fix typo in mock instance
Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector
KenticoInspector.Reports.Tests/Helpers/MockInstances.cs
KenticoInspector.Reports.Tests/Helpers/MockInstances.cs
using KenticoInspector.Core.Models; using System; namespace KenticoInspector.Reports.Tests.Helpers { public static class MockInstances { public static Instance Kentico9 = new Instance { Name = "K9 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico9", Url = "http://kentico9.com", DatabaseSettings = null }; public static Instance Kentico10 = new Instance { Name = "K10 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico10", Url = "http://kentico10.com", DatabaseSettings = null }; public static Instance Kentico11 = new Instance { Name = "K11 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico11", Url = "http://kentico11.com", DatabaseSettings = null }; public static Instance Kentico12 = new Instance { Name = "K11 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico12", Url = "http://kentico12.com", DatabaseSettings = null }; public static Instance Get(int majorVersion) { switch (majorVersion) { case 9: return Kentico9; case 10: return Kentico10; case 11: return Kentico11; case 12: return Kentico12; } return null; } } }
using KenticoInspector.Core.Models; using System; namespace KenticoInspector.Reports.Tests.Helpers { public static class MockInstances { public static Instance Kentico9 = new Instance { Name = "K9 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico9", Url = "http://kentico9.com", DatabaseSettings = null }; public static Instance Kentico10 = new Instance { Name = "K11 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico10", Url = "http://kentico10.com", DatabaseSettings = null }; public static Instance Kentico11 = new Instance { Name = "K11 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico11", Url = "http://kentico11.com", DatabaseSettings = null }; public static Instance Kentico12 = new Instance { Name = "K11 Test Instance", Guid = Guid.NewGuid(), Path = "C:\\inetpub\\wwwroot\\Kentico12", Url = "http://kentico12.com", DatabaseSettings = null }; public static Instance Get(int majorVersion) { switch (majorVersion) { case 9: return Kentico9; case 10: return Kentico10; case 11: return Kentico11; case 12: return Kentico12; } return null; } } }
mit
C#
55f7db963969b0007311464a7d784c56e4a7d0d9
remove commented out code and unused using
jonsequitur/PocketLogger
Pocket.Logger/Disposable.cs
Pocket.Logger/Disposable.cs
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Pocket { [DebuggerStepThrough] internal static class Disposable { private static readonly IDisposable empty = Create(() => { }); public static IDisposable Create(Action dispose) => new AnonymousDisposable(dispose); public static IDisposable Empty { get; } = empty; private class AnonymousDisposable : IDisposable { private Action dispose; public AnonymousDisposable(Action dispose) => this.dispose = dispose ?? throw new ArgumentNullException(nameof(dispose)); public void Dispose() { dispose?.Invoke(); dispose = null; } } } [DebuggerStepThrough] internal class CompositeDisposable : IDisposable, IEnumerable<IDisposable> { private bool isDisposed = false; private readonly List<IDisposable> disposables = new List<IDisposable>(); public void Add(IDisposable disposable) { if (disposable == null) { throw new ArgumentNullException(nameof(disposable)); } if (isDisposed) { disposable.Dispose(); } disposables.Add(disposable); } public void Add(Action dispose) => Add(Disposable.Create(dispose)); public void Dispose() { isDisposed = true; foreach (var disposable in disposables.ToArray()) { disposables.Remove(disposable); disposable.Dispose(); } } public IEnumerator<IDisposable> GetEnumerator() => disposables.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Pocket { [DebuggerStepThrough] internal static class Disposable { private static readonly IDisposable empty = Create(() => { }); public static IDisposable Create(Action dispose) => new AnonymousDisposable(dispose); public static IDisposable Empty { get; } = empty; private class AnonymousDisposable : IDisposable { private Action dispose; public AnonymousDisposable(Action dispose) => this.dispose = dispose ?? throw new ArgumentNullException(nameof(dispose)); public void Dispose() { dispose?.Invoke(); dispose = null; } } } [DebuggerStepThrough] internal class CompositeDisposable : IDisposable, IEnumerable<IDisposable> { private bool isDisposed = false; private readonly List<IDisposable> disposables = new List<IDisposable>(); public void Add(IDisposable disposable) { if (disposable == null) { throw new ArgumentNullException(nameof(disposable)); } if (isDisposed) { disposable.Dispose(); } disposables.Add(disposable); } public void Add(Action dispose) => Add(Disposable.Create(dispose)); public void Dispose() { isDisposed = true; foreach (var disposable in disposables.ToArray()) { disposables.Remove(disposable); disposable.Dispose(); } // // while (disposables.TryTake(out var disposable)) // { // disposable.Dispose(); // } } public IEnumerator<IDisposable> GetEnumerator() => disposables.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
mit
C#
a5fedf0d52b48ae92a7bc722737ab35c64ac9cf3
Fix typo in header
GNOME/hyena,GNOME/hyena,dufoli/hyena,petejohanson/hyena,dufoli/hyena,arfbtwn/hyena,arfbtwn/hyena,petejohanson/hyena
src/Hyena/Hyena.Metrics/Sample.cs
src/Hyena/Hyena.Metrics/Sample.cs
// // Sample.cs // // Author: // Gabriel Burt <gabriel.burt@gmail.com> // // Copyright (c) 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Hyena.Data.Sqlite; namespace Hyena.Metrics { public class Sample { [DatabaseColumn (Constraints = DatabaseColumnConstraints.PrimaryKey)] private long Id { get; set; } [DatabaseColumn] public string MetricName { get; protected set; } [DatabaseColumn] public DateTime Stamp { get; protected set; } [DatabaseColumn] public string Value { get; protected set; } // For SqliteModelProvider's use public Sample () {} public Sample (Metric metric, object value) { MetricName = metric.FullName; Stamp = DateTime.Now; Value = value == null ? "" : value.ToString (); } } }
// // Metric.cs // // Author: // Gabriel Burt <gabriel.burt@gmail.com> // // Copyright (c) 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Hyena.Data.Sqlite; namespace Hyena.Metrics { public class Sample { [DatabaseColumn (Constraints = DatabaseColumnConstraints.PrimaryKey)] private long Id { get; set; } [DatabaseColumn] public string MetricName { get; protected set; } [DatabaseColumn] public DateTime Stamp { get; protected set; } [DatabaseColumn] public string Value { get; protected set; } // For SqliteModelProvider's use public Sample () {} public Sample (Metric metric, object value) { MetricName = metric.FullName; Stamp = DateTime.Now; Value = value == null ? "" : value.ToString (); } } }
mit
C#
5fb5ef1264c0e824fbfa89b27ca81e752e60442d
Update to v4.25
SotoiGhost/FacebookComponents,SotoiGhost/FacebookComponents
Facebook.Android/build.cake
Facebook.Android/build.cake
#load "../common.cake" var FB_NUGET_VERSION = "4.25.0"; var AN_NUGET_VERSION = "4.25.0"; var FB_VERSION = "4.25.0"; var FB_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}.aar", FB_VERSION); var FB_DOCS_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}-javadoc.jar", FB_VERSION); var AN_VERSION = "4.25.0"; var AN_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/audience-network-sdk/{0}/audience-network-sdk-{0}.aar", AN_VERSION); var TARGET = Argument ("t", Argument ("target", "Default")); var buildSpec = new BuildSpec () { Libs = new [] { new DefaultSolutionBuilder { AlwaysUseMSBuild = true, SolutionPath = "./Xamarin.Facebook.sln", BuildsOn = BuildPlatforms.Mac, OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/Xamarin.Facebook/bin/Release/Xamarin.Facebook.dll" }, new OutputFileCopy { FromFile = "./source/Xamarin.Facebook.AudienceNetwork/bin/Release/Xamarin.Facebook.AudienceNetwork.dll" } } } }, Samples = new [] { new DefaultSolutionBuilder { SolutionPath = "./samples/HelloFacebookSample.sln", AlwaysUseMSBuild = true }, new DefaultSolutionBuilder { SolutionPath = "./samples/MessengerSendSample.sln", AlwaysUseMSBuild = true }, new DefaultSolutionBuilder { SolutionPath = "./samples/AudienceNetworkSample.sln", AlwaysUseMSBuild = true }, }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.Android.nuspec", Version = FB_NUGET_VERSION }, new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.AudienceNetwork.Android.nuspec", Version = AN_NUGET_VERSION }, }, Components = new [] { new Component { ManifestDirectory = "./component" }, }, }; Task ("externals") .WithCriteria (!FileExists ("./externals/facebook.aar")) .Does (() => { EnsureDirectoryExists ("./externals/"); // Download the FB aar DownloadFile (FB_URL, "./externals/facebook.aar"); // Download, and unzip the docs .jar DownloadFile (FB_DOCS_URL, "./externals/facebook-docs.jar"); EnsureDirectoryExists ("./externals/fb-docs"); Unzip ("./externals/facebook-docs.jar", "./externals/fb-docs"); // Download the FB aar DownloadFile (AN_URL, "./externals/audiencenetwork.aar"); }); Task ("clean").IsDependentOn ("clean-base").Does (() => { if (DirectoryExists ("./externals/")) DeleteDirectory ("./externals", true); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
#load "../common.cake" var FB_NUGET_VERSION = "4.24.0"; var AN_NUGET_VERSION = "4.24.0"; var FB_VERSION = "4.24.0"; var FB_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}.aar", FB_VERSION); var FB_DOCS_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}-javadoc.jar", FB_VERSION); var AN_VERSION = "4.24.0"; var AN_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/audience-network-sdk/{0}/audience-network-sdk-{0}.aar", AN_VERSION); var TARGET = Argument ("t", Argument ("target", "Default")); var buildSpec = new BuildSpec () { Libs = new [] { new DefaultSolutionBuilder { AlwaysUseMSBuild = true, SolutionPath = "./Xamarin.Facebook.sln", BuildsOn = BuildPlatforms.Mac, OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/Xamarin.Facebook/bin/Release/Xamarin.Facebook.dll" }, new OutputFileCopy { FromFile = "./source/Xamarin.Facebook.AudienceNetwork/bin/Release/Xamarin.Facebook.AudienceNetwork.dll" } } } }, Samples = new [] { new DefaultSolutionBuilder { SolutionPath = "./samples/HelloFacebookSample.sln", AlwaysUseMSBuild = true }, new DefaultSolutionBuilder { SolutionPath = "./samples/MessengerSendSample.sln", AlwaysUseMSBuild = true }, new DefaultSolutionBuilder { SolutionPath = "./samples/AudienceNetworkSample.sln", AlwaysUseMSBuild = true }, }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.Android.nuspec", Version = FB_NUGET_VERSION }, new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.AudienceNetwork.Android.nuspec", Version = AN_NUGET_VERSION }, }, Components = new [] { new Component { ManifestDirectory = "./component" }, }, }; Task ("externals") .WithCriteria (!FileExists ("./externals/facebook.aar")) .Does (() => { EnsureDirectoryExists ("./externals/"); // Download the FB aar DownloadFile (FB_URL, "./externals/facebook.aar"); // Download, and unzip the docs .jar DownloadFile (FB_DOCS_URL, "./externals/facebook-docs.jar"); EnsureDirectoryExists ("./externals/fb-docs"); Unzip ("./externals/facebook-docs.jar", "./externals/fb-docs"); // Download the FB aar DownloadFile (AN_URL, "./externals/audiencenetwork.aar"); }); Task ("clean").IsDependentOn ("clean-base").Does (() => { if (DirectoryExists ("./externals/")) DeleteDirectory ("./externals", true); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
mit
C#
b2fb55491d93fd36ec9387b88aa37fd25a7d7f78
Update GoogleAnalyticsPlatform.cs
KSemenenko/GoogleAnalyticsForXamarinForms,KSemenenko/Google-Analytics-for-Xamarin-Forms
Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.WindowsStore/GoogleAnalyticsPlatform.cs
Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.WindowsStore/GoogleAnalyticsPlatform.cs
using System.Threading.Tasks; using Windows.UI.Xaml; namespace Plugin.GoogleAnalytics { public partial class GoogleAnalytics { static GoogleAnalytics() { Application.Current.UnhandledException += CurrentDomain_UnhandledException; } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (!Current.Config.ReportUncaughtExceptions) return; Current.Tracker.SendException(e.Exception, true); Task.Delay(1000).Wait(); //delay } } }
using System.Threading.Tasks; using Windows.UI.Xaml; namespace Plugin.GoogleAnalytics { public partial class GoogleAnalytics { static GoogleAnalytics() { Application.Current.UnhandledException += CurrentDomain_UnhandledException; } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Current.Tracker.SendException(e.Exception, true); Task.Delay(1000).Wait(); //delay } } }
mit
C#
819ab03cabaecc9632d205a03ef92f3d04ba458a
Remove unnecessary debugging printout
opcon/QuickFont,opcon/QuickFont
QuickFont.Shared/GDIFont.cs
QuickFont.Shared/GDIFont.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.Linq; using System.Text; namespace QuickFont { public class GDIFont : IFont, IDisposable { private Font _font; private FontFamily _fontFamily; public float Size { get { return _font.Size; } } /// <summary> /// Creates a GDI+ Font from the specified font file /// </summary> /// <param name="fontPath">The path to the font file</param> /// <param name="size"></param> /// <param name="style"></param> /// <param name="superSampleLevels"></param> /// <param name="scale"></param> public GDIFont(string fontPath, float size, FontStyle style, int superSampleLevels = 1, float scale = 1.0f) { try { var pfc = new PrivateFontCollection(); pfc.AddFontFile(fontPath); _fontFamily = pfc.Families[0]; } catch (System.IO.FileNotFoundException ex) { //font file could not be found, check if it exists in the installed font collection var installed = new InstalledFontCollection(); _fontFamily = installed.Families.FirstOrDefault(family => string.Equals(fontPath, family.Name)); //if we can't find the font file at all, use the system default font if (_fontFamily == null) _fontFamily = SystemFonts.DefaultFont.FontFamily; } if (!_fontFamily.IsStyleAvailable(style)) throw new ArgumentException("Font file: " + fontPath + " does not support style: " + style); _font = new Font(_fontFamily, size * scale * superSampleLevels, style); } public Point DrawString(string s, Graphics graph, Brush color, int x, int y, float height) { graph.DrawString(s, _font, color, x, y); return Point.Empty; } public SizeF MeasureString(string s, Graphics graph) { return graph.MeasureString(s, _font); } public override string ToString() { return _font.Name; } public void Dispose() { _font.Dispose(); _fontFamily.Dispose(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.Linq; using System.Text; namespace QuickFont { public class GDIFont : IFont, IDisposable { private Font _font; private FontFamily _fontFamily; public float Size { get { return _font.Size; } } /// <summary> /// Creates a GDI+ Font from the specified font file /// </summary> /// <param name="fontPath">The path to the font file</param> /// <param name="size"></param> /// <param name="style"></param> /// <param name="superSampleLevels"></param> /// <param name="scale"></param> public GDIFont(string fontPath, float size, FontStyle style, int superSampleLevels = 1, float scale = 1.0f) { try { var pfc = new PrivateFontCollection(); pfc.AddFontFile(fontPath); _fontFamily = pfc.Families[0]; } catch (System.IO.FileNotFoundException ex) { //font file could not be found, check if it exists in the installed font collection var installed = new InstalledFontCollection(); _fontFamily = installed.Families.FirstOrDefault(family => string.Equals(fontPath, family.Name)); //if we can't find the font file at all, use the system default font if (_fontFamily == null) _fontFamily = SystemFonts.DefaultFont.FontFamily; } if (!_fontFamily.IsStyleAvailable(style)) throw new ArgumentException("Font file: " + fontPath + " does not support style: " + style); _font = new Font(_fontFamily, size * scale * superSampleLevels, style); } public Point DrawString(string s, Graphics graph, Brush color, int x, int y, float height) { graph.DrawString(s, _font, color, x, y); Debug.WriteLine(string.Format("Loading character {0}, y position is {1}", s, y)); return Point.Empty; } public SizeF MeasureString(string s, Graphics graph) { return graph.MeasureString(s, _font); } public override string ToString() { return _font.Name; } public void Dispose() { _font.Dispose(); _fontFamily.Dispose(); } } }
mit
C#
90fc070b419e6ac9e8f59df2dad898d1559c0b51
Adjust sample bass counter location
peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework
osu.Framework/Audio/Sample/SampleBass.cs
osu.Framework/Audio/Sample/SampleBass.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 ManagedBass; using osu.Framework.Allocation; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Audio.Sample { internal sealed class SampleBass : Sample, IBassAudio { private volatile int sampleId; public override bool IsLoaded => sampleId != 0; internal SampleBass(byte[] data, ConcurrentQueue<Task> customPendingActions = null, int concurrency = DEFAULT_CONCURRENCY) : base(concurrency) { if (customPendingActions != null) PendingActions = customPendingActions; EnqueueAction(() => { sampleId = loadSample(data); loaded_sample_bytes.Value += loadedBytes = data.Length; }); } protected override void Dispose(bool disposing) { if (IsLoaded) { Bass.SampleFree(sampleId); loaded_sample_bytes.Value -= loadedBytes; } base.Dispose(disposing); } void IBassAudio.UpdateDevice(int deviceIndex) { if (IsLoaded) // counter-intuitively, this is the correct API to use to migrate a sample to a new device. Bass.ChannelSetDevice(sampleId, deviceIndex); } public int CreateChannel() => Bass.SampleGetChannel(sampleId); private long loadedBytes; private static readonly GlobalStatistic<long> loaded_sample_bytes = GlobalStatistics.Get<long>("Native", nameof(SampleBass)); private int loadSample(byte[] data) { const BassFlags flags = BassFlags.Default | BassFlags.SampleOverrideLongestPlaying; if (RuntimeInfo.SupportsJIT) return Bass.SampleLoad(data, 0, data.Length, PlaybackConcurrency, flags); using (var handle = new ObjectHandle<byte[]>(data, GCHandleType.Pinned)) return Bass.SampleLoad(handle.Address, 0, data.Length, PlaybackConcurrency, flags); } } }
// 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 ManagedBass; using osu.Framework.Allocation; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Audio.Sample { internal sealed class SampleBass : Sample, IBassAudio { private volatile int sampleId; public override bool IsLoaded => sampleId != 0; internal SampleBass(byte[] data, ConcurrentQueue<Task> customPendingActions = null, int concurrency = DEFAULT_CONCURRENCY) : base(concurrency) { if (customPendingActions != null) PendingActions = customPendingActions; EnqueueAction(() => { sampleId = loadSample(data); }); } protected override void Dispose(bool disposing) { loaded_sample_bytes.Value -= loadedBytes; Bass.SampleFree(sampleId); base.Dispose(disposing); } void IBassAudio.UpdateDevice(int deviceIndex) { if (IsLoaded) // counter-intuitively, this is the correct API to use to migrate a sample to a new device. Bass.ChannelSetDevice(sampleId, deviceIndex); } public int CreateChannel() => Bass.SampleGetChannel(sampleId); private long loadedBytes; private static readonly GlobalStatistic<long> loaded_sample_bytes = GlobalStatistics.Get<long>("Native", nameof(SampleBass)); private int loadSample(byte[] data) { const BassFlags flags = BassFlags.Default | BassFlags.SampleOverrideLongestPlaying; loaded_sample_bytes.Value += loadedBytes = data.Length; if (RuntimeInfo.SupportsJIT) return Bass.SampleLoad(data, 0, data.Length, PlaybackConcurrency, flags); using (var handle = new ObjectHandle<byte[]>(data, GCHandleType.Pinned)) return Bass.SampleLoad(handle.Address, 0, data.Length, PlaybackConcurrency, flags); } } }
mit
C#
613f527303d28e4f4dfb1f2c599f50a69fcefc9e
Update Framework.cs
dimmpixeye/Unity3dTools
Runtime/LibEcs/Framework.cs
Runtime/LibEcs/Framework.cs
// Project : ecs.unity // Contacts : Pix - ask@pixeye.games using UnityEngine; using static Pixeye.Actors.LogType; namespace Pixeye.Actors { public static class Framework { public static class Processors { internal static Processor[] storage = new Processor[64]; internal static int length; } public static void Cleanup() { groups.All.Dispose(); for (int i = 0; i < groups.globals.Length; i++) { groups.globals[i] = null; } } public static class Debugger { public static void Log(int logID, params object[] contenxt) { switch (logID) { case NOT_ACTIVE: Debug.LogError($"Entity <b>{contenxt[0]}</b> is not active. You should not add components to an inactive entity. <b> {contenxt[1]}</b> "); break; case ALREADY_HAVE: Debug.LogError($"Entity <b>{contenxt[0]}</b> already have this component: <b>{contenxt[1]}</b> "); break; case REMOVE_NON_EXISTANT: Debug.LogError($"Entity <b>{contenxt[0]}</b> is deleted. You can't remove a component from a deleted entity. <b>{contenxt[1]}</b> "); break; case NULL_ENTITY: Debug.LogError($"Entity <b>{contenxt[0]}</b> is null. Use <color=#ff0000ff>Entity.Create</color> to register a new entity first. <b>{contenxt[1]}</b> "); break; case TAGS_LIMIT_REACHED: Debug.LogError($"Entity <b>{contenxt[0]}</b> has reached tag capacity. Go to Tools->Actors->Tags->Size to increase cap. Current cap: <b>{contenxt[1]}</b> "); break; case DESTROYED: Debug.LogError($"You are trying to release already destroyed entity with ID <b>{contenxt[0]}</b>, <b>{contenxt[1]}</b>"); break; } } } public static SettingsEngine Settings = new SettingsEngine(); } public class groups { public GroupCore this[int index] => globals[index]; public static bool has(int index) { return globals.Length > index && globals[index] != null; } public static GroupCore[] globals = new GroupCore[32]; internal static CacheGroup All = new CacheGroup(); internal static FamilyGroupTags ByTag = new FamilyGroupTags(); internal static FamilyGroupTags ByType = new FamilyGroupTags(); } struct LogType { public const int NOT_ACTIVE = 0; public const int ALREADY_HAVE = 1; public const int REMOVE_NON_EXISTANT = 2; public const int NULL_ENTITY = 3; public const int TAGS_LIMIT_REACHED = 4; public const int DESTROYED = 5; } }
// Project : ecs.unity // Contacts : Pix - ask@pixeye.games using UnityEngine; using static Pixeye.Actors.LogType; namespace Pixeye.Actors { public static class Framework { public static class Processors { internal static Processor[] storage = new Processor[64]; internal static int length; } public static void Cleanup() { groups.All.Dispose(); for (int i = 0; i < groups.globals.Length; i++) { groups.globals[i] = null; } } public static class Debugger { public static void Log(int logID, params object[] contenxt) { switch (logID) { case NOT_ACTIVE: Debug.LogError($"Entity <b>{contenxt[0]}</b> is not active. You should not add components to an inactive entity. <b> {contenxt[1]}</b> "); break; case ALREADY_HAVE: Debug.LogError($"Entity <b>{contenxt[0]}</b> already have this component: <b>{contenxt[1]}</b> "); break; case REMOVE_NON_EXISTANT: Debug.LogError($"Entity <b>{contenxt[0]}</b> is deleted. You can't remove a component from a deleted entity. <b>{contenxt[1]}</b> "); break; case NULL_ENTITY: Debug.LogError($"Entity <b>{contenxt[0]}</b> is null. Use <color=#ff0000ff>Entity.Create</color> to register a new entity first. <b>{contenxt[1]}</b> "); break; case TAGS_LIMIT_REACHED: Debug.LogError($"Entity <b>{contenxt[0]}</b> has reached tag capacity. Go to Tools->Actors->Tags->Size to increase cap. Current cap: <b>{contenxt[1]}</b> "); break; case DESTROYED: Debug.LogError($"You are trying to release already destroyed entity with ID <b>{contenxt[0]}</b>, <b>{contenxt[1]}</b>"); break; } } } public static SettingsEngine Settings = new SettingsEngine(); } public class groups { public GroupCore this[int index] => globals[index]; internal static GroupCore[] globals = new GroupCore[32]; internal static CacheGroup All = new CacheGroup(); internal static FamilyGroupTags ByTag = new FamilyGroupTags(); internal static FamilyGroupTags ByType = new FamilyGroupTags(); } struct LogType { public const int NOT_ACTIVE = 0; public const int ALREADY_HAVE = 1; public const int REMOVE_NON_EXISTANT = 2; public const int NULL_ENTITY = 3; public const int TAGS_LIMIT_REACHED = 4; public const int DESTROYED = 5; } }
mit
C#
f48e3a3b9eb02955ba388ca36e4b0dd2c99c00af
Add overload to retrieve specific template
Puzzlepart/PnP-Sites-Core,PieterVeenstra/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,m-carter1/PnP-Sites-Core,phillipharding/PnP-Sites-Core,BobGerman/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,Oaden/PnP-Sites-Core,Puzzlepart/PnP-Sites-Core,itacs/PnP-Sites-Core,comblox/PnP-Sites-Core,itacs/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,Oaden/PnP-Sites-Core,comblox/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,m-carter1/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,BobGerman/PnP-Sites-Core,PieterVeenstra/PnP-Sites-Core
Core/OfficeDevPnP.Core/Framework/Provisioning/BaseTemplates/BaseTemplateManager.cs
Core/OfficeDevPnP.Core/Framework/Provisioning/BaseTemplates/BaseTemplateManager.cs
using System; using System.IO; using System.Reflection; using System.Xml.Linq; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml; using OfficeDevPnP.Core.Utilities; using OfficeDevPnP.Core.Framework.Provisioning.Providers; namespace Microsoft.SharePoint.Client { /// <summary> /// This class will be used to provide access to the right base template configuration /// </summary> public static class BaseTemplateManager { public static ProvisioningTemplate GetBaseTemplate(this Web web) { web.Context.Load(web, p => p.WebTemplate, p => p.Configuration); web.Context.ExecuteQueryRetry(); return GetBaseTemplate(web, web.WebTemplate, web.Configuration); } public static ProvisioningTemplate GetBaseTemplate(this Web web, string webTemplate, short configuration) { ProvisioningTemplate provisioningTemplate = null; try { string baseTemplate = string.Format("OfficeDevPnP.Core.Framework.Provisioning.BaseTemplates.v{0}.{1}{2}Template.xml", GetSharePointVersion(), webTemplate, configuration); using (Stream stream = typeof(BaseTemplateManager).Assembly.GetManifestResourceStream(baseTemplate)) { // Get the XML document from the stream ITemplateFormatter formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLPnPSchemaVersion.V201505); // And convert it into a ProvisioningTemplate provisioningTemplate = formatter.ToProvisioningTemplate(stream); } } catch (Exception) { //TODO: log message } return provisioningTemplate; } private static int GetSharePointVersion() { Assembly asm = Assembly.GetAssembly(typeof(Site)); return asm.GetName().Version.Major; } } }
using System; using System.IO; using System.Reflection; using System.Xml.Linq; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml; using OfficeDevPnP.Core.Utilities; using OfficeDevPnP.Core.Framework.Provisioning.Providers; namespace Microsoft.SharePoint.Client { /// <summary> /// This class will be used to provide access to the right base template configuration /// </summary> public static class BaseTemplateManager { public static ProvisioningTemplate GetBaseTemplate(this Web web) { web.Context.Load(web, p => p.WebTemplate, p => p.Configuration); web.Context.ExecuteQueryRetry(); ProvisioningTemplate provisioningTemplate = null; try { string baseTemplate = string.Format("OfficeDevPnP.Core.Framework.Provisioning.BaseTemplates.v{0}.{1}{2}Template.xml", GetSharePointVersion(), web.WebTemplate, web.Configuration); using (Stream stream = typeof(BaseTemplateManager).Assembly.GetManifestResourceStream(baseTemplate)) { // Get the XML document from the stream ITemplateFormatter formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLPnPSchemaVersion.V201505); // And convert it into a ProvisioningTemplate provisioningTemplate = formatter.ToProvisioningTemplate(stream); } } catch(Exception) { //TODO: log message } return provisioningTemplate; } private static int GetSharePointVersion() { Assembly asm = Assembly.GetAssembly(typeof(Site)); return asm.GetName().Version.Major; } } }
mit
C#
e27fb139dd2ebd266712e5c804abc34553f50c0b
Add input event to dotnetcore2.0 example function
lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda
examples/dotnetcore2.0/Function.cs
examples/dotnetcore2.0/Function.cs
// Compile with: // docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub // Run with: // docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some" using Amazon.Lambda.Core; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace test { public class Function { public string FunctionHandler(object inputEvent, ILambdaContext context) { context.Logger.Log($"inputEvent: {inputEvent}"); return "Hello World!"; } } }
// Compile with: // docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub // Run with: // docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using System.IO; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace test { public class Function { public string FunctionHandler(Stream stream, ILambdaContext context) { context.Logger.Log("Log Hello world"); return "Hallo world!"; } } }
mit
C#
387e3fcbab0aa64d78ecc6ba864f90a4f37a049d
Update to MD5 hash PR.
Gibe/Gibe.DittoProcessors
Gibe.DittoProcessors/Processors/StringToMd5HashAttribute.cs
Gibe.DittoProcessors/Processors/StringToMd5HashAttribute.cs
using System; using System.Text; using System.Security.Cryptography; namespace Gibe.DittoProcessors.Processors { public class StringToMd5HashAttribute : TestableDittoProcessorAttribute { public override object ProcessValue() { if (Value == null) throw new NullReferenceException(); var stringValue = Value as string; byte[] encodedValue = new UTF8Encoding().GetBytes(stringValue); byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedValue); // string representation (similar to UNIX format) return BitConverter.ToString(hashValue).Replace("-", string.Empty).ToLower(); } } }
using System; using System.Text; using System.Security.Cryptography; namespace Gibe.DittoProcessors.Processors { public class StringToMd5HashAttribute : TestableDittoProcessorAttribute { public override object ProcessValue() { if (Value == null) throw new NullReferenceException(); var stringValue = Value as string; // byte array representation of that string byte[] encodedValue = new UTF8Encoding().GetBytes(stringValue); // need MD5 to calculate the hash byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedValue); // string representation (similar to UNIX format) return BitConverter.ToString(hashValue).Replace("-", string.Empty).ToLower(); } } }
mit
C#
4ac85e408ec7b58a90065d8e0bede3e7629a7aec
Update for .NET 6 rc2
rockfordlhotka/csla,rockfordlhotka/csla,rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,MarimerLLC/csla
Source/Csla.Axml.Android/Resources/Resource.Designer.cs
Source/Csla.Axml.Android/Resources/Resource.Designer.cs
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)] namespace Csla.Axml { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.1.0.11")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class String { // aapt resource value: 0x7F010000 public static int ApplicationName = 2130771968; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)] namespace Csla.Axml { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.1.0.10")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class String { // aapt resource value: 0x7F010000 public static int ApplicationName = 2130771968; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
mit
C#
b8385e621c24366fbdd9d39b160e5e7c779ecfda
update version
prodot/ReCommended-Extension
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2021 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("5.5.0.0")] [assembly: AssemblyFileVersion("5.5.0")]
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2021 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("5.4.1.0")] [assembly: AssemblyFileVersion("5.4.1")]
apache-2.0
C#
d96abf0cedaee963971f6adf572de7f428243123
revert CommonAssemblyInfo
panesofglass/Hopac,jacqueline-homan/Hopac,jacqueline-homan/Hopac,panesofglass/Hopac,Hopac/Hopac,Hopac/Hopac
Libs/Hopac.Core/Assembly.cs
Libs/Hopac.Core/Assembly.cs
// Copyright (C) by Housemarque, Inc. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Hopac.Core is really only intended to be used by other Hopac libraries. [assembly: InternalsVisibleTo("Hopac")] [assembly: InternalsVisibleTo("Hopac.Platform")] namespace Hopac { #pragma warning disable 1591 // Missing XML comment public static class CommonAssemblyInfo { public const string Description = "A library for Higher-Order, Parallel, Asynchronous and Concurrent programming in F#."; public const string Configuration = ""; public const string Product = "Hopac"; public const string Company = "Housemarque Inc."; public const string Copyright = "© Housemarque Inc."; public const string Version = "0.0.0.35"; public const string FileVersion = Version; public const string Trademark = ""; public const string Culture = ""; } }
// Copyright (C) by Housemarque, Inc. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Hopac.Core is really only intended to be used by other Hopac libraries. [assembly: InternalsVisibleTo("Hopac")] [assembly: InternalsVisibleTo("Hopac.Platform")]
mit
C#
833f09085df3510a8ee1b9eef6500c08f2463d87
edit cashier repo
VladTsiukin/AirlineTicketOffice
AirlineTicketOffice.Repository/Repositories/CashierRepository.cs
AirlineTicketOffice.Repository/Repositories/CashierRepository.cs
using AirlineTicketOffice.Model.IRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using AirlineTicketOffice.Model.Models; using System.Linq.Expressions; using System.Data.Entity; using AirlineTicketOffice.Data; using System.Threading.Tasks; namespace AirlineTicketOffice.Repository.Repositories { public sealed class CashierRepository : BaseModelRepository<CashierModel>, ICashierRepository { public IEnumerable<CashierModel> GetAll() { return _context.Cashiers.AsNoTracking().ToArray().Select((Cashier c) => { return new CashierModel { CashierID = c.CashierID, NumberOfOffices = c.NumberOfOffices, FullName = c.FullName }; }); } } }
using AirlineTicketOffice.Model.IRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using AirlineTicketOffice.Model.Models; using System.Linq.Expressions; using System.Data.Entity; using AirlineTicketOffice.Data; using System.Threading.Tasks; namespace AirlineTicketOffice.Repository.Repositories { public sealed class CashierRepository : BaseModelRepository<Cashier>, ICashierRepository { public IEnumerable<CashierModel> GetAll() { return _context.Cashiers.AsNoTracking().ToArray().Select((Cashier c) => { return new CashierModel { CashierID = c.CashierID, NumberOfOffices = c.NumberOfOffices, FullName = c.FullName }; }); } } }
mit
C#
1df6ec448fa17fef17195df1e399f4ff806163c0
Fix bug when users first login.
Pathfinder-Fr/YAFNET,mexxanit/YAFNET,YAFNET/YAFNET,mexxanit/YAFNET,mexxanit/YAFNET,moorehojer/YAFNET,moorehojer/YAFNET,moorehojer/YAFNET,Pathfinder-Fr/YAFNET,Pathfinder-Fr/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET
yafsrc/YetAnotherForum.NET/controls/ForumWelcome.ascx.cs
yafsrc/YetAnotherForum.NET/controls/ForumWelcome.ascx.cs
/* Yet Another Forum.NET * Copyright (C) 2006-2009 Jaben Cargman * http://www.yetanotherforum.net/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ namespace YAF.Controls { using System; using YAF.Classes; using YAF.Classes.Core; using YAF.Classes.Utils; /// <summary> /// The forum welcome. /// </summary> public partial class ForumWelcome : BaseUserControl { /// <summary> /// Initializes a new instance of the <see cref="ForumWelcome"/> class. /// </summary> public ForumWelcome() { PreRender += new EventHandler(ForumWelcome_PreRender); } /// <summary> /// The forum welcome_ pre render. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void ForumWelcome_PreRender(object sender, EventArgs e) { this.TimeNow.Text = PageContext.Localization.GetTextFormatted("Current_Time", YafServices.DateTime.FormatTime(DateTime.Now)); if (Mession.LastVisit != DateTime.MinValue) { this.TimeLastVisit.Visible = true; this.TimeLastVisit.Text = PageContext.Localization.GetTextFormatted( "last_visit", YafServices.DateTime.FormatDateTime(Mession.LastVisit)); } else { this.TimeLastVisit.Visible = false; } if (PageContext.UnreadPrivate > 0) { this.UnreadMsgs.Visible = true; this.UnreadMsgs.NavigateUrl = YafBuildLink.GetLink(ForumPages.cp_pm); if (PageContext.UnreadPrivate == 1) { this.UnreadMsgs.Text = PageContext.Localization.GetTextFormatted("unread1", PageContext.UnreadPrivate); } else { this.UnreadMsgs.Text = PageContext.Localization.GetTextFormatted("unread0", PageContext.UnreadPrivate); } } } } }
/* Yet Another Forum.NET * Copyright (C) 2006-2009 Jaben Cargman * http://www.yetanotherforum.net/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ namespace YAF.Controls { using System; using YAF.Classes; using YAF.Classes.Core; using YAF.Classes.Utils; /// <summary> /// The forum welcome. /// </summary> public partial class ForumWelcome : BaseUserControl { /// <summary> /// Initializes a new instance of the <see cref="ForumWelcome"/> class. /// </summary> public ForumWelcome() { PreRender += new EventHandler(ForumWelcome_PreRender); } /// <summary> /// The forum welcome_ pre render. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void ForumWelcome_PreRender(object sender, EventArgs e) { this.TimeNow.Text = PageContext.Localization.GetTextFormatted("Current_Time", YafServices.DateTime.FormatTime(DateTime.Now)); this.TimeLastVisit.Text = PageContext.Localization.GetTextFormatted("last_visit", YafServices.DateTime.FormatDateTime(Mession.LastVisit)); if (PageContext.UnreadPrivate > 0) { this.UnreadMsgs.Visible = true; this.UnreadMsgs.NavigateUrl = YafBuildLink.GetLink(ForumPages.cp_pm); if (PageContext.UnreadPrivate == 1) { this.UnreadMsgs.Text = PageContext.Localization.GetTextFormatted("unread1", PageContext.UnreadPrivate); } else { this.UnreadMsgs.Text = PageContext.Localization.GetTextFormatted("unread0", PageContext.UnreadPrivate); } } } } }
apache-2.0
C#
caf9fb4b1f37e70574d7c19f97e4c35179fde41c
Add several User32.dll NativeMethods
tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server
src/Tgstation.Server.Host/NativeMethods.cs
src/Tgstation.Server.Host/NativeMethods.cs
using System; using System.Runtime.InteropServices; using System.Text; namespace Tgstation.Server.Host { /// <summary> /// Native methods used by the code /// </summary> static class NativeMethods { /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid /// </summary> [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-findwindoww /// </summary> [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage /// </summary> [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); /// <summary> /// See https://msdn.microsoft.com/en-us/library/ms633493(v=VS.85).aspx /// </summary> public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam); /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-enumchildwindows /// </summary> [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam); /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw /// </summary> [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); /// <summary> /// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx /// </summary> [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createsymboliclinkw /// </summary> [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags); } }
using System; using System.Runtime.InteropServices; namespace Tgstation.Server.Host { /// <summary> /// Native methods used by the code /// </summary> static class NativeMethods { /// <summary> /// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx /// </summary> [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); /// <summary> /// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createsymboliclinkw /// </summary> [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags); } }
agpl-3.0
C#
0d6eee3ccdd7aba89dc717e9fd77aac6e8ba324f
Update AutoFitMode.cs
PanAndZoom/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/PanAndZoom,wieslawsoltes/MatrixPanAndZoomDemo,wieslawsoltes/PanAndZoom
src/Wpf.Controls.PanAndZoom/AutoFitMode.cs
src/Wpf.Controls.PanAndZoom/AutoFitMode.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. namespace Wpf.Controls.PanAndZoom { /// <summary> /// Specifies auto-fit modes. /// </summary> public enum AutoFitMode { /// <summary> /// Specifies a none mode. /// </summary> None, /// <summary> /// Specifies an extent mode. /// </summary> Extent, /// <summary> /// Specifies a fill mode. /// </summary> 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. namespace Wpf.Controls.PanAndZoom { /// <summary> /// /// </summary> public enum AutoFitMode { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> Extent, /// <summary> /// /// </summary> Fill } }
mit
C#
ed2d31071ba9b2e0c335af8196ce01d52cbc7ef0
Set ToolTipText
larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl
MatterControlLib/PartPreviewWindow/OperationIconButton.cs
MatterControlLib/PartPreviewWindow/OperationIconButton.cs
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg.UI; using MatterHackers.MatterControl.CustomWidgets; namespace MatterHackers.MatterControl.PartPreviewWindow { public class OperationIconButton : IconButton { private SceneSelectionOperation sceneOperation; private ISceneContext sceneContext; public OperationIconButton(SceneSelectionOperation sceneOperation, ISceneContext sceneContext, ThemeConfig theme) : base(sceneOperation.Icon(theme.InvertIcons), theme) { this.sceneOperation = sceneOperation; this.sceneContext = sceneContext; this.ToolTipText = sceneOperation.HelpText ?? sceneOperation.Title; } protected override void OnClick(MouseEventArgs mouseEvent) { sceneOperation.Action?.Invoke(sceneContext); base.OnClick(mouseEvent); } } }
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg.UI; using MatterHackers.MatterControl.CustomWidgets; namespace MatterHackers.MatterControl.PartPreviewWindow { public class OperationIconButton : IconButton { private SceneSelectionOperation sceneOperation; private ISceneContext sceneContext; public OperationIconButton(SceneSelectionOperation sceneOperation, ISceneContext sceneContext, ThemeConfig theme) : base(sceneOperation.Icon(theme.InvertIcons), theme) { this.sceneOperation = sceneOperation; this.sceneContext = sceneContext; } protected override void OnClick(MouseEventArgs mouseEvent) { sceneOperation.Action?.Invoke(sceneContext); base.OnClick(mouseEvent); } } }
bsd-2-clause
C#
266b1c2f95679ac4b95dc0fd7c39f45f41a027c2
test for build
batbuild/duality,Andrea/duality,Andrea/duality
Other/Dependencies/propertygrid/CustomPropertyGrid/ObjectItem.cs
Other/Dependencies/propertygrid/CustomPropertyGrid/ObjectItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AdamsLair.PropertyGrid { public class ObjectItem { private object value = null; private string caption = null; public string Caption { get { return this.caption; } } public object Value { get { return this.value; } } public ObjectItem(object v, string c) { this.value = v; this.caption = c; } public override string ToString() { return this.caption; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AdamsLair.PropertyGrid { public class ObjectItem { private object value = null; private string caption = null; public string Caption { get { return this.caption; } } public object Value { get { return this.value; } } public ObjectItem(object v, string c) { this.value = v; this.caption = c; } public override string ToString() { return this.caption; } } }
mit
C#
5861084e0bbf9c210e8a93aa414c2c8277dac846
make this a class
intari/OpenSimMirror,ft-/opensim-optimizations-wip-extras,zekizeki/agentservice,N3X15/VoxelSim,intari/OpenSimMirror,allquixotic/opensim-autobackup,AlexRa/opensim-mods-Alex,rryk/omp-server,RavenB/opensim,M-O-S-E-S/opensim,RavenB/opensim,bravelittlescientist/opensim-performance,AlphaStaxLLC/taiga,AlexRa/opensim-mods-Alex,AlphaStaxLLC/taiga,cdbean/CySim,TomDataworks/opensim,BogusCurry/arribasim-dev,justinccdev/opensim,cdbean/CySim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,BogusCurry/arribasim-dev,N3X15/VoxelSim,ft-/arribasim-dev-tests,TechplexEngineer/Aurora-Sim,zekizeki/agentservice,zekizeki/agentservice,intari/OpenSimMirror,BogusCurry/arribasim-dev,justinccdev/opensim,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,AlphaStaxLLC/taiga,ft-/arribasim-dev-tests,TomDataworks/opensim,ft-/opensim-optimizations-wip-extras,zekizeki/agentservice,allquixotic/opensim-autobackup,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,zekizeki/agentservice,Michelle-Argus/ArribasimExtract,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-tests,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,N3X15/VoxelSim,OpenSimian/opensimulator,cdbean/CySim,allquixotic/opensim-autobackup,zekizeki/agentservice,AlphaStaxLLC/taiga,rryk/omp-server,bravelittlescientist/opensim-performance,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,rryk/omp-server,justinccdev/opensim,AlphaStaxLLC/taiga,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,TechplexEngineer/Aurora-Sim,justinccdev/opensim,bravelittlescientist/opensim-performance,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip,AlexRa/opensim-mods-Alex,intari/OpenSimMirror,QuillLittlefeather/opensim-1,cdbean/CySim,bravelittlescientist/opensim-performance,bravelittlescientist/opensim-performance,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,cdbean/CySim,M-O-S-E-S/opensim,OpenSimian/opensimulator,ft-/arribasim-dev-extras,TomDataworks/opensim,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-extras,Michelle-Argus/ArribasimExtract,RavenB/opensim,allquixotic/opensim-autobackup,rryk/omp-server,ft-/arribasim-dev-extras,cdbean/CySim,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-extras,justinccdev/opensim,RavenB/opensim,ft-/arribasim-dev-tests,N3X15/VoxelSim,ft-/arribasim-dev-extras,allquixotic/opensim-autobackup,AlexRa/opensim-mods-Alex,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip-tests,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,intari/OpenSimMirror,AlexRa/opensim-mods-Alex,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,TomDataworks/opensim,OpenSimian/opensimulator,AlphaStaxLLC/taiga,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,N3X15/VoxelSim,justinccdev/opensim,AlphaStaxLLC/taiga,rryk/omp-server,RavenB/opensim,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TechplexEngineer/Aurora-Sim,OpenSimian/opensimulator,TomDataworks/opensim,N3X15/VoxelSim,ft-/opensim-optimizations-wip,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,intari/OpenSimMirror,AlexRa/opensim-mods-Alex,N3X15/VoxelSim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,AlphaStaxLLC/taiga,ft-/opensim-optimizations-wip-extras,BogusCurry/arribasim-dev,TechplexEngineer/Aurora-Sim,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,bravelittlescientist/opensim-performance,QuillLittlefeather/opensim-1
OpenSim/Framework/OSUUID.cs
OpenSim/Framework/OSUUID.cs
// OSUUID.cs created with MonoDevelop // User: sdague at 10:17 AM 4/9/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // using System; using libsecondlife; namespace OpenSim.Framework { [Serializable] public class OSUUID: IComparable { public Guid UUID; public OSUUID() {} /* Constructors */ public OSUUID(string s) { if (s == null) UUID = new Guid(); else UUID = new Guid(s); } public OSUUID(Guid g) { UUID = g; } public OSUUID(LLUUID l) { UUID = l.UUID; } public OSUUID(ulong u) { UUID = new Guid(0, 0, 0, BitConverter.GetBytes(u)); } // out conversion public override string ToString() { return UUID.ToString(); } public LLUUID ToLLUUID() { return new LLUUID(UUID); } // for comparison bits public override int GetHashCode() { return UUID.GetHashCode(); } public override bool Equals(object o) { if (!(o is LLUUID)) return false; OSUUID uuid = (OSUUID)o; return UUID == uuid.UUID; } public int CompareTo(object obj) { if (obj is OSUUID) { OSUUID ID = (OSUUID)obj; return this.UUID.CompareTo(ID.UUID); } throw new ArgumentException("object is not a OSUUID"); } // Static methods public static OSUUID Random() { return new OSUUID(Guid.NewGuid()); } public static readonly OSUUID Zero = new OSUUID(); } }
// OSUUID.cs created with MonoDevelop // User: sdague at 10:17 AM 4/9/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // using System; using libsecondlife; namespace OpenSim.Framework { [Serializable] public struct OSUUID: IComparable { public Guid UUID; /* Constructors */ public OSUUID(string s) { if (s == null) UUID = new Guid(); else UUID = new Guid(s); } public OSUUID(Guid g) { UUID = g; } public OSUUID(LLUUID l) { UUID = l.UUID; } public OSUUID(ulong u) { UUID = new Guid(0, 0, 0, BitConverter.GetBytes(u)); } // out conversion public string ToString() { return UUID.ToString(); } public LLUUID ToLLUUID() { return new LLUUID(UUID); } // for comparison bits public override int GetHashCode() { return UUID.GetHashCode(); } public override bool Equals(object o) { if (!(o is LLUUID)) return false; OSUUID uuid = (OSUUID)o; return UUID == uuid.UUID; } public int CompareTo(object obj) { if (obj is OSUUID) { OSUUID ID = (OSUUID)obj; return this.UUID.CompareTo(ID.UUID); } throw new ArgumentException("object is not a OSUUID"); } // Static methods public static OSUUID Random() { return new OSUUID(Guid.NewGuid()); } public static readonly OSUUID Zero = new OSUUID(); } }
bsd-3-clause
C#
ed5b6f669b1a3d543b07e6e86f5a75202abd4a61
change of possible move color
bytePassion/OpenQuoridorFramework
OpenQuoridorFramework/OQF.PlayerVsBot/Global/Constants.cs
OpenQuoridorFramework/OQF.PlayerVsBot/Global/Constants.cs
using System.Windows; using System.Windows.Media; namespace OQF.PlayerVsBot.Global { internal static class Constants { //public static readonly SolidColorBrush TopPlayerActiveColor = new SolidColorBrush(Colors.Red); //public static readonly SolidColorBrush BottomPlayerActiveColor = new SolidColorBrush(Colors.GreenYellow); public static readonly SolidColorBrush PlayerInactiveColor = new SolidColorBrush(Colors.DarkGray); public static readonly SolidColorBrush FieldBackgroundColor = new SolidColorBrush(Color.FromRgb(121, 93, 86)); public static readonly SolidColorBrush FieldColor = new SolidColorBrush(Color.FromRgb(97, 64, 56)); public static readonly SolidColorBrush FrameColor = new SolidColorBrush(Colors.Black); public static readonly SolidColorBrush WallColor = new SolidColorBrush(Colors.AntiqueWhite); public static readonly SolidColorBrush PossibleMoveFieldColor = new SolidColorBrush(Color.FromArgb(96, 255, 249, 197)); public static readonly SolidColorBrush PotentialPlacedWallColor = new SolidColorBrush(Color.FromArgb(207, 255, 255, 255)); public static readonly Brush TopPlayerActiveColor = new LinearGradientBrush() { MappingMode = BrushMappingMode.RelativeToBoundingBox, EndPoint = new Point(0.5, 1), StartPoint = new Point(0.5, 0), GradientStops = new GradientStopCollection() { new GradientStop(Color.FromRgb(241, 241, 241), 0.159), new GradientStop(Color.FromRgb(178, 178, 178), 0.674) } }; public static readonly Brush BottomPlayerActiveColor = new LinearGradientBrush() { MappingMode = BrushMappingMode.RelativeToBoundingBox, EndPoint = new Point(0.5, 1), StartPoint = new Point(0.5, 0), GradientStops = new GradientStopCollection() { new GradientStop(Color.FromRgb(122, 122, 122), 0.159), new GradientStop(Color.FromRgb(48, 48, 48), 0.674) } }; public static readonly Size SizeFallBackValue = new Size(300,300); } }
using System.Windows; using System.Windows.Media; namespace OQF.PlayerVsBot.Global { internal static class Constants { //public static readonly SolidColorBrush TopPlayerActiveColor = new SolidColorBrush(Colors.Red); //public static readonly SolidColorBrush BottomPlayerActiveColor = new SolidColorBrush(Colors.GreenYellow); public static readonly SolidColorBrush PlayerInactiveColor = new SolidColorBrush(Colors.DarkGray); public static readonly SolidColorBrush FieldBackgroundColor = new SolidColorBrush(Color.FromRgb(121, 93, 86)); public static readonly SolidColorBrush FieldColor = new SolidColorBrush(Color.FromRgb(97, 64, 56)); public static readonly SolidColorBrush FrameColor = new SolidColorBrush(Colors.Black); public static readonly SolidColorBrush WallColor = new SolidColorBrush(Colors.AntiqueWhite); public static readonly SolidColorBrush PossibleMoveFieldColor = new SolidColorBrush(Color.FromArgb(255, 255, 206, 0)); public static readonly SolidColorBrush PotentialPlacedWallColor = new SolidColorBrush(Color.FromArgb(207, 255, 255, 255)); public static readonly Brush TopPlayerActiveColor = new LinearGradientBrush() { MappingMode = BrushMappingMode.RelativeToBoundingBox, EndPoint = new Point(0.5, 1), StartPoint = new Point(0.5, 0), GradientStops = new GradientStopCollection() { new GradientStop(Color.FromRgb(241, 241, 241), 0.159), new GradientStop(Color.FromRgb(178, 178, 178), 0.674) } }; public static readonly Brush BottomPlayerActiveColor = new LinearGradientBrush() { MappingMode = BrushMappingMode.RelativeToBoundingBox, EndPoint = new Point(0.5, 1), StartPoint = new Point(0.5, 0), GradientStops = new GradientStopCollection() { new GradientStop(Color.FromRgb(122, 122, 122), 0.159), new GradientStop(Color.FromRgb(48, 48, 48), 0.674) } }; public static readonly Size SizeFallBackValue = new Size(300,300); } }
apache-2.0
C#
82b1bd98100cf892f99ed6fb942aa33b24ec8b87
add Database for Integration tests
SRoddis/Mongo.Migration
Mongo.Migration.Test/IntegrationTest.cs
Mongo.Migration.Test/IntegrationTest.cs
using Mongo.Migration.Startup.Static; using Mongo2Go; using MongoDB.Bson; using MongoDB.Driver; namespace Mongo.Migration.Test { public class IntegrationTest { protected IMongoClient _client; protected IComponentRegistry _components; protected MongoDbRunner _mongoToGoRunner; protected IntegrationTest() { _mongoToGoRunner = MongoDbRunner.Start(); _client = new MongoClient(_mongoToGoRunner.ConnectionString); _client.GetDatabase("PerformanceTest").CreateCollection("Test"); _components = new ComponentRegistry(); _components.RegisterComponents(_client); } } }
using Mongo.Migration.Startup.Static; using Mongo2Go; using MongoDB.Driver; namespace Mongo.Migration.Test { public class IntegrationTest { protected IMongoClient _client; protected IComponentRegistry _components; protected MongoDbRunner _mongoToGoRunner; protected IntegrationTest() { _mongoToGoRunner = MongoDbRunner.Start(); _client = new MongoClient(_mongoToGoRunner.ConnectionString); _components = new ComponentRegistry(); _components.RegisterComponents(_client); } } }
mit
C#
aa614de7f1dad1be8390f8ea8b5150f31f69c680
Add container for sprite sheet prototypes
iridinite/shiftdrive
Client/Assets.cs
Client/Assets.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace ShiftDrive { /// <summary> /// A simple static container, for holding game assets like textures and meshes. /// </summary> internal static class Assets { public static SpriteFont fontDefault, fontBold; public static readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>(); public static readonly Dictionary<string, SpriteSheet> sprites = new Dictionary<string, SpriteSheet>(); public static Model mdlSkybox; public static Effect fxUnlit; public static SoundEffect sndUIConfirm, sndUICancel, sndUIAppear1, sndUIAppear2, sndUIAppear3, sndUIAppear4; public static Texture2D GetTexture(string name) { if (!textures.ContainsKey(name.ToLowerInvariant())) throw new KeyNotFoundException($"Texture '{name}' was not found."); return textures[name.ToLowerInvariant()]; } public static SpriteSheet GetSprite(string name) { if (!sprites.ContainsKey(name.ToLowerInvariant())) throw new KeyNotFoundException($"Sprite '{name}' was not found."); return sprites[name.ToLowerInvariant()]; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace ShiftDrive { /// <summary> /// A simple static container, for holding game assets like textures and meshes. /// </summary> internal static class Assets { public static SpriteFont fontDefault, fontBold; public static readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>(); public static Model mdlSkybox; public static Effect fxUnlit; public static SoundEffect sndUIConfirm, sndUICancel, sndUIAppear1, sndUIAppear2, sndUIAppear3, sndUIAppear4; public static Texture2D GetTexture(string name) { if (!textures.ContainsKey(name.ToLowerInvariant())) throw new KeyNotFoundException($"Texture '{name}' was not found."); return textures[name.ToLowerInvariant()]; } } }
bsd-3-clause
C#
5743cab5fe8cbe56c9345765356237b1af526e88
change initial directory of open file dialog to last file
martin2250/OpenCNCPilot
OpenCNCPilot/MainWindow.xaml.FileTab.cs
OpenCNCPilot/MainWindow.xaml.FileTab.cs
using OpenCNCPilot.Communication; using OpenCNCPilot.GCode; using System; using System.Windows; namespace OpenCNCPilot { partial class MainWindow { private string _currentFileName = ""; public string CurrentFileName { get => _currentFileName; set { _currentFileName = value; GetBindingExpression(Window.TitleProperty).UpdateTarget(); } } private void OpenFileDialogGCode_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; CurrentFileName = ""; ToolPath = GCodeFile.Empty; openFileDialogGCode.InitialDirectory = System.IO.Path.GetDirectoryName(openFileDialogGCode.FileName); try { machine.SetFile(System.IO.File.ReadAllLines(openFileDialogGCode.FileName)); CurrentFileName = System.IO.Path.GetFileName(openFileDialogGCode.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void SaveFileDialogGCode_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; try { ToolPath.Save(saveFileDialogGCode.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ButtonOpen_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; // prevent exception when the drive letter doesn't exist if (!System.IO.Directory.Exists(openFileDialogGCode.InitialDirectory)) { openFileDialogGCode.InitialDirectory = ""; } openFileDialogGCode.ShowDialog(); } private void ButtonSave_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; saveFileDialogGCode.ShowDialog(); } private void ButtonClear_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; machine.ClearFile(); CurrentFileName = ""; } private void ButtonFileStart_Click(object sender, RoutedEventArgs e) { machine.FileStart(); } private void ButtonFilePause_Click(object sender, RoutedEventArgs e) { machine.FilePause(); } private void ButtonFileGoto_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; EnterNumberWindow enw = new EnterNumberWindow(machine.FilePosition + 1); enw.Title = "Enter new line number"; enw.Owner = this; enw.User_Ok += Enw_User_Ok_Goto; enw.Show(); } private void Enw_User_Ok_Goto(double value) { if (machine.Mode == Machine.OperatingMode.SendFile) return; machine.FileGoto((int)value - 1); } } }
using OpenCNCPilot.Communication; using OpenCNCPilot.GCode; using System; using System.Windows; namespace OpenCNCPilot { partial class MainWindow { private string _currentFileName = ""; public string CurrentFileName { get => _currentFileName; set { _currentFileName = value; GetBindingExpression(Window.TitleProperty).UpdateTarget(); } } private void OpenFileDialogGCode_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; CurrentFileName = ""; ToolPath = GCodeFile.Empty; try { machine.SetFile(System.IO.File.ReadAllLines(openFileDialogGCode.FileName)); CurrentFileName = System.IO.Path.GetFileName(openFileDialogGCode.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void SaveFileDialogGCode_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; try { ToolPath.Save(saveFileDialogGCode.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ButtonOpen_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; openFileDialogGCode.ShowDialog(); } private void ButtonSave_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; saveFileDialogGCode.ShowDialog(); } private void ButtonClear_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; machine.ClearFile(); CurrentFileName = ""; } private void ButtonFileStart_Click(object sender, RoutedEventArgs e) { machine.FileStart(); } private void ButtonFilePause_Click(object sender, RoutedEventArgs e) { machine.FilePause(); } private void ButtonFileGoto_Click(object sender, RoutedEventArgs e) { if (machine.Mode == Machine.OperatingMode.SendFile) return; EnterNumberWindow enw = new EnterNumberWindow(machine.FilePosition + 1); enw.Title = "Enter new line number"; enw.Owner = this; enw.User_Ok += Enw_User_Ok_Goto; enw.Show(); } private void Enw_User_Ok_Goto(double value) { if (machine.Mode == Machine.OperatingMode.SendFile) return; machine.FileGoto((int)value - 1); } } }
mit
C#
85dd7a75abfc1f45ec7b8dde68a5599654a4abdc
add using
elyen3824/myfinanalysis-data
data-provider/run.csx
data-provider/run.csx
using System; using System.Net; using System.Threading.Tasks; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; string symbol = GetValueFromQuery(req, "symbol"); string start = GetValueFromQuery(req, "start"); string end = GetValueFromQuery(req, "end"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); // Set name to query string or body data string[] symbols = data?.symbols; HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end); return result; } private static string GetValueFromQuery(HttpRequestMessage req, string key) { return req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, key, true) == 0) .Value; } private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end) { if(symbol == null && symbols == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body"); dynamic urls = GetUrls(symbol, symbols, start, end); return req.CreateResponse(HttpStatusCode.OK, urls); } private static dynamic GetUrls(string symbol, string[] symbols, string start, string end) { if(symbol !=null) return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul"; return string.Empty; }
using System.Net; using System.Net.Http; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; string symbol = GetValueFromQuery(req, "symbol"); string start = GetValueFromQuery(req, "start"); string end = GetValueFromQuery(req, "end"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); // Set name to query string or body data string[] symbols = data?.symbols; HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end); return result; } private static string GetValueFromQuery(HttpRequestMessage req, string key) { return req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, key, true) == 0) .Value; } private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end) { if(symbol == null && symbols == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body"); dynamic urls = GetUrls(symbol, symbols, start, end); return req.CreateResponse(HttpStatusCode.OK, urls); } private static dynamic GetUrls(string symbol, string[] symbols, string start, string end) { if(symbol !=null) return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul"; return string.Empty; }
mit
C#
3cf194e86d2581451229359175c15fa17df769cb
add swpin's Dispose
yun2dot0/w10iotSample
LEDSwitch/MainPage.xaml.cs
LEDSwitch/MainPage.xaml.cs
using System; using Windows.Devices.Gpio; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace LEDSwitch { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private const int LED_PIN = 6; private const int SW_PIN = 5; private GpioPin ledpin; private GpioPin swpin; public MainPage() { this.InitializeComponent(); Unloaded += MainPage_Unloaded; InitGPIO(); } private void MainPage_Unloaded(object sender, RoutedEventArgs e) { ledpin.Dispose(); swpin.Dispose(); } private void InitGPIO() { var gpio = GpioController.GetDefault(); ledpin = gpio.OpenPin(LED_PIN, GpioSharingMode.Exclusive); ledpin.SetDriveMode(GpioPinDriveMode.Output); swpin = gpio.OpenPin(SW_PIN, GpioSharingMode.Exclusive); swpin.SetDriveMode(GpioPinDriveMode.Input); swpin.DebounceTimeout = new TimeSpan(200); swpin.ValueChanged += Swpin_ValueChanged; } private void Swpin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args) { if (args.Edge != GpioPinEdge.RisingEdge) return; var ledval = ledpin.Read() == GpioPinValue.High ? GpioPinValue.Low : GpioPinValue.High; ledpin.Write(ledval); } } }
using System; using Windows.Devices.Gpio; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace LEDSwitch { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private const int LED_PIN = 6; private const int SW_PIN = 5; private GpioPin ledpin; private GpioPin swpin; public MainPage() { this.InitializeComponent(); Unloaded += MainPage_Unloaded; InitGPIO(); } private void MainPage_Unloaded(object sender, RoutedEventArgs e) { ledpin.Dispose(); } private void InitGPIO() { var gpio = GpioController.GetDefault(); ledpin = gpio.OpenPin(LED_PIN, GpioSharingMode.Exclusive); ledpin.SetDriveMode(GpioPinDriveMode.Output); swpin = gpio.OpenPin(SW_PIN, GpioSharingMode.Exclusive); swpin.SetDriveMode(GpioPinDriveMode.Input); swpin.DebounceTimeout = new TimeSpan(200); swpin.ValueChanged += Swpin_ValueChanged; } private void Swpin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args) { if (args.Edge != GpioPinEdge.RisingEdge) return; var ledval = ledpin.Read() == GpioPinValue.High ? GpioPinValue.Low : GpioPinValue.High; ledpin.Write(ledval); } } }
mit
C#
e926b747cfd92b4fa08cbdac0bffd5991aa0481f
Remove accidental debugging statements
jlewin/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl
SlicerConfiguration/UIFields/UIField.cs
SlicerConfiguration/UIFields/UIField.cs
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.UI; namespace MatterHackers.MatterControl.SlicerConfiguration { public abstract class UIField { public event EventHandler<FieldChangedEventArgs> ValueChanged; public void SetValue(string newValue, bool userInitiated) { string convertedValue = this.ConvertValue(newValue); if (this.Value != convertedValue) { this.Value = convertedValue; this.OnValueChanged(new FieldChangedEventArgs(userInitiated)); } else if (newValue != convertedValue) { // If the validated value matches the current value, then UI element values were rejected and must be discarded this.OnValueChanged(new FieldChangedEventArgs(userInitiated)); } } public string Value { get; private set; } public GuiWidget Content { get; protected set; } public string HelpText { get; set; } public string Name { get; set; } protected virtual string ConvertValue(string newValue) { return newValue; } public virtual void Initialize(int tabIndex) { } protected virtual void OnValueChanged(FieldChangedEventArgs fieldChangedEventArgs) { ValueChanged?.Invoke(this, fieldChangedEventArgs); } } }
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.UI; namespace MatterHackers.MatterControl.SlicerConfiguration { public abstract class UIField { public event EventHandler<FieldChangedEventArgs> ValueChanged; public void SetValue(string newValue, bool userInitiated) { string convertedValue = this.ConvertValue(newValue); Console.WriteLine($"SetValue: {newValue}/{convertedValue}/{userInitiated}"); if (this.Value != convertedValue) { this.Value = convertedValue; this.OnValueChanged(new FieldChangedEventArgs(userInitiated)); } else if (newValue != convertedValue) { // If the validated value matches the current value, then UI element values were rejected and must be discarded this.OnValueChanged(new FieldChangedEventArgs(userInitiated)); } } public string Value { get; private set; } public GuiWidget Content { get; protected set; } public string HelpText { get; set; } public string Name { get; set; } protected virtual string ConvertValue(string newValue) { return newValue; } public virtual void Initialize(int tabIndex) { } protected virtual void OnValueChanged(FieldChangedEventArgs fieldChangedEventArgs) { ValueChanged?.Invoke(this, fieldChangedEventArgs); } } }
bsd-2-clause
C#
ad50215de681dc6e2f6bb6aabd58f302bbb1521b
Update KSPCompatible.cs
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer
LmpGlobal/KSPCompatible.cs
LmpGlobal/KSPCompatible.cs
using System; namespace LmpGlobal { public static class KspCompatible { public static readonly Version MinKspVersion = new Version("1.4.3"); public static readonly Version MaxKspVersion = new Version("1.4.9"); } }
using System; namespace LmpGlobal { public static class KspCompatible { public static readonly Version MinKspVersion = new Version("1.4.0"); public static readonly Version MaxKspVersion = new Version("1.4.9"); } }
mit
C#
f87f715f929e7145f2b6f7a499f028540814f969
Mark old API methods in Game as obsolete
TheEadie/PlayerRank,TheEadie/PlayerRank
PlayerRank/Game.cs
PlayerRank/Game.cs
using System; using System.Collections.Generic; using System.Linq; namespace PlayerRank { public class Game { private readonly Dictionary<string, Points> m_Scores = new Dictionary<string, Points>(); public void AddResult(string name, Points points) { if (m_Scores.ContainsKey(name)) { m_Scores[name] = points; } else { m_Scores.Add(name, points); } } internal Dictionary<string, double> GetResults() { var oldResults = new Dictionary<string, double>(); foreach (var score in m_Scores) { oldResults.Add(score.Key, score.Value.GetValue()); } return oldResults; } /// Obsolete V1 API [Obsolete("Please use AddResult(string, Points) instead")] public void AddResult(string name, double score) { if (m_Scores.ContainsKey(name)) { m_Scores[name] = new Points(score); } else { m_Scores.Add(name, new Points(score)); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace PlayerRank { public class Game { private readonly Dictionary<string, Points> m_Scores = new Dictionary<string, Points>(); public void AddResult(string name, double score) { if (m_Scores.ContainsKey(name)) { m_Scores[name] = new Points(score); } else { m_Scores.Add(name, new Points(score)); } } public void AddResult(string name, Points points) { if (m_Scores.ContainsKey(name)) { m_Scores[name] = points; } else { m_Scores.Add(name, points); } } internal Dictionary<string, double> GetResults() { var oldResults = new Dictionary<string, double>(); foreach (var score in m_Scores) { oldResults.Add(score.Key, score.Value.GetValue()); } return oldResults; } } }
mit
C#
b88b6a6f4fde8543f3543d3e8e2b36ed3cd73783
Use Section instead of Paragraph for quote blocks.
Kryptos-FR/markdig-wpf,Kryptos-FR/markdig.wpf
src/Markdig.Xaml/Renderers/Xaml/QuoteBlockRenderer.cs
src/Markdig.Xaml/Renderers/Xaml/QuoteBlockRenderer.cs
// Copyright (c) 2016 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using Markdig.Syntax; namespace Markdig.Renderers.Xaml { /// <summary> /// A XAML renderer for a <see cref="QuoteBlock"/>. /// </summary> /// <seealso cref="Xaml.XamlObjectRenderer{T}" /> public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock> { protected override void Write(XamlRenderer renderer, QuoteBlock obj) { renderer.EnsureLine(); // TODO: apply quote block styling renderer.Write("<Section>"); renderer.WriteChildren(obj); renderer.WriteLine("</Section>"); } } }
// Copyright (c) 2016 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using Markdig.Syntax; namespace Markdig.Renderers.Xaml { /// <summary> /// A XAML renderer for a <see cref="QuoteBlock"/>. /// </summary> /// <seealso cref="Xaml.XamlObjectRenderer{T}" /> public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock> { protected override void Write(XamlRenderer renderer, QuoteBlock obj) { renderer.EnsureLine(); // TODO: apply quote block styling renderer.Write("<Paragraph>"); renderer.WriteChildren(obj); renderer.WriteLine("</Paragraph>"); } } }
mit
C#
ebbd4ff9ac9e4d9bdb5cbf3c60b24540ea5f193e
Revert "Revert "Base directory for Avalonia""
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Program.cs
WalletWasabi.Gui/Program.cs
using Avalonia; using AvalonStudio.Shell; using AvalonStudio.Shell.Extensibility.Platforms; using NBitcoin; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Logging; namespace WalletWasabi.Gui { internal class Program { #pragma warning disable IDE1006 // Naming Styles private static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { StatusBarViewModel statusBar = null; try { Platform.BaseDirectory = Path.Combine(Global.DataDir, "Gui"); BuildAvaloniaApp().BeforeStarting(async builder => { try { MainWindowViewModel.Instance = new MainWindowViewModel(); Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo<Config>("Config is successfully initialized."); Global.InitializeConfig(config); if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it. { var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath)); if (File.Exists(cachedIndexFilePath)) { File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false); } } Global.InitializeNoWallet(); statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker); MainWindowViewModel.Instance.StatusBar = statusBar; if (Global.IndexDownloader.Network != Network.Main) { MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}"; } } catch (Exception ex) { Logger.LogCritical<Program>(ex); } }).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance); } catch (Exception ex) { Logger.LogCritical<Program>(ex); } finally { statusBar?.Dispose(); await Global.DisposeAsync(); } } private static AppBuilder BuildAvaloniaApp() { return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI(); } } }
using Avalonia; using AvalonStudio.Shell; using AvalonStudio.Shell.Extensibility.Platforms; using NBitcoin; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Logging; namespace WalletWasabi.Gui { internal class Program { #pragma warning disable IDE1006 // Naming Styles private static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { StatusBarViewModel statusBar = null; try { BuildAvaloniaApp().BeforeStarting(async builder => { try { MainWindowViewModel.Instance = new MainWindowViewModel(); Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo<Config>("Config is successfully initialized."); Global.InitializeConfig(config); if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it. { var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath)); if (File.Exists(cachedIndexFilePath)) { File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false); } } Global.InitializeNoWallet(); statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker); MainWindowViewModel.Instance.StatusBar = statusBar; if (Global.IndexDownloader.Network != Network.Main) { MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}"; } } catch (Exception ex) { Logger.LogCritical<Program>(ex); } }).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance); } catch (Exception ex) { Logger.LogCritical<Program>(ex); } finally { statusBar?.Dispose(); await Global.DisposeAsync(); } } private static AppBuilder BuildAvaloniaApp() { return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI(); } } }
mit
C#
6a77832519c0f10437cae54c5857869c255145c7
Add header comment.
AIWolfSharp/AIWolf_NET,AIWolfSharp/AIWolfCore
AIWolfLib/Error.cs
AIWolfLib/Error.cs
// // Error.cs // // Copyright (c) 2016 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // using System; using System.Diagnostics; namespace AIWolf.Lib { /// <summary> /// Error handling class. /// </summary> public static class Error { /// <summary> /// Writes an error message, then throws exception on debug. /// </summary> /// <param name="message">Error message.</param> public static void RuntimeError(string message) { Console.Error.WriteLine(message); ThrowException(message); } [Conditional("DEBUG")] static void ThrowException(string message) { throw new AIWolfRuntimeException(message); } } }
using System; using System.Diagnostics; namespace AIWolf.Lib { public static class Error { /// <summary> /// Writes an error message, then throws exception on debug. /// </summary> /// <param name="message">Error message.</param> public static void RuntimeError(string message) { Console.Error.WriteLine(message); ThrowException(message); } [Conditional("DEBUG")] public static void ThrowException(string message) { throw new AIWolfRuntimeException(message); } } }
mit
C#
89f00cea4e507c8c542d623ca2811b8c56dc10bd
Introduce a Protocol class for better encapsulation
msdeibel/opcmock
OpcMock/OpcMockProtocol.cs
OpcMock/OpcMockProtocol.cs
using System; using System.Collections.Generic; namespace OpcMock { public class OpcMockProtocol { private List<ProtocolLine> lines; public OpcMockProtocol() { lines = new List<ProtocolLine>(); } public List<ProtocolLine> Lines { get{ return lines; } } public void Append(ProtocolLine protocolLine) { lines.Add(protocolLine); } } }
namespace OpcMockTests { internal class OpcMockProtocol { } }
mit
C#
28da048db7774ddbb2fe48c281a45693f4bc976a
Update "App"
DRFP/Personal-Library
_Build/PersonalLibrary/Base/App.xaml.cs
_Build/PersonalLibrary/Base/App.xaml.cs
using System.IO; using System.Windows; using static Library.Configuration; using static Library.SQLiteManager; namespace Base { public partial class App : Application { public App() { Configure(); } private async void Configure() { if (!File.Exists(databaseName)) await CreateDatabase(); } } }
using System.IO; using System.Windows; using static Library.Configuration; using static Library.SQLiteManager; namespace Base { public partial class App : Application { public App() { Configure(); } private async void Configure() { if (!File.Exists(DatabaseName)) await CreateDatabase(); } } }
mit
C#
d0e5d49100bb55d2e92edd40453cb8da4f12d35e
add infos to the assembly
TUD-INF-IAI-MCI/DotNet_AudioRenderer
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AudioRenderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TU Dresden, Germany")] [assembly: AssemblyProduct("AudioRenderer")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("522bdb30-56bb-4e81-b67b-9ed3090b2ba0")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AudioRenderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AudioRenderer")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("522bdb30-56bb-4e81-b67b-9ed3090b2ba0")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bsd-2-clause
C#
37ef5c70729c6f99cf51cc6841eb4833a728e51c
rename SliderVelocity to ScrollSpeed
smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu
osu.Game.Rulesets.Taiko/Mods/TaikoModDifficultyAdjust.cs
osu.Game.Rulesets.Taiko/Mods/TaikoModDifficultyAdjust.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModDifficultyAdjust : ModDifficultyAdjust { [SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1)] public BindableNumber<float> ScrollSpeed { get; } = new BindableFloat { Precision = 0.05f, MinValue = 0.25f, MaxValue = 4, Default = 1, Value = 1, }; public override string SettingDescription { get { string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N1}"; return string.Join(", ", new[] { base.SettingDescription, scrollSpeed }.Where(s => !string.IsNullOrEmpty(s))); } } protected override void ApplySettings(BeatmapDifficulty difficulty) { base.ApplySettings(difficulty); ApplySetting(ScrollSpeed, scroll => difficulty.SliderMultiplier *= scroll); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModDifficultyAdjust : ModDifficultyAdjust { [SettingSource("Slider Velocity", "Adjust a beatmap's set SV", LAST_SETTING_ORDER + 1)] public BindableNumber<float> SliderVelocity { get; } = new BindableFloat { Precision = 0.05f, MinValue = 0.25f, MaxValue = 4, Default = 1, Value = 1, }; public override string SettingDescription { get { string sliderVelocity = SliderVelocity.IsDefault ? string.Empty : $"SV {SliderVelocity.Value:N1}"; return string.Join(", ", new[] { base.SettingDescription, sliderVelocity }.Where(s => !string.IsNullOrEmpty(s))); } } protected override void ApplySettings(BeatmapDifficulty difficulty) { base.ApplySettings(difficulty); ApplySetting(SliderVelocity, sv => difficulty.SliderMultiplier *= sv); } } }
mit
C#
8d2ff1d584898fb9f5e54cd95cfcfae95c1bd9da
Update version number.
mmatkow/BotBuilder,digibaraka/BotBuilder,mmatkow/BotBuilder,xiangyan99/BotBuilder,jockorob/BotBuilder,jockorob/BotBuilder,yakumo/BotBuilder,digibaraka/BotBuilder,xiangyan99/BotBuilder,stevengum97/BotBuilder,navaei/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,digibaraka/BotBuilder,Clairety/ConnectMe,dr-em/BotBuilder,dr-em/BotBuilder,navaei/BotBuilder,yakumo/BotBuilder,dr-em/BotBuilder,yakumo/BotBuilder,Clairety/ConnectMe,Clairety/ConnectMe,stevengum97/BotBuilder,msft-shahins/BotBuilder,stevengum97/BotBuilder,mmatkow/BotBuilder,digibaraka/BotBuilder,navaei/BotBuilder,navaei/BotBuilder,mmatkow/BotBuilder,jockorob/BotBuilder,jockorob/BotBuilder,msft-shahins/BotBuilder,xiangyan99/BotBuilder,msft-shahins/BotBuilder,stevengum97/BotBuilder,dr-em/BotBuilder,xiangyan99/BotBuilder,Clairety/ConnectMe
CSharp/Library/Properties/AssemblyInfo.cs
CSharp/Library/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("Microsoft.Bot.Builder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Bot Builder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")] // 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.9.0.29")] [assembly: AssemblyFileVersion("0.9.0.29")] [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.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("Microsoft.Bot.Builder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Bot Builder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")] // 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.9.0.28")] [assembly: AssemblyFileVersion("0.9.0.28")] [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")]
mit
C#
790eadf7d8f4001574b5aea14d7a71d9f842514b
Bump version number
Sunlighter/CanonicalTypes
CanonicalTypes/Properties/AssemblyInfo.cs
CanonicalTypes/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("CanonicalTypes")] [assembly: AssemblyDescription("A library of general-purpose, immutable, serializable types")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CanonicalTypes")] [assembly: AssemblyCopyright("Copyright © 2015, 2016 by Sunlighter")] [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("124426d4-c037-4d9d-8ca9-f23deaea89d5")] // 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")]
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("CanonicalTypes")] [assembly: AssemblyDescription("A library of general-purpose, immutable, serializable types")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CanonicalTypes")] [assembly: AssemblyCopyright("Copyright © 2015, 2016 by Sunlighter")] [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("124426d4-c037-4d9d-8ca9-f23deaea89d5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
83d6c9070ad0a94213fb87dfe53b26e8adedbc84
Update Jab.cs
darvell/Coremero
Coremero/Coremero.Plugin.Converter/Jab.cs
Coremero/Coremero.Plugin.Converter/Jab.cs
using System.Text; using Coremero.Client; using Coremero.Commands; using Coremero.Utilities; namespace Coremero.Plugin.Converter { public class Jab : IPlugin { [Command("jab", Help = ".jab <text> - Convert <text> to full width.")] public string FullWidth(IInvocationContext context, IMessage message) { return message.Text.TrimCommand().ToUnicodeFullWidth(); } [Command("bigjab", Help = ".bigjab <text> - Convert <text> to multiline full width with borders.")] public string FullWidthMultiline(IInvocationContext context, IMessage message) { string jab = FullWidth(context, message); // Generate borders. var fancy = "ஜ۩۞۩ஜ"; var padLen = (jab.Length * 2 - fancy.Length) / 2 - 1; var spaces = ""; if (padLen < 0) { jab = jab.PadLeft(fancy.Length / 2 + 1).PadRight(fancy.Length); } else { spaces = "".PadLeft(padLen, '\u25AC'); } fancy = $"{spaces}{fancy}{spaces}"; jab = $"{fancy}\n{jab}\n{fancy}"; if (context.OriginClient.Features.HasFlag(ClientFeature.Markdown)) { return $"```\n{jab}\n```"; } return jab; } } }
using System.Text; using Coremero.Client; using Coremero.Commands; using Coremero.Utilities; namespace Coremero.Plugin.Converter { public class Jab : IPlugin { [Command("jab", Help = ".jab <text> - Convert <text> to full width.")] public string FullWidth(IInvocationContext context, IMessage message) { return message.Text.TrimCommand().ToUnicodeFullWidth(); } [Command("bigjab", Help = ".bigjab <text> - ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\ Convert <text> to multiline full width with borders.\ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬")] public string FullWidthMultiline(IInvocationContext context, IMessage message) { string jab = FullWidth(context, message); // Generate borders. var fancy = "ஜ۩۞۩ஜ"; var padLen = (jab.Length * 2 - fancy.Length) / 2 - 1; var spaces = ""; if (padLen < 0) { jab = jab.PadLeft(fancy.Length / 2 + 1).PadRight(fancy.Length); } else { spaces = "".PadLeft(padLen, '\u25AC'); } fancy = $"{spaces}{fancy}{spaces}"; jab = $"{fancy}\n{jab}\n{fancy}"; if (context.OriginClient.Features.HasFlag(ClientFeature.Markdown)) { return $"```\n{jab}\n```"; } return jab; } } }
mit
C#
04926b3451c88be92b37571e9c7491a970690cfc
remove non-UserDefinedTitle when validating conceptual metadata (#4132)
superyyrrzz/docfx,dotnet/docfx,dotnet/docfx,superyyrrzz/docfx,dotnet/docfx,superyyrrzz/docfx
src/Microsoft.DocAsCode.Build.ConceptualDocuments/ValidateConceptualDocumentMetadata.cs
src/Microsoft.DocAsCode.Build.ConceptualDocuments/ValidateConceptualDocumentMetadata.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.ConceptualDocuments { using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.DocAsCode.Build.Common; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.Plugins; [Export(nameof(ConceptualDocumentProcessor), typeof(IDocumentBuildStep))] public class ValidateConceptualDocumentMetadata : BaseDocumentBuildStep, ISupportIncrementalBuildStep { private const string ConceptualKey = Constants.PropertyName.Conceptual; public override string Name => nameof(ValidateConceptualDocumentMetadata); public override int BuildOrder => 1; public override void Build(FileModel model, IHostService host) { if (model.Type != DocumentType.Article) { return; } if (!host.HasMetadataValidation) { return; } var metadata = ((Dictionary<string, object>)model.Content).ToImmutableDictionary().Remove(ConceptualKey); if(!model.Properties.IsUserDefinedTitle) { metadata = metadata.Remove(Constants.PropertyName.Title); } host.ValidateInputMetadata(model.OriginalFileAndType.File, metadata); } #region ISupportIncrementalBuildStep Members public bool CanIncrementalBuild(FileAndType fileAndType) => true; public string GetIncrementalContextHash() => null; public IEnumerable<DependencyType> GetDependencyTypesToRegister() => null; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.ConceptualDocuments { using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.DocAsCode.Build.Common; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.Plugins; [Export(nameof(ConceptualDocumentProcessor), typeof(IDocumentBuildStep))] public class ValidateConceptualDocumentMetadata : BaseDocumentBuildStep, ISupportIncrementalBuildStep { private const string ConceptualKey = Constants.PropertyName.Conceptual; public override string Name => nameof(ValidateConceptualDocumentMetadata); public override int BuildOrder => 1; public override void Build(FileModel model, IHostService host) { if (model.Type != DocumentType.Article) { return; } if (!host.HasMetadataValidation) { return; } host.ValidateInputMetadata( model.OriginalFileAndType.File, ((Dictionary<string, object>)model.Content).ToImmutableDictionary().Remove(ConceptualKey)); } #region ISupportIncrementalBuildStep Members public bool CanIncrementalBuild(FileAndType fileAndType) => true; public string GetIncrementalContextHash() => null; public IEnumerable<DependencyType> GetDependencyTypesToRegister() => null; #endregion } }
mit
C#
293d1c2709a0ee51323ed1daa8727da5caab3c7d
Fix Record Graph Type Query
SnowflakePowered/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,RonnChyran/snowflake
src/Snowflake.Support.GraphQLFrameworkQueries/Types/Model/GameFileExtensionGraphType.cs
src/Snowflake.Support.GraphQLFrameworkQueries/Types/Model/GameFileExtensionGraphType.cs
using System; using System.Collections.Generic; using System.Text; using GraphQL.Types; using Snowflake.Model.Game.LibraryExtensions; namespace Snowflake.Support.Remoting.GraphQL.Types.Model { public class GameFileExtensionGraphType : ObjectGraphType<IGameFileExtension> { public GameFileExtensionGraphType() { Name = "GameFiles"; Description = "The files of a game"; Field<ListGraphType<FileRecordGraphType>>("fileRecords", description: "The files for which have metadata and are installed, not all files.", resolve: context => context.Source.Files); Field<ListGraphType<FileGraphType>>("programFiles", description: "All files inside the program files folder for this game.", arguments: new QueryArguments(new QueryArgument<BooleanGraphType> {Name = "recursive", DefaultValue = false,}), resolve: context => context.GetArgument("recursive", false) ? context.Source.ProgramRoot.EnumerateFilesRecursive() : context.Source.ProgramRoot.EnumerateFiles()); } } }
using System; using System.Collections.Generic; using System.Text; using GraphQL.Types; using Snowflake.Model.Game.LibraryExtensions; namespace Snowflake.Support.Remoting.GraphQL.Types.Model { public class GameFileExtensionGraphType : ObjectGraphType<IGameFileExtension> { public GameFileExtensionGraphType() { Name = "GameFiles"; Description = "The files of a game"; Field<FileRecordGraphType>("files", description: "The files for which have metadata and are installed, not all files.", resolve: context => context.Source.Files); Field<ListGraphType<FileGraphType>>("programFiles", description: "The files for which have metadata and are installed ", arguments: new QueryArguments(new QueryArgument<BooleanGraphType> {Name = "recursive", DefaultValue = false,}), resolve: context => context.GetArgument("recursive", false) ? context.Source.ProgramRoot.EnumerateFilesRecursive() : context.Source.ProgramRoot.EnumerateFiles()); } } }
mpl-2.0
C#
c179ec1a0c1c7db2011ab7f65f34ddcba6601811
Change order of OWIN handlers so static file handler does not preempt NuGet client redirect handler.
davidvmckay/Klondike,Stift/Klondike,fhchina/Klondike,davidvmckay/Klondike,jochenvangasse/Klondike,davidvmckay/Klondike,jochenvangasse/Klondike,themotleyfool/Klondike,Stift/Klondike,jochenvangasse/Klondike,themotleyfool/Klondike,themotleyfool/Klondike,fhchina/Klondike,Stift/Klondike,fhchina/Klondike
src/Klondike.SelfHost/SelfHostStartup.cs
src/Klondike.SelfHost/SelfHostStartup.cs
using Autofac; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using NuGet.Lucene.Web; using NuGet.Lucene.Web.Formatters; using Owin; namespace Klondike.SelfHost { class SelfHostStartup : Klondike.Startup { private readonly SelfHostSettings selfHostSettings; public SelfHostStartup(SelfHostSettings selfHostSettings) { this.selfHostSettings = selfHostSettings; } protected override string MapPath(string virtualPath) { return selfHostSettings.MapPath(virtualPath); } protected override INuGetWebApiSettings CreateSettings() { return selfHostSettings; } protected override NuGetHtmlMicrodataFormatter CreateMicrodataFormatter() { return new NuGetHtmlMicrodataFormatter(); } protected override void Start(IAppBuilder app, IContainer container) { base.Start(app, container); var fileServerOptions = new FileServerOptions { FileSystem = new PhysicalFileSystem(selfHostSettings.BaseDirectory), EnableDefaultFiles = true, }; fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"}; app.UseFileServer(fileServerOptions); } } }
using Autofac; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using NuGet.Lucene.Web; using NuGet.Lucene.Web.Formatters; using Owin; namespace Klondike.SelfHost { class SelfHostStartup : Klondike.Startup { private readonly SelfHostSettings selfHostSettings; public SelfHostStartup(SelfHostSettings selfHostSettings) { this.selfHostSettings = selfHostSettings; } protected override string MapPath(string virtualPath) { return selfHostSettings.MapPath(virtualPath); } protected override INuGetWebApiSettings CreateSettings() { return selfHostSettings; } protected override NuGetHtmlMicrodataFormatter CreateMicrodataFormatter() { return new NuGetHtmlMicrodataFormatter(); } protected override void Start(IAppBuilder app, IContainer container) { var fileServerOptions = new FileServerOptions { FileSystem = new PhysicalFileSystem(selfHostSettings.BaseDirectory), EnableDefaultFiles = true, }; fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"}; app.UseFileServer(fileServerOptions); base.Start(app, container); } } }
apache-2.0
C#
6b8ac9a0307c5c840693e6ff59f69bf68fad8bfb
use parameterless constructor
acple/ParsecSharp
ParsecSharp/Data/Position/TextPosition.cs
ParsecSharp/Data/Position/TextPosition.cs
using System; using System.Runtime.InteropServices; namespace ParsecSharp.Data { [StructLayout(LayoutKind.Auto)] public readonly struct TextPosition : IPosition<char, TextPosition>, IComparable<TextPosition>, IEquatable<TextPosition> { public static TextPosition Initial => new(); public int Line { get; } public int Column { get; } public TextPosition() : this(line: 1, column: 1) { } public TextPosition(int line, int column) { this.Line = line; this.Column = column; } public TextPosition Next(char token) => token == '\n' ? new(this.Line + 1, column: 1) : new(this.Line, this.Column + 1); public int CompareTo(IPosition? other) => other is null ? 1 // always greater than null : this.Line != other.Line ? this.Line.CompareTo(other.Line) : this.Column.CompareTo(other.Column); public int CompareTo(TextPosition other) => this.Line != other.Line ? this.Line.CompareTo(other.Line) : this.Column.CompareTo(other.Column); public bool Equals(IPosition? other) => other is TextPosition position && this == position; public bool Equals(TextPosition other) => this == other; public override bool Equals(object? obj) => obj is TextPosition position && this == position; public override int GetHashCode() => this.Line ^ this.Line << 16 ^ this.Column; public override string ToString() => $"Line: {this.Line.ToString()}, Column: {this.Column.ToString()}"; public static bool operator ==(TextPosition left, TextPosition right) => left.Line == right.Line && left.Column == right.Column; public static bool operator !=(TextPosition left, TextPosition right) => !(left == right); } }
using System; using System.Runtime.InteropServices; namespace ParsecSharp.Data { [StructLayout(LayoutKind.Auto)] public readonly struct TextPosition : IPosition<char, TextPosition>, IComparable<TextPosition>, IEquatable<TextPosition> { public static TextPosition Initial => new(line: 1, column: 1); public int Line { get; } public int Column { get; } public TextPosition(int line, int column) { this.Line = line; this.Column = column; } public TextPosition Next(char token) => token == '\n' ? new(this.Line + 1, column: 1) : new(this.Line, this.Column + 1); public int CompareTo(IPosition? other) => other is null ? 1 // always greater than null : this.Line != other.Line ? this.Line.CompareTo(other.Line) : this.Column.CompareTo(other.Column); public int CompareTo(TextPosition other) => this.Line != other.Line ? this.Line.CompareTo(other.Line) : this.Column.CompareTo(other.Column); public bool Equals(IPosition? other) => other is TextPosition position && this == position; public bool Equals(TextPosition other) => this == other; public override bool Equals(object? obj) => obj is TextPosition position && this == position; public override int GetHashCode() => this.Line ^ this.Line << 16 ^ this.Column; public override string ToString() => $"Line: {this.Line.ToString()}, Column: {this.Column.ToString()}"; public static bool operator ==(TextPosition left, TextPosition right) => left.Line == right.Line && left.Column == right.Column; public static bool operator !=(TextPosition left, TextPosition right) => !(left == right); } }
mit
C#
2d828abe02695b768b180ee43ba90558f4e9d4bd
Bump version to 1.0.1
xoofx/SharpScss,xoofx/SharpScss
src/SharpScss/Properties/AssemblyInfo.cs
src/SharpScss/Properties/AssemblyInfo.cs
using System.Resources; 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("SharpScss")] [assembly: AssemblyDescription("P/Invoke .NET wrapper around libsass")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpScss")] [assembly: AssemblyCopyright("Copyright (c) 2016, Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
using System.Resources; 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("SharpScss")] [assembly: AssemblyDescription("P/Invoke .NET wrapper around libsass")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpScss")] [assembly: AssemblyCopyright("Copyright (c) 2016, Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bsd-2-clause
C#
9f3f2155ae2cd8eba6f2b220df108bc9a2a15cee
Add some example on how to use
mattgwagner/CertiPay.Common
CertiPay.Common/WebServices/MessageInspector.cs
CertiPay.Common/WebServices/MessageInspector.cs
using System; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; namespace CertiPay.Common.WebServices { /// <summary> /// Behavior that can be added to the WCF client to getting request and response raw XML. /// /// Usage: /// /// Action<Message> OnSend = (message) => Log.Info(message.ToString()); /// Action<Message> OnReceive = (message) => Log.Info(message.ToString()); /// /// var client = new ServiceAPI.ServiceAPISoapClient(GetBinding(), new EndpointAddress(Url)); /// /// client.Endpoint.EndpointBehaviors.Add(new MessageInspectorBehavior(OnSend, OnReceive)); /// </summary> public class MessageInspectorBehavior : IEndpointBehavior { private IClientMessageInspector _inspector; public MessageInspectorBehavior(Action<Message> OnSend, Action<Message> OnReceive) { this._inspector = new RawMessageInspector { OnSend = OnSend, OnReceive = OnReceive }; } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.ClientMessageInspectors.Add(_inspector); } private class RawMessageInspector : IClientMessageInspector { public Action<Message> OnSend; public Action<Message> OnReceive; public void AfterReceiveReply(ref Message reply, object correlationState) { if (OnReceive != null) OnReceive(reply); } public object BeforeSendRequest(ref Message request, IClientChannel channel) { if (OnSend != null) OnSend(request); return null; } } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { // Nothing to do here. } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { // Nothing to do here. } public void Validate(ServiceEndpoint endpoint) { // Nothing to do here. } } }
using System; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; namespace CertiPay.Common.WebServices { /// <summary> /// Behavior that can be added to the WCF client to getting request and response raw XML. /// </summary> public class MessageInspectorBehavior : IEndpointBehavior { private IClientMessageInspector _inspector; public MessageInspectorBehavior(Action<Message> OnSend, Action<Message> OnReceive) { this._inspector = new RawMessageInspector { OnSend = OnSend, OnReceive = OnReceive }; } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.ClientMessageInspectors.Add(_inspector); } private class RawMessageInspector : IClientMessageInspector { public Action<Message> OnSend; public Action<Message> OnReceive; public void AfterReceiveReply(ref Message reply, object correlationState) { if (OnReceive != null) OnReceive(reply); } public object BeforeSendRequest(ref Message request, IClientChannel channel) { if (OnSend != null) OnSend(request); return null; } } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { // Nothing to do here. } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { // Nothing to do here. } public void Validate(ServiceEndpoint endpoint) { // Nothing to do here. } } }
mit
C#