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 |
|---|---|---|---|---|---|---|---|---|
54cebd8e879d40fab4dd9d8b3822bc71daa4ded5 | make Player nullable | svmnotn/friendly-guacamole | Assets/src/data/Player.cs | Assets/src/data/Player.cs | public class Player {
public int score;
public string type;
public Player(string type){
this.type = type;
this.score = 0;
}
}
| public struct Player {
public int score;
public string type;
public Player(string type){
this.type = type;
this.score = 0;
}
}
| mit | C# |
fa787247783e1dda7b67a7b75b6ffe73f3930cc6 | Increase assembly version to 'beta01' | Jericho/CakeMail.RestClient | CakeMail.RestClient/Properties/AssemblyInfo.cs | CakeMail.RestClient/Properties/AssemblyInfo.cs | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta01")] | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha01")] | mit | C# |
c324dde4dd159b869d34420e27b6107522529b31 | Update SolutionVersion to 2.11.1 | Faithlife/System.Data.SQLite,Faithlife/System.Data.SQLite | SolutionVersion.cs | SolutionVersion.cs | using System.Reflection;
[assembly: AssemblyVersion("2.11.1.0")]
[assembly: AssemblyFileVersion("2.11.1.0")]
[assembly: AssemblyInformationalVersion("2.11.1")]
| using System.Reflection;
[assembly: AssemblyVersion("2.11.0.0")]
[assembly: AssemblyFileVersion("2.11.0.0")]
[assembly: AssemblyInformationalVersion("2.11.0")]
| mit | C# |
c1b4acbfd6130ad3874ccf3a0b96246f3a0565d0 | Swap colon for dash in progress messages | unlimitedbacon/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl | PrinterCommunication/Io/SendProgressStream.cs | PrinterCommunication/Io/SendProgressStream.cs | /*
Copyright (c) 2015, Lars Brubaker
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.MatterControl.DataStorage;
using MatterHackers.MatterControl.SlicerConfiguration;
using System;
namespace MatterHackers.MatterControl.PrinterCommunication.Io
{
public class SendProgressStream : GCodeStreamProxy
{
private double nextPercent = -1;
PrinterConfig printer;
public SendProgressStream(PrinterConfig printer, GCodeStream internalStream)
: base(internalStream)
{
this.printer = printer;
}
public override string ReadLine()
{
if (printer.Settings.GetValue(SettingsKey.progress_reporting) != "None"
&& printer.Connection.CommunicationState == CommunicationStates.Printing
&& printer.Connection.activePrintTask != null
&& printer.Connection.activePrintTask.PercentDone > nextPercent)
{
nextPercent = Math.Round(printer.Connection.activePrintTask.PercentDone) + 0.5;
if (printer.Settings.GetValue(SettingsKey.progress_reporting) == "M73")
{
return String.Format("M73 P{0:0}", printer.Connection.activePrintTask.PercentDone);
}
else
{
return String.Format("M117 Printing - {0:0}%", printer.Connection.activePrintTask.PercentDone);
}
}
return base.ReadLine();
}
}
}
| /*
Copyright (c) 2015, Lars Brubaker
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.MatterControl.DataStorage;
using MatterHackers.MatterControl.SlicerConfiguration;
using System;
namespace MatterHackers.MatterControl.PrinterCommunication.Io
{
public class SendProgressStream : GCodeStreamProxy
{
private double nextPercent = -1;
PrinterConfig printer;
public SendProgressStream(PrinterConfig printer, GCodeStream internalStream)
: base(internalStream)
{
this.printer = printer;
}
public override string ReadLine()
{
if (printer.Settings.GetValue(SettingsKey.progress_reporting) != "None"
&& printer.Connection.CommunicationState == CommunicationStates.Printing
&& printer.Connection.activePrintTask != null
&& printer.Connection.activePrintTask.PercentDone > nextPercent)
{
nextPercent = Math.Round(printer.Connection.activePrintTask.PercentDone) + 0.5;
if (printer.Settings.GetValue(SettingsKey.progress_reporting) == "M73")
{
return String.Format("M73 P{0:0}", printer.Connection.activePrintTask.PercentDone);
}
else
{
return String.Format("M117 Printing: {0:0}%", printer.Connection.activePrintTask.PercentDone);
}
}
return base.ReadLine();
}
}
}
| bsd-2-clause | C# |
56d616c6cba9dd6b6f42135b150e9ad8a2c2ac67 | add missing license headers (#2730) | msft-shahins/BotBuilder,msft-shahins/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,stevengum97/BotBuilder,stevengum97/BotBuilder | CSharp/Library/Microsoft.Bot.Builder/Fibers/StackStoreFactory.cs | CSharp/Library/Microsoft.Bot.Builder/Fibers/StackStoreFactory.cs | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK GitHub:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// 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 Microsoft.Bot.Builder.Dialogs;
namespace Microsoft.Bot.Builder.Internals.Fibers
{
public interface IStackStoreFactory<C>
{
IStore<IFiberLoop<C>> StoreFrom(string taskId, IBotDataBag dataBag);
}
public sealed class StoreFromStack<C> : IStackStoreFactory<C>
{
private readonly Func<string, IBotDataBag, IStore<IFiberLoop<C>>> make;
public StoreFromStack(Func<string, IBotDataBag, IStore<IFiberLoop<C>>> make)
{
SetField.NotNull(out this.make, nameof(make), make);
}
IStore<IFiberLoop<C>> IStackStoreFactory<C>.StoreFrom(string stackId, IBotDataBag dataBag)
{
return this.make(stackId, dataBag);
}
}
}
| using System;
using Microsoft.Bot.Builder.Dialogs;
namespace Microsoft.Bot.Builder.Internals.Fibers
{
public interface IStackStoreFactory<C>
{
IStore<IFiberLoop<C>> StoreFrom(string taskId, IBotDataBag dataBag);
}
public sealed class StoreFromStack<C> : IStackStoreFactory<C>
{
private readonly Func<string, IBotDataBag, IStore<IFiberLoop<C>>> make;
public StoreFromStack(Func<string, IBotDataBag, IStore<IFiberLoop<C>>> make)
{
SetField.NotNull(out this.make, nameof(make), make);
}
IStore<IFiberLoop<C>> IStackStoreFactory<C>.StoreFrom(string stackId, IBotDataBag dataBag)
{
return this.make(stackId, dataBag);
}
}
}
| mit | C# |
5ce5dfab1a000b7dc973a347b44fce55ceea4d79 | Edit and Show Subtitle views edited | bergthor13/Skermstafir,bergthor13/Skermstafir,bergthor13/Skermstafir | Skermstafir/Views/Subtitle/EditSubtitle.cshtml | Skermstafir/Views/Subtitle/EditSubtitle.cshtml | @model Skermstafir.Models.SubtitleModel
@{
ViewBag.Title = "Edit Subtitle";
}
<div class="subtitle-box">
<div class="box-title">
<p>Gladiator</p>
<p class="votes-req-page">▲ 15</p>
</div>
<div class="flokkar">
<input type="checkbox" id="genre1" />
<label for="genre1">Kvikmyndir</label>
<input type="checkbox" id="genre2" />
<label for="genre2">Þættir</label>
<input type="checkbox" id="genre3" />
<label for="genre3">Barnaefni</label>
<input type="checkbox" id="genre4" />
<label for="genre4">Heimildir</label> <br />
<input type="checkbox" id="genre5" />
<label for="genre5">Gaman</label>
<input type="checkbox" id="genre6" />
<label for="genre6">Spenna</label>
<input type="checkbox" id="genre7" />
<label for="genre7">Drama</label>
<input type="checkbox" id="genre8" />
<label for="genre8">Ævintýri</label>
</div>
<p>Stofnandi þýðingu: </p>
<p>Útgáfuár:</p>
<input type="text" name="year" value="@Model.subtitle.YearCreated" disabled />
<textarea id="description" cols="50" rows="8" disabled>@Model.subtitle.Description</textarea>
</div>
<div class="col-md-6">
<textarea id="originalText" cols="900" rows="40" disabled></textarea>
</div>
<div class="col-md-6">
<textarea id="editedText" cols="900" rows="40" disabled></textarea>
</div> | @model Skermstafir.Models.SubtitleModel
@{
ViewBag.Title = "Edit Subtitle";
}
<div class="subtitle-box">
<div class="box-title">
<p>Gladiator</p>
<p class="votes-req-page">▲ 15</p>
</div>
<div class="flokkar disabled">
<input type="checkbox" id="genre1" />
<label for="genre1">Kvikmyndir</label>
<input type="checkbox" id="genre2" />
<label for="genre2">Þættir</label>
<input type="checkbox" id="genre3" />
<label for="genre3">Barnaefni</label>
<input type="checkbox" id="genre4" />
<label for="genre4">Heimildir</label> <br />
<input type="checkbox" id="genre5" />
<label for="genre5">Gaman</label>
<input type="checkbox" id="genre6" />
<label for="genre6">Spenna</label>
<input type="checkbox" id="genre7" />
<label for="genre7">Drama</label>
<input type="checkbox" id="genre8" />
<label for="genre8">Ævintýri</label>
</div>
<p>Stofnandi þýðingu: </p>
<p>Útgáfuár:</p>
<input type="text" name="year" value="2014" />
<textarea>Hér kemur lýsing á myndinni.</textarea>
<textarea cols="20" rows="20"></textarea>
<textarea cols="20" rows="20"></textarea>
</div> | mit | C# |
a43cf8460767939ba3faec18e1ebc5cb2f5c5e73 | test for build failure | Volodya7/VILab,Volodya7/VILab,Volodya7/VILab,Volodya7/VILab | VILab.API/Startup.cs | VILab.API/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc.Formatters;
namespace VILab.API
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();fgh
}
app.UseStatusCodePages();
app.UseMvc();
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc.Formatters;
namespace VILab.API
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
app.UseStatusCodePages();
app.UseMvc();
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
}
}
}
| mit | C# |
6397dda6c08b07431740b766e3dfd7ba3722a28d | Improve title | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/WalletExplorer/CoinInfoTabViewModel.cs | WalletWasabi.Gui/Controls/WalletExplorer/CoinInfoTabViewModel.cs | using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinInfoTabViewModel : WasabiDocumentTabViewModel
{
public CoinInfoTabViewModel(CoinViewModel coin) : base(string.Empty)
{
Coin = coin;
Title = $"Details of {coin.OutputIndex}:{coin.TransactionId[0..7]}";
}
public CoinViewModel Coin { get; }
}
}
| using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinInfoTabViewModel : WasabiDocumentTabViewModel
{
public CoinInfoTabViewModel(CoinViewModel coin) : base(string.Empty)
{
Coin = coin;
Title = $"{coin.TransactionId[0..7]}'s Details";
}
public CoinViewModel Coin { get; }
}
}
| mit | C# |
fa3511d0d2aebf2c001a2a0c8fe6d33acc553a86 | Update DeletingAColumn.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/RowsColumns/InsertingAndDeleting/DeletingAColumn.cs | Examples/CSharp/RowsColumns/InsertingAndDeleting/DeletingAColumn.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.InsertingAndDeleting
{
public class DeletingAColumn
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Deleting a column from the worksheet at 2nd position
worksheet.Cells.DeleteColumn(1);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.InsertingAndDeleting
{
public class DeletingAColumn
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Deleting a column from the worksheet at 2nd position
worksheet.Cells.DeleteColumn(1);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
} | mit | C# |
b1b0381d2282a408f0b16e94bc9caf2912595ec9 | Add texture brush test shapes. | l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1 | Source/Eto.Test/Eto.Test/Sections/Drawing/TextureBrushesSection2.cs | Source/Eto.Test/Eto.Test/Sections/Drawing/TextureBrushesSection2.cs | using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Drawing
{
class TextureBrushesSection2 : Scrollable
{
Bitmap image = TestIcons.Textures;
public TextureBrushesSection2()
{
var w = image.Size.Width / 3; // same as height
var img = image.Clone(new Rectangle(w, w, w, w));
var brush = new TextureBrush(img);
var drawable = new Drawable();
var font = new Font(SystemFont.Default);
this.Content = drawable;
var location = new PointF(100, 100);
drawable.BackgroundColor = Colors.Green;
drawable.MouseMove += (s, e) => {
location = e.Location;
drawable.Invalidate(); };
drawable.Paint += (s, e) => {
e.Graphics.DrawText(font, Colors.White, 3, 3, "Move the mouse in this area to move the textured shapes.");
var temp = brush.Transform; // save state
brush.Transform = Matrix.FromTranslation(location);
e.Graphics.FillRectangle(brush, new RectangleF(location, img.Size));
brush.Transform = temp;
location += new PointF(0, 100);
temp = brush.Transform; // save state
brush.Transform = Matrix.FromTranslation(location);
e.Graphics.FillEllipse(brush, new RectangleF(location, img.Size));
brush.Transform = temp;
location += new PointF(0, 100);
temp = brush.Transform; // save state
brush.Transform = Matrix.FromTranslation(location);
var polygon = GetPolygon(location);
e.Graphics.FillPolygon(brush, polygon);
brush.Transform = temp;
};
}
private static PointF[] GetPolygon(PointF location)
{
var polygon = new PointF[] { new PointF(0, 50), new PointF(50, 100), new PointF(100, 50), new PointF(50, 0) };
for (var i = 0; i < polygon.Length; ++i)
polygon[i] += location;
return polygon;
}
}
}
| using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Drawing
{
class TextureBrushesSection2 : Scrollable
{
Bitmap image = TestIcons.Textures;
public TextureBrushesSection2()
{
var w = image.Size.Width / 3; // same as height
var img = image.Clone(new Rectangle(w, w, w, w));
var brush = new TextureBrush(img);
var drawable = new Drawable();
var font = new Font(SystemFont.Default);
this.Content = drawable;
var location = new PointF(100, 100);
drawable.BackgroundColor = Colors.Green;
drawable.MouseMove += (s, e) => {
location = e.Location;
drawable.Invalidate(); };
drawable.Paint += (s, e) => {
e.Graphics.DrawText(font, Colors.White, 3, 3, "Move the mouse in this area to move the image.");
var temp = brush.Transform; // save state
brush.Transform = Matrix.FromTranslation(location);
e.Graphics.FillRectangle(brush, new RectangleF(location, img.Size));
brush.Transform = temp;
};
}
}
}
| bsd-3-clause | C# |
f00c0ca54bf922359dce3a22043fe8b3ba4d8f9a | Update TransactionHistory.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Test/AdventureWorksFunctionalModel/Production/TransactionHistory.cs | Test/AdventureWorksFunctionalModel/Production/TransactionHistory.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using NakedFunctions;
using static AW.Utilities;
namespace AW.Types {
public record TransactionHistory {
public virtual int TransactionID { get; init; }
public virtual int ReferenceOrderID { get; init; }
public virtual int ReferenceOrderLineID { get; init; }
public virtual DateTime TransactionDate { get; init; }
public virtual string TransactionType { get; init; }
public virtual int Quantity { get; init; }
public virtual decimal ActualCost { get; init; }
[Hidden]
public virtual int ProductID { get; init; }
public virtual Product Product { get; init; }
[MemberOrder(99)]
[Versioned]
public virtual DateTime ModifiedDate { get; init; }
public override string ToString() => $"TransactionHistory: {TransactionID}";
public override int GetHashCode() => HashCode(this, TransactionID);
public virtual bool Equals(TransactionHistory other) => ReferenceEquals(this, other);
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using NakedFunctions;
using static AW.Utilities;
namespace AW.Types {
public record TransactionHistory {
public virtual int TransactionID { get; init; }
public virtual int ReferenceOrderID { get; init; }
public virtual int ReferenceOrderLineID { get; init; }
public virtual DateTime TransactionDate { get; init; }
public virtual string TransactionType { get; init; }
public virtual int Quantity { get; init; }
public virtual decimal ActualCost { get; init; }
[Hidden]
public virtual int ProductID { get; init; }
public Product Product { get; init; }
[MemberOrder(99)]
[Versioned]
public virtual DateTime ModifiedDate { get; init; }
public override string ToString() => $"TransactionHistory: {TransactionID}";
public override int GetHashCode() => HashCode(this, TransactionID);
public virtual bool Equals(TransactionHistory other) => ReferenceEquals(this, other);
}
} | apache-2.0 | C# |
495b92208f6282492eedf1e6f045299a0cce7fac | Update StarScythe.cs | Minesap/TheMinepack | Projectiles/StarScythe.cs | Projectiles/StarScythe.cs | using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace TheMinepack.Projectiles
{
public class StarScytheProjectile : ModProjectile
{
public override void SetDefaults()
{
projectile.CloneDefaults(ProjectileID.IceSickle);
projectile.name = "Starry Scythe";
projectile.width = 32;
projectile.scale = 1.15f;
projectile.height = 32;
projectile.aiStyle = 18;
aiType = 274;
}
public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
Projectile.NewProjectile(target.position.X + (float)target.velocity.X, target.position.Y - 500, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
Projectile.NewProjectile(target.position.X - 20 + (float)target.velocity.X, target.position.Y - 470, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
Projectile.NewProjectile(target.position.X + 40 + (float)target.velocity.X, target.position.Y - 580, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
}
}
}
| using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace Minepack.Projectiles
{
public class StarScythe : ModProjectile
{
public override void SetDefaults()
{
projectile.CloneDefaults(ProjectileID.IceSickle);
projectile.name = "Starry Scythe";
projectile.width = 32;
projectile.scale = 1.15f;
projectile.height = 32;
projectile.aiStyle = 18;
aiType = 274;
}
public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
Projectile.NewProjectile(target.position.X + (float)target.velocity.X, target.position.Y - 500, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
Projectile.NewProjectile(target.position.X - 20 + (float)target.velocity.X, target.position.Y - 470, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
Projectile.NewProjectile(target.position.X + 40 + (float)target.velocity.X, target.position.Y - 580, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
}
}
} | mit | C# |
37044bb9fd53f0501a1f67a2b91d34fa8a429bfb | test to check the cancellation list is being maintained | rmacdonaldsmith/ForgetMeNot-Akka | src/Core.Tests/Cancellation/WhenCancelled.cs | src/Core.Tests/Cancellation/WhenCancelled.cs | using System;
using Akka.Actor;
using Akka.TestKit.NUnit;
using ForgetMeNot.Core.Cancellation;
using ForgetMeNot.Messages;
using NUnit.Framework;
namespace ForgetMeNot.Core.Tests.Cancellation
{
public class WhenCancelled : TestKit
{
[Test]
public void ShouldAllowNonCancelledRemindersThrough()
{
var cancellationFilter = ActorOf(CancellationFilter.ActorProps(TestActor), "cancellation-filter-1");
cancellationFilter.Tell(new ReminderMessage.Cancel(Guid.NewGuid()));
cancellationFilter.Tell(new ReminderMessage.Cancel(Guid.NewGuid()));
var due = new ReminderMessage.Due(TestHelper.BuildMeAScheduleMessage());
cancellationFilter.Tell(due);
ExpectMsg<ReminderMessage.Due>(dueReminder => due.ReminderId = dueReminder.ReminderId);
}
[Test]
public void ShouldBlockCancelledReminders()
{
var cancelledReminderId = Guid.NewGuid();
var cancellationFilter = ActorOf(CancellationFilter.ActorProps(TestActor), "cancellation-filter-2");
cancellationFilter.Tell(new ReminderMessage.Cancel(cancelledReminderId));
cancellationFilter.Tell(new ReminderMessage.Cancel(Guid.NewGuid()));
var due = new ReminderMessage.Due(TestHelper.BuildMeAScheduleMessage().WithIdentity(cancelledReminderId));
cancellationFilter.Tell(due);
ExpectNoMsg();
//we should now be able to send the due reminder with this "cancelled" id again
//it should have been removed from the list that the CancellationFilter maintains,
//hence we can test that the list is being maintained
cancellationFilter.Tell(due);
ExpectMsg<ReminderMessage.Due>(dueReminder => due.ReminderId == dueReminder.ReminderId);
}
}
}
| using System;
using Akka.Actor;
using Akka.TestKit.NUnit;
using ForgetMeNot.Core.Cancellation;
using ForgetMeNot.Messages;
using NUnit.Framework;
namespace ForgetMeNot.Core.Tests.Cancellation
{
public class WhenCancelled : TestKit
{
[Test]
public void ShouldAllowNonCancelledRemindersThrough()
{
var cancellationFilter = ActorOf(CancellationFilter.ActorProps(TestActor), "cancellation-filter-1");
cancellationFilter.Tell(new ReminderMessage.Cancel(Guid.NewGuid()));
cancellationFilter.Tell(new ReminderMessage.Cancel(Guid.NewGuid()));
var due = new ReminderMessage.Due(TestHelper.BuildMeAScheduleMessage());
cancellationFilter.Tell(due);
ExpectMsg<ReminderMessage.Due>(dueReminder => due.ReminderId = dueReminder.ReminderId);
}
[Test]
public void ShouldBlockCancelledReminders()
{
var cancelledReminderId = Guid.NewGuid();
var cancellationFilter = ActorOf(CancellationFilter.ActorProps(TestActor), "cancellation-filter-2");
cancellationFilter.Tell(new ReminderMessage.Cancel(cancelledReminderId));
cancellationFilter.Tell(new ReminderMessage.Cancel(Guid.NewGuid()));
var due = new ReminderMessage.Due(TestHelper.BuildMeAScheduleMessage().WithIdentity(cancelledReminderId));
cancellationFilter.Tell(due);
ExpectNoMsg();
}
}
}
| mit | C# |
bc7c8574e954f127ab0253861fd0022318f2620d | Improve comparison order to avoid reading blob values by mistake | kamsar/Rainbow,MacDennis76/Rainbow,PetersonDave/Rainbow | src/Rainbow/Diff/Fields/DefaultComparison.cs | src/Rainbow/Diff/Fields/DefaultComparison.cs | using Rainbow.Model;
namespace Rainbow.Diff.Fields
{
public class DefaultComparison : IFieldComparer
{
public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2)
{
return field1 != null && field2 != null;
}
public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
{
if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value);
var field1Value = field1.Value;
var field2Value = field2.Value;
if (field1Value == null || field2Value == null) return false;
return field1Value.Equals(field2Value);
}
}
}
| using Rainbow.Model;
namespace Rainbow.Diff.Fields
{
public class DefaultComparison : IFieldComparer
{
public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2)
{
return field1 != null && field2 != null;
}
public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
{
if (field1.Value == null || field2.Value == null) return false;
if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value);
return field1.Value.Equals(field2.Value);
}
}
}
| mit | C# |
8a54eb77f1535b52570390c6dcaa6ff1fd2f8fb6 | update totpHelperTest | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | test/WeihanLi.Common.Test/HelpersTest/TotpHelperTest.cs | test/WeihanLi.Common.Test/HelpersTest/TotpHelperTest.cs | using System.Threading;
using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class TotpHelperTest
{
private readonly object _lock = new object();
[Fact]
public void Test()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = null;
options.ExpiresIn = 600;
});
var bizToken = "test_xxx";
var code = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.True(TotpHelper.VerifyCode(bizToken, code));
}
}
[Fact]
public void SaltTest()
{
lock (_lock)
{
var bizToken = "test_xxx";
TotpHelper.ConfigureTotpOptions(options => options.Salt = null);
var code = TotpHelper.GenerateCode(bizToken);
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = "amazing-dotnet";
options.ExpiresIn = 600;
});
var code1 = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.False(TotpHelper.VerifyCode(bizToken, code));
Assert.NotEmpty(code1);
Assert.True(TotpHelper.VerifyCode(bizToken, code1));
}
}
}
}
| using System.Threading;
using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class TotpHelperTest
{
private readonly object _lock = new object();
[Fact]
public void Test()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = null;
options.ExpiresIn = 300;
});
var bizToken = "test_xxx";
var code = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.True(TotpHelper.VerifyCode(bizToken, code));
}
}
[Fact]
public void SaltTest()
{
lock (_lock)
{
var bizToken = "test_xxx";
TotpHelper.ConfigureTotpOptions(options => options.Salt = null);
var code = TotpHelper.GenerateCode(bizToken);
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = "amazing-dotnet";
options.ExpiresIn = 300;
});
var code1 = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.False(TotpHelper.VerifyCode(bizToken, code));
Assert.NotEmpty(code1);
Assert.True(TotpHelper.VerifyCode(bizToken, code1));
}
}
}
}
| mit | C# |
ac08d2c9711b694fa228e91ecb5e081951a4c3d0 | Add field in savegame | Xeeynamo/KingdomHearts | OpenKh.Kh2/SaveData/DriveForm.cs | OpenKh.Kh2/SaveData/DriveForm.cs | /*
Kingdom Save Editor
Copyright (C) 2021 Luciano Ciccariello
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Xe.BinaryMapper;
namespace OpenKh.Kh2.SaveData
{
public interface IDriveForm
{
short Weapon { get; set; }
byte Level { get; set; }
byte AbilityLevel { get; set; }
int Experience { get; set; }
ushort[] Abilities { get; set; }
}
public class DriveFormVanilla : IDriveForm
{
[Data(0)] public short Weapon { get; set; }
[Data] public byte Level { get; set; }
[Data] public byte AbilityLevel { get; set; }
[Data] public int Experience { get; set; }
[Data(Count = 0x10)] public ushort[] Abilities { get; set; }
}
public class DriveFormFinalMix : IDriveForm
{
[Data(0)] public short Weapon { get; set; }
[Data] public byte Level { get; set; }
[Data] public byte AbilityLevel { get; set; }
[Data] public int Experience { get; set; }
[Data(Count = 0x18)] public ushort[] Abilities { get; set; }
}
}
| /*
Kingdom Save Editor
Copyright (C) 2021 Luciano Ciccariello
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Xe.BinaryMapper;
namespace OpenKh.Kh2.SaveData
{
public interface IDriveForm
{
short Weapon { get; set; }
byte Level { get; set; }
byte Unknown { get; set; }
int Experience { get; set; }
ushort[] Abilities { get; set; }
}
public class DriveFormVanilla : IDriveForm
{
[Data(0)] public short Weapon { get; set; }
[Data] public byte Level { get; set; }
[Data] public byte Unknown { get; set; }
[Data] public int Experience { get; set; }
[Data(Count = 0x10)] public ushort[] Abilities { get; set; }
}
public class DriveFormFinalMix : IDriveForm
{
[Data(0)] public short Weapon { get; set; }
[Data] public byte Level { get; set; }
[Data] public byte Unknown { get; set; }
[Data] public int Experience { get; set; }
[Data(Count = 0x18)] public ushort[] Abilities { get; set; }
}
}
| mit | C# |
602ef2b41e4168e82f5a7a601fe303a4d4b809d1 | Add initial category selection | zaynetro/PicMatcher | PicMatcher/Pages/SettingsPage.cs | PicMatcher/Pages/SettingsPage.cs | using System;
using Xamarin.Forms;
using System.Collections.Generic;
namespace PicMatcher
{
public class SettingsPage : ContentPage
{
GameSettings _settings;
Dictionary<string, Category> _catsHash = new Dictionary<string, Category> ();
Dictionary<string, Language> _langHash = new Dictionary<string, Language> ();
int _catsSelected = 0;
public SettingsPage () {}
public SettingsPage (GameSettings Settings) {
_settings = Settings;
// Categories table section
var catSection = new TableSection ("Categories");
// Populate section with switches
foreach (Category cat in Settings.Categories) {
_catsHash.Add (cat.Name, cat);
var cell = new SwitchCell {
Text = cat.Name
};
cell.OnChanged += SwitchCellChanged;
if (cat.IsOn) cell.On = true;
catSection.Add (cell);
}
// When no category is selected, select first one
if (_catsSelected == 0)
((SwitchCell)catSection [0]).On = true;
var tableView = new TableView {
Intent = TableIntent.Settings,
Root = new TableRoot ("Settings") {
catSection
}
};
// Languages picker
var languagePicker = new Picker {
Title = "Language",
VerticalOptions = LayoutOptions.CenterAndExpand
};
// Populate picker
foreach (Language lang in Settings.Languages) {
_langHash.Add (lang.Name, lang);
languagePicker.Items.Add (lang.Name);
}
languagePicker.SelectedIndex = 0;
var languageGroup = new StackLayout {
Padding = 20,
Children = {
languagePicker
}
};
var DoneBtn = new Button {
Text = "Done"
};
DoneBtn.Clicked += (object sender, EventArgs e) => {
if(CanLeave()) Navigation.PopModalAsync();
};
Content = new StackLayout {
VerticalOptions = LayoutOptions.FillAndExpand,
Children = {
languageGroup,
tableView,
DoneBtn
}
};
}
void SwitchCellChanged(object sender, EventArgs e) {
var cell = (SwitchCell)sender;
// Get Category position
var catIndex = _settings.Categories.IndexOf (_catsHash [cell.Text]);
// Update IsEnabled field
var isOn = cell.On;
_settings.Categories [catIndex].IsOn = isOn;
// Count number of selected categories
if (isOn)
_catsSelected++;
else
_catsSelected--;
}
bool CanLeave() {
if(_catsSelected == 0) {
DisplayAlert("No category selected", "Select at least one category", "OK");
return false;
}
return true;
}
protected override bool OnBackButtonPressed () {
// Return true if you don't want to leave page (wierd)
if (!CanLeave()) return true;
return base.OnBackButtonPressed ();
}
}
}
| using System;
using Xamarin.Forms;
using System.Collections.Generic;
namespace PicMatcher
{
public class SettingsPage : ContentPage
{
GameSettings _settings;
Dictionary<string, Category> _catsHash = new Dictionary<string, Category> ();
Dictionary<string, Language> _langHash = new Dictionary<string, Language> ();
int _catsSelected = 0;
public SettingsPage () {}
public SettingsPage (GameSettings Settings) {
_settings = Settings;
// Categories table section
var catSection = new TableSection ("Categories");
// Populate section with switches
foreach (Category cat in Settings.Categories) {
_catsHash.Add (cat.Name, cat);
var cell = new SwitchCell {
Text = cat.Name
};
cell.OnChanged += SwitchCellChanged;
if (cat.IsOn)
cell.On = true;
catSection.Add (cell);
}
var tableView = new TableView {
Intent = TableIntent.Settings,
Root = new TableRoot ("Settings") {
catSection
}
};
// Languages picker
var languagePicker = new Picker {
Title = "Language",
VerticalOptions = LayoutOptions.CenterAndExpand
};
// Populate picker
foreach (Language lang in Settings.Languages) {
_langHash.Add (lang.Name, lang);
languagePicker.Items.Add (lang.Name);
}
languagePicker.SelectedIndex = 0;
var languageGroup = new StackLayout {
Padding = 20,
Children = {
languagePicker
}
};
var DoneBtn = new Button {
Text = "Done"
};
DoneBtn.Clicked += (object sender, EventArgs e) => {
if(CanLeave()) Navigation.PopModalAsync();
};
Content = new StackLayout {
VerticalOptions = LayoutOptions.FillAndExpand,
Children = {
languageGroup,
tableView,
DoneBtn
}
};
}
void SwitchCellChanged(object sender, EventArgs e) {
var cell = (SwitchCell)sender;
// Get Category position
var catIndex = _settings.Categories.IndexOf (_catsHash [cell.Text]);
// Update IsEnabled field
var isOn = cell.On;
_settings.Categories [catIndex].IsOn = isOn;
// Count number of selected categories
if (isOn)
_catsSelected++;
else
_catsSelected--;
}
bool CanLeave() {
if(_catsSelected == 0) {
DisplayAlert("No category selected", "Select at least one category", "OK");
return false;
}
return true;
}
protected override bool OnBackButtonPressed () {
// Return true if you don't want to leave page (wierd)
if (!CanLeave()) return true;
return base.OnBackButtonPressed ();
}
}
}
| mit | C# |
c6dab57f566f786b315a3e25e7f35053d591676c | Update BracketPush.cs | ErikSchierboom/xcsharp,GKotfis/csharp,exercism/xcsharp,robkeim/xcsharp,GKotfis/csharp,ErikSchierboom/xcsharp,exercism/xcsharp,robkeim/xcsharp | exercises/bracket-push/BracketPush.cs | exercises/bracket-push/BracketPush.cs | using System;
public static class BracketPush
{
public static bool IsPaired(string input)
{
throw new NotImplementedException();
}
}
| using System.Linq;
public static class BracketPush
{
public static bool IsPaired(string input)
{
var brackets = new string(input.Where(c => "[]{}()".Contains(c)).ToArray());
var previousLength = brackets.Length;
while (brackets.Length > 0)
{
brackets = brackets.Replace("[]", "").Replace("{}", "").Replace("()", "");
if (brackets.Length == previousLength)
return false;
previousLength = brackets.Length;
}
return true;
}
}
| mit | C# |
ec4e1ad61dedb3167e6ef511cc180c0e48957f01 | Remove comment | insthync/unity-utilities | UnityUtilities/Scripts/Misc/UnityUtils.cs | UnityUtilities/Scripts/Misc/UnityUtils.cs | using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
| using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
/// <summary>
/// Detect headless mode (which has graphicsDeviceType Null)
/// </summary>
/// <returns></returns>
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
| mit | C# |
870eb92e5c5d29aa25bdf1f6e4ad87acd7be0f63 | Fix ParentProvider not being set on MyFilteringProcessor (#3370) | open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet | docs/trace/extending-the-sdk/MyFilteringProcessor.cs | docs/trace/extending-the-sdk/MyFilteringProcessor.cs | // <copyright file="MyFilteringProcessor.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
/// <summary>
/// A custom processor for filtering <see cref="Activity"/> instances.
/// </summary>
/// <remarks>
/// Note: <see cref="CompositeProcessor{T}"/> is used as the base class because
/// the SDK needs to understand that <c>MyFilteringProcessor</c> wraps an inner
/// processor. Without that understanding some features such as <see
/// cref="Resource"/> would be unavailable because the SDK needs to push state
/// about the parent <see cref="TracerProvider"/> to all processors in the
/// chain.
/// </remarks>
internal sealed class MyFilteringProcessor : CompositeProcessor<Activity>
{
private readonly Func<Activity, bool> filter;
public MyFilteringProcessor(BaseProcessor<Activity> processor, Func<Activity, bool> filter)
: base(new[] { processor })
{
this.filter = filter ?? throw new ArgumentNullException(nameof(filter));
}
public override void OnEnd(Activity activity)
{
// Call the underlying processor
// only if the Filter returns true.
if (this.filter(activity))
{
base.OnEnd(activity);
}
}
}
| // <copyright file="MyFilteringProcessor.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using OpenTelemetry;
internal class MyFilteringProcessor : BaseProcessor<Activity>
{
private readonly Func<Activity, bool> filter;
private readonly BaseProcessor<Activity> processor;
public MyFilteringProcessor(BaseProcessor<Activity> processor, Func<Activity, bool> filter)
{
this.filter = filter ?? throw new ArgumentNullException(nameof(filter));
this.processor = processor ?? throw new ArgumentNullException(nameof(processor));
}
public override void OnEnd(Activity activity)
{
// Call the underlying processor
// only if the Filter returns true.
if (this.filter(activity))
{
this.processor.OnEnd(activity);
}
}
}
| apache-2.0 | C# |
3a5b21c0f5caafc98e93783f5d014dbc34841f8c | Update "reset all bindings" button to better match new key binding row widths | smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Overlays/KeyBinding/KeyBindingsSubsection.cs | osu.Game/Overlays/KeyBinding/KeyBindingsSubsection.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets;
using osuTK;
namespace osu.Game.Overlays.KeyBinding
{
public abstract class KeyBindingsSubsection : SettingsSubsection
{
protected IEnumerable<Framework.Input.Bindings.KeyBinding> Defaults;
protected RulesetInfo Ruleset;
private readonly int? variant;
protected KeyBindingsSubsection(int? variant)
{
this.variant = variant;
FlowContent.Spacing = new Vector2(0, 1);
FlowContent.Padding = new MarginPadding { Left = SettingsPanel.CONTENT_MARGINS, Right = SettingsPanel.CONTENT_MARGINS };
}
[BackgroundDependencyLoader]
private void load(KeyBindingStore store)
{
var bindings = store.Query(Ruleset?.ID, variant);
foreach (var defaultGroup in Defaults.GroupBy(d => d.Action))
{
// one row per valid action.
Add(new RestorableKeyBindingRow(defaultGroup.Key, bindings, Ruleset, defaultGroup.Select(d => d.KeyCombination)));
}
Add(new ResetButton
{
Action = () => Children.OfType<RestorableKeyBindingRow>().ForEach(k => k.KeyBindingRow.RestoreDefaults())
});
}
}
public class ResetButton : DangerousTriangleButton
{
[BackgroundDependencyLoader]
private void load()
{
Text = "Reset all bindings in section";
RelativeSizeAxes = Axes.X;
Width = 0.5f;
Anchor = Anchor.TopCentre;
Origin = Anchor.TopCentre;
Margin = new MarginPadding { Top = 15 };
Height = 30;
Content.CornerRadius = 5;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets;
using osuTK;
namespace osu.Game.Overlays.KeyBinding
{
public abstract class KeyBindingsSubsection : SettingsSubsection
{
protected IEnumerable<Framework.Input.Bindings.KeyBinding> Defaults;
protected RulesetInfo Ruleset;
private readonly int? variant;
protected KeyBindingsSubsection(int? variant)
{
this.variant = variant;
FlowContent.Spacing = new Vector2(0, 1);
FlowContent.Padding = new MarginPadding { Left = SettingsPanel.CONTENT_MARGINS, Right = SettingsPanel.CONTENT_MARGINS };
}
[BackgroundDependencyLoader]
private void load(KeyBindingStore store)
{
var bindings = store.Query(Ruleset?.ID, variant);
foreach (var defaultGroup in Defaults.GroupBy(d => d.Action))
{
// one row per valid action.
Add(new RestorableKeyBindingRow(defaultGroup.Key, bindings, Ruleset, defaultGroup.Select(d => d.KeyCombination)));
}
Add(new ResetButton
{
Action = () => Children.OfType<RestorableKeyBindingRow>().ForEach(k => k.KeyBindingRow.RestoreDefaults())
});
}
}
public class ResetButton : DangerousTriangleButton
{
[BackgroundDependencyLoader]
private void load()
{
Text = "Reset all bindings in section";
RelativeSizeAxes = Axes.X;
Margin = new MarginPadding { Top = 5 };
Height = 20;
Content.CornerRadius = 5;
}
}
} | mit | C# |
fedf04ad6760b4fa2ce20b2ac3133912a82ab7d4 | Remove extra read | SteamDatabase/ValveResourceFormat | ValveResourceFormat/ResourceTypes/Panorama.cs | ValveResourceFormat/ResourceTypes/Panorama.cs | using System;
using System.IO;
using System.Text;
namespace ValveResourceFormat.ResourceTypes
{
public class Panorama : Blocks.ResourceData
{
public byte[] Data { get; private set; }
public override void Read(BinaryReader reader)
{
reader.BaseStream.Position = this.Offset;
reader.ReadBytes(4); // TODO: ????
var size = reader.ReadUInt16();
int headerSize = 4 + 2;
while (size-- > 0)
{
var name = reader.ReadNullTermString(Encoding.UTF8);
reader.ReadBytes(4); // TODO: ????
headerSize += name.Length + 1 + 4; // string length + null byte + 4 bytes
}
Data = reader.ReadBytes((int)this.Size - headerSize);
}
}
}
| using System;
using System.IO;
using System.Text;
namespace ValveResourceFormat.ResourceTypes
{
public class Panorama : Blocks.ResourceData
{
public byte[] Data { get; private set; }
public override void Read(BinaryReader reader)
{
reader.BaseStream.Position = this.Offset;
var test = reader.ReadUInt32();
reader.ReadBytes(4); // TODO: ????
var size = reader.ReadUInt16();
int headerSize = 4 + 2;
while (size-- > 0)
{
var name = reader.ReadNullTermString(Encoding.UTF8);
reader.ReadBytes(4); // TODO: ????
headerSize += name.Length + 1 + 4; // string length + null byte + 4 bytes
}
Data = reader.ReadBytes((int)this.Size - headerSize);
}
}
}
| mit | C# |
f498afb46f487aa24977f20b69e6f7c77105efcd | Make Add and Increment internal | paparony03/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,default0/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,naoey/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,default0/osu-framework,Tom94/osu-framework | osu.Framework/Statistics/FrameStatistics.cs | osu.Framework/Statistics/FrameStatistics.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
namespace osu.Framework.Statistics
{
internal class FrameStatistics
{
internal readonly Dictionary<PerformanceCollectionType, double> CollectedTimes = new Dictionary<PerformanceCollectionType, double>(NUM_STATISTICS_COUNTER_TYPES);
internal readonly Dictionary<StatisticsCounterType, long> Counts = new Dictionary<StatisticsCounterType, long>(NUM_STATISTICS_COUNTER_TYPES);
internal readonly List<int> GarbageCollections = new List<int>();
internal static readonly int NUM_STATISTICS_COUNTER_TYPES = Enum.GetValues(typeof(StatisticsCounterType)).Length;
internal static readonly int NUM_PERFORMANCE_COLLECTION_TYPES = Enum.GetValues(typeof(PerformanceCollectionType)).Length;
internal static readonly long[] COUNTERS = new long[NUM_STATISTICS_COUNTER_TYPES];
internal void Clear()
{
CollectedTimes.Clear();
GarbageCollections.Clear();
Counts.Clear();
}
internal static void Increment(StatisticsCounterType type) => ++COUNTERS[(int)type];
internal static void Add(StatisticsCounterType type, long amount) => COUNTERS[(int)type] += amount;
}
internal enum PerformanceCollectionType
{
Work = 0,
SwapBuffer,
WndProc,
Debug,
Sleep,
Scheduler,
IPC,
GLReset,
}
internal enum StatisticsCounterType
{
Invalidations = 0,
Refreshes,
DrawNodeCtor,
DrawNodeAppl,
ScheduleInvk,
VBufBinds,
VBufOverflow,
TextureBinds,
DrawCalls,
VerticesDraw,
VerticesUpl,
Pixels,
TasksRun,
Tracks,
Samples,
SChannels,
Components,
MouseEvents,
KeyEvents,
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
namespace osu.Framework.Statistics
{
internal class FrameStatistics
{
internal readonly Dictionary<PerformanceCollectionType, double> CollectedTimes = new Dictionary<PerformanceCollectionType, double>(NUM_STATISTICS_COUNTER_TYPES);
internal readonly Dictionary<StatisticsCounterType, long> Counts = new Dictionary<StatisticsCounterType, long>(NUM_STATISTICS_COUNTER_TYPES);
internal readonly List<int> GarbageCollections = new List<int>();
internal static readonly int NUM_STATISTICS_COUNTER_TYPES = Enum.GetValues(typeof(StatisticsCounterType)).Length;
internal static readonly int NUM_PERFORMANCE_COLLECTION_TYPES = Enum.GetValues(typeof(PerformanceCollectionType)).Length;
internal static readonly long[] COUNTERS = new long[NUM_STATISTICS_COUNTER_TYPES];
internal void Clear()
{
CollectedTimes.Clear();
GarbageCollections.Clear();
Counts.Clear();
}
public static void Increment(StatisticsCounterType type) => ++COUNTERS[(int)type];
public static void Add(StatisticsCounterType type, long amount) => COUNTERS[(int)type] += amount;
}
internal enum PerformanceCollectionType
{
Work = 0,
SwapBuffer,
WndProc,
Debug,
Sleep,
Scheduler,
IPC,
GLReset,
}
internal enum StatisticsCounterType
{
Invalidations = 0,
Refreshes,
DrawNodeCtor,
DrawNodeAppl,
ScheduleInvk,
VBufBinds,
VBufOverflow,
TextureBinds,
DrawCalls,
VerticesDraw,
VerticesUpl,
Pixels,
TasksRun,
Tracks,
Samples,
SChannels,
Components,
MouseEvents,
KeyEvents,
}
}
| mit | C# |
9a02c0c326bef1a8f2999644d17458b5dc864fdb | Fix typo in CounterValue.cs | AngleSharp/AngleSharp.Css,AngleSharp/AngleSharp.Css,AngleSharp/AngleSharp.Css | src/AngleSharp.Css/Values/Primitives/CounterValue.cs | src/AngleSharp.Css/Values/Primitives/CounterValue.cs | namespace AngleSharp.Css.Values
{
using AngleSharp.Text;
using System;
/// <summary>
/// Sets a CSS counter.
/// </summary>
struct CounterValue : ICssPrimitiveValue, IEquatable<CounterValue>
{
#region Fields
private readonly String _name;
private readonly Int32 _value;
#endregion
#region ctor
/// <summary>
/// Specifies a counter value.
/// </summary>
/// <param name="name">The name of the referenced counter.</param>
/// <param name="value">The new value of the counter.</param>
public CounterValue(String name, Int32 value)
{
_name = name;
_value = value;
}
#endregion
#region Properties
/// <summary>
/// Gets the CSS text representation.
/// </summary>
public String CssText => String.Concat(_name, " ", _value.ToString());
/// <summary>
/// Gets the identifier of the counter.
/// </summary>
public String Name => _name;
/// <summary>
/// Gets the value of the counter.
/// </summary>
public Int32 Value => _value;
#endregion
#region Methods
/// <summary>
/// Checks the two counter values for equality.
/// </summary>
/// <param name="other">The other counter to check against.</param>
/// <returns>True if both are equal, otherwise false.</returns>
public Boolean Equals(CounterValue other) => Name.Is(other.Name) && Value == other.Value;
/// <summary>
/// Checks for equality against the given object,
/// if the provided object is no counter value the
/// result is false.
/// </summary>
/// <param name="obj">The object to check against.</param>
/// <returns>True if both are equal, otherwise false.</returns>
public override Boolean Equals(Object obj) =>
obj is CounterValue cv ? Equals(cv) : false;
/// <summary>
/// Gets the hash code of the object.
/// </summary>
/// <returns>The computed hash code.</returns>
public override Int32 GetHashCode() => CssText.GetHashCode();
#endregion
}
}
| namespace AngleSharp.Css.Values
{
using AngleSharp.Text;
using System;
/// <summary>
/// Sets a CSS counter.
/// </summary>
struct CounterValue : ICssPrimitiveValue, IEquatable<CounterValue>
{
#region Fields
private readonly String _name;
private readonly Int32 _value;
#endregion
#region ctor
/// <summary>
/// Specifies a counter value.
/// </summary>
/// <param name="name">The name of the referenced counter.</param>
/// <param name="value">The new value of the counter.</param>
public CounterValue(String name, Int32 value)
{
_name = name;
_value = value;
}
#endregion
#region Properties
/// <summary>
/// Gets the CSS text representation.
/// </summary>
public String CssText => String.Concat(_name, " ", _value.ToString());
/// <summary>
/// Gets the identifier of the counter.
/// </summary>
public String Name => _name;
/// <summary>
/// Gets the value of the counter.
/// </summary>
public Int32 Value => _value;
#endregion
#region Methods
/// <summary>
/// Checks the two counter values for equality.
/// </summary>
/// <param name="other">The other counter to check against.</param>
/// <returns>True if both are equal, otherwise false.</returns>
public Boolean Equals(CounterValue other) => Name.Is(other.Name) && Value == other.Value;
/// <summary>
/// Checks for equality against the given object,
/// if the provided object is no counter vlaue the
/// result is false.
/// </summary>
/// <param name="obj">The object to check against.</param>
/// <returns>True if both are equal, otherwise false.</returns>
public override Boolean Equals(Object obj) =>
obj is CounterValue cv ? Equals(cv) : false;
/// <summary>
/// Gets the hash code of the object.
/// </summary>
/// <returns>The computed hash code.</returns>
public override Int32 GetHashCode() => CssText.GetHashCode();
#endregion
}
}
| mit | C# |
4806b9e52ff191537d181d29406f071cbc110931 | Fix EF Core issue, where `MySqlGeometry.Value` of type `ReadOnlySpan<byte>` will throw an exception in `Microsoft.EntityFrameworkCore.Storage.Internal.DbParameterCollectionExtensions.FormatParameterValue(StringBuilder builder, object parameterValue)`. | mysql-net/MySqlConnector,mysql-net/MySqlConnector | src/MySqlConnector/MySql.Data.Types/MySqlGeometry.cs | src/MySqlConnector/MySql.Data.Types/MySqlGeometry.cs | using System;
using System.Buffers.Binary;
namespace MySql.Data.Types
{
/// <summary>
/// Represents MySQL's internal GEOMETRY format: https://dev.mysql.com/doc/refman/8.0/en/gis-data-formats.html#gis-internal-format
/// </summary>
public sealed class MySqlGeometry
{
/// <summary>
/// Constructs a <see cref="MySqlGeometry"/> from a SRID and Well-known Binary bytes.
/// </summary>
/// <param name="srid">The SRID (Spatial Reference System ID).</param>
/// <param name="wkb">The Well-known Binary serialization of the geometry.</param>
/// <returns>A new <see cref="MySqlGeometry"/> containing the specified geometry.</returns>
public static MySqlGeometry FromWkb(int srid, ReadOnlySpan<byte> wkb)
{
var bytes = new byte[wkb.Length + 4];
BinaryPrimitives.WriteInt32LittleEndian(bytes, srid);
wkb.CopyTo(bytes.AsSpan().Slice(4));
return new MySqlGeometry(bytes);
}
/// <summary>
/// Constructs a <see cref="MySqlGeometry"/> from MySQL's internal format.
/// </summary>
/// <param name="value">The raw bytes of MySQL's internal GEOMETRY format.</param>
/// <returns>A new <see cref="MySqlGeometry"/> containing the specified geometry.</returns>
/// <remarks>See <a href="https://dev.mysql.com/doc/refman/8.0/en/gis-data-formats.html#gis-internal-format">Internal Geometry Storage Format</a>.</remarks>
public static MySqlGeometry FromMySql(ReadOnlySpan<byte> value) => new MySqlGeometry(value.ToArray());
/// <summary>
/// The Spatial Reference System ID of this geometry.
/// </summary>
public int SRID => BinaryPrimitives.ReadInt32LittleEndian(m_bytes);
/// <summary>
/// The Well-known Binary serialization of this geometry.
/// </summary>
public ReadOnlySpan<byte> WKB => new ReadOnlySpan<byte>(Value).Slice(4);
/// <summary>
/// The internal MySQL form of this geometry.
/// </summary>
public byte[] Value => m_bytes;
internal MySqlGeometry(byte[] bytes) => m_bytes = bytes;
readonly byte[] m_bytes;
}
}
| using System;
using System.Buffers.Binary;
namespace MySql.Data.Types
{
/// <summary>
/// Represents MySQL's internal GEOMETRY format: https://dev.mysql.com/doc/refman/8.0/en/gis-data-formats.html#gis-internal-format
/// </summary>
public sealed class MySqlGeometry
{
/// <summary>
/// Constructs a <see cref="MySqlGeometry"/> from a SRID and Well-known Binary bytes.
/// </summary>
/// <param name="srid">The SRID (Spatial Reference System ID).</param>
/// <param name="wkb">The Well-known Binary serialization of the geometry.</param>
/// <returns>A new <see cref="MySqlGeometry"/> containing the specified geometry.</returns>
public static MySqlGeometry FromWkb(int srid, ReadOnlySpan<byte> wkb)
{
var bytes = new byte[wkb.Length + 4];
BinaryPrimitives.WriteInt32LittleEndian(bytes, srid);
wkb.CopyTo(bytes.AsSpan().Slice(4));
return new MySqlGeometry(bytes);
}
/// <summary>
/// Constructs a <see cref="MySqlGeometry"/> from MySQL's internal format.
/// </summary>
/// <param name="value">The raw bytes of MySQL's internal GEOMETRY format.</param>
/// <returns>A new <see cref="MySqlGeometry"/> containing the specified geometry.</returns>
/// <remarks>See <a href="https://dev.mysql.com/doc/refman/8.0/en/gis-data-formats.html#gis-internal-format">Internal Geometry Storage Format</a>.</remarks>
public static MySqlGeometry FromMySql(ReadOnlySpan<byte> value) => new MySqlGeometry(value.ToArray());
/// <summary>
/// The Spatial Reference System ID of this geometry.
/// </summary>
public int SRID => BinaryPrimitives.ReadInt32LittleEndian(m_bytes);
/// <summary>
/// The Well-known Binary serialization of this geometry.
/// </summary>
public ReadOnlySpan<byte> WKB => Value.Slice(4);
/// <summary>
/// The internal MySQL form of this geometry.
/// </summary>
public ReadOnlySpan<byte> Value => m_bytes;
internal MySqlGeometry(byte[] bytes) => m_bytes = bytes;
readonly byte[] m_bytes;
}
}
| mit | C# |
822d1045fbbd02e654f40d05760b41fe31079c29 | Insert new files, Alura, C# e seus Fundamentos, Aula 3 | fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs | alura/c-sharp/CaixaEletronico.cs | alura/c-sharp/CaixaEletronico.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CaixaEletronico
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double saldo = 100.0;
double valor = 10.0;
bool podeSacar = (valor <= saldo) && (valor >= 0);
if(podeSacar)
{
saldo = saldo - valor;
MessageBox.Show("Saque realizado com sucesso");
}
else
{
MessageBox.Show("Saldo insuficiente");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CaixaEletronico
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int numeroDaConta;
numeroDaConta = 1;
double saldo = 100.0;
double valor = 10.0;
double saldoAposSaque = saldo - valor;
MessageBox.Show("O saldo atual é: " + saldoAposSaque);
}
}
}
| mit | C# |
ad6d90c6085cc3805db5422381973acafc8bd5a3 | Check InputStream on when seekable. | ianbattersby/Simple.Http,markrendle/Simple.Web,ianbattersby/Simple.Http,markrendle/Simple.Web,markrendle/Simple.Web,ianbattersby/Simple.Http | src/Simple.Web/Behaviors/Implementations/SetInput.cs | src/Simple.Web/Behaviors/Implementations/SetInput.cs | namespace Simple.Web.Behaviors.Implementations
{
using MediaTypeHandling;
using Behaviors;
using Http;
/// <summary>
/// This type supports the framework directly and should not be used from your code.
/// </summary>
public static class SetInput
{
/// <summary>
/// This method supports the framework directly and should not be used from your code
/// </summary>
/// <typeparam name="T">The input model type.</typeparam>
/// <param name="handler">The handler.</param>
/// <param name="context">The context.</param>
public static void Impl<T>(IInput<T> handler, IContext context)
{
if (context.Request.InputStream.CanSeek && context.Request.InputStream.Length == 0)
{
return;
}
var mediaTypeHandlerTable = new MediaTypeHandlerTable();
var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType());
handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T));
}
}
}
| namespace Simple.Web.Behaviors.Implementations
{
using MediaTypeHandling;
using Behaviors;
using Http;
/// <summary>
/// This type supports the framework directly and should not be used from your code.
/// </summary>
public static class SetInput
{
/// <summary>
/// This method supports the framework directly and should not be used from your code
/// </summary>
/// <typeparam name="T">The input model type.</typeparam>
/// <param name="handler">The handler.</param>
/// <param name="context">The context.</param>
public static void Impl<T>(IInput<T> handler, IContext context)
{
if (context.Request.InputStream.Length == 0) return;
var mediaTypeHandlerTable = new MediaTypeHandlerTable();
var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType());
handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T));
}
}
}
| mit | C# |
d67251ba8d47456ade1073ff1c59f35e37dbd184 | Fix bug with require token field in register page | RenetConsulting/angularcore.net,RenetConsulting/angularcore.net,RenetConsulting/angularcore.net,RenetConsulting/angularcore.net | Business/Application.Business/Models/ResetPasswordFromMailModel.cs | Business/Application.Business/Models/ResetPasswordFromMailModel.cs | namespace Application.Business.Models
{
using System.ComponentModel.DataAnnotations;
public class ResetPasswordFromMailModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Token")]
public string Token { get; set; }
}
}
| namespace Application.Business.Models
{
using System.ComponentModel.DataAnnotations;
public class ResetPasswordFromMailModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Token")]
public string Token { get; set; }
}
}
| mit | C# |
9161c5992954d5538054bc73cd5dd8bcc7e415cc | Solve day 16 part 2 | martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode | tests/AdventOfCode.Tests/Puzzles/Y2016/Day16Tests.cs | tests/AdventOfCode.Tests/Puzzles/Y2016/Day16Tests.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Day16"/> class. This class cannot be inherited.
/// </summary>
public static class Day16Tests
{
[Theory]
[InlineData("110010110100", 12, "100")]
[InlineData("10000", 20, "01100")]
public static void Y2016_Day16_GetDiskChecksum_Returns_Correct_Solution(string initial, int size, string expected)
{
// Act
string actual = Day16.GetDiskChecksum(initial, size);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("272", "10010110010011110")]
[InlineData("35651584", "01101011101100011")]
public static void Y2016_Day16_Solve_Returns_Correct_Solution(string size, string expected)
{
// Arrange
string[] args = new[] { "10010000000110000", size };
// Act
var puzzle = PuzzleTestHelpers.SolvePuzzle<Day16>(args);
// Assert
Assert.Equal(expected, puzzle.Checksum);
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Day16"/> class. This class cannot be inherited.
/// </summary>
public static class Day16Tests
{
[Theory]
[InlineData("110010110100", 12, "100")]
[InlineData("10000", 20, "01100")]
public static void Y2016_Day16_GetDiskChecksum_Returns_Correct_Solution(string initial, int size, string expected)
{
// Act
string actual = Day16.GetDiskChecksum(initial, size);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public static void Y2016_Day16_Solve_Returns_Correct_Solution()
{
// Arrange
string[] args = new[] { "10010000000110000", "272" };
// Act
var puzzle = PuzzleTestHelpers.SolvePuzzle<Day16>(args);
// Assert
Assert.Equal("10010110010011110", puzzle.Checksum);
}
}
}
| apache-2.0 | C# |
45a0682aead329042f6cf3e1cceada9c068ee347 | Fix rename | nigel-sampson/talks,nigel-sampson/talks | Ignite-2015/Hubb.Core/ViewModels/NoFodyLoginViewModel.cs | Ignite-2015/Hubb.Core/ViewModels/NoFodyLoginViewModel.cs | using System;
using System.Threading.Tasks;
using Caliburn.Micro;
using Hubb.Core.Services;
namespace Hubb.Core.ViewModels
{
public class NoFodyLoginViewModel : Screen
{
private readonly IAppNavigationService navigation;
private readonly IAuthenticationService authentication;
private string username;
private string password;
private string message;
public NoFodyLoginViewModel(IAppNavigationService navigation, IAuthenticationService authentication)
{
this.navigation = navigation;
this.authentication = authentication;
}
public string Username
{
get { return username; }
set
{
username = value;
NotifyOfPropertyChange();
NotifyOfPropertyChange(() => CanLogin);
}
}
public string Password
{
get { return password; }
set
{
password = value;
NotifyOfPropertyChange(() => Username);
NotifyOfPropertyChange(() => Password);
}
}
public bool CanLogin
{
get { return !String.IsNullOrWhiteSpace(Username) && !String.IsNullOrWhiteSpace(Password); }
}
public string Message
{
get { return message; }
set
{
message = value;
NotifyOfPropertyChange(nameof(Message));
}
}
public async Task Login()
{
var valid = await authentication.AreCredentialsValidAsync(Username, Password);
if (!valid)
{
Message = "Could not log you in to GitHub.";
return;
}
navigation.ToRepositorySearch();
}
}
}
| using System;
using System.Threading.Tasks;
using Caliburn.Micro;
using Hubb.Core.Services;
namespace Hubb.Core.ViewModels
{
public class FodyLoginViewModel : Screen
{
private readonly IAppNavigationService navigation;
private readonly IAuthenticationService authentication;
private string username;
private string password;
private string message;
public FodyLoginViewModel(IAppNavigationService navigation, IAuthenticationService authentication)
{
this.navigation = navigation;
this.authentication = authentication;
}
public string Username
{
get { return username; }
set
{
username = value;
NotifyOfPropertyChange();
NotifyOfPropertyChange(() => CanLogin);
}
}
public string Password
{
get { return password; }
set
{
password = value;
NotifyOfPropertyChange(() => Username);
NotifyOfPropertyChange(() => Password);
}
}
public bool CanLogin
{
get { return !String.IsNullOrWhiteSpace(Username) && !String.IsNullOrWhiteSpace(Password); }
}
public string Message
{
get { return message; }
set
{
message = value;
NotifyOfPropertyChange(nameof(Message));
}
}
public async Task Login()
{
var valid = await authentication.AreCredentialsValidAsync(Username, Password);
if (!valid)
{
Message = "Could not log you in to GitHub.";
return;
}
navigation.ToRepositorySearch();
}
}
}
| mit | C# |
9ea44ecdd977fe4ab255e237938a426a9c42e206 | add url option for PostToServiceOptions | linpiero/Serenity,WasimAhmad/Serenity,linpiero/Serenity,linpiero/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,linpiero/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,TukekeSoft/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,linpiero/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,volkanceylan/Serenity,dfaruque/Serenity | Serenity.Script.Imports/Services/PostToServiceOptions.cs | Serenity.Script.Imports/Services/PostToServiceOptions.cs | using System;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;
using System.Collections.Generic;
namespace Serenity
{
/// <summary>
/// Options for the Q.Externals.PostToService function
/// </summary>
[Imported, Serializable]
public class PostToServiceOptions
{
/// <summary>
/// Gets or sets service URL
/// </summary>
public string Service { get; set; }
/// <summary>
/// Gets or sets service URL
/// </summary>
public string Url { get; set; }
/// <summary>
/// Gets or sets target
/// </summary>
public string Target { get; set; }
/// <summary>
/// Gets or sets the request object
/// </summary>
public Object Request { get; set; }
}
}
| using System;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;
using System.Collections.Generic;
namespace Serenity
{
/// <summary>
/// Options for the Q.Externals.PostToService function
/// </summary>
[Imported, Serializable]
public class PostToServiceOptions
{
/// <summary>
/// Gets or sets service URL
/// </summary>
public string Service { get; set; }
/// <summary>
/// Gets or sets target
/// </summary>
public string Target { get; set; }
/// <summary>
/// Gets or sets the request object
/// </summary>
public Object Request { get; set; }
}
}
| mit | C# |
512536f5fe3465b329c1ccb6f7a2a7e23d8d6a65 | Fix unconditional null in `Equals` implementation | ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu | osu.Game/Online/Chat/Message.cs | osu.Game/Online/Chat/Message.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.Chat
{
public class Message : IComparable<Message>, IEquatable<Message>
{
[JsonProperty(@"message_id")]
public readonly long? Id;
[JsonProperty(@"channel_id")]
public long ChannelId;
[JsonProperty(@"is_action")]
public bool IsAction;
[JsonProperty(@"timestamp")]
public DateTimeOffset Timestamp;
[JsonProperty(@"content")]
public string Content;
[JsonProperty(@"sender")]
public APIUser Sender;
[JsonConstructor]
public Message()
{
}
/// <summary>
/// The text that is displayed in chat.
/// </summary>
public string DisplayContent { get; set; }
/// <summary>
/// The links found in this message.
/// </summary>
/// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks>
public List<Link> Links;
public Message(long? id)
{
Id = id;
}
public int CompareTo(Message other)
{
if (!Id.HasValue)
return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp);
if (!other.Id.HasValue)
return -1;
return Id.Value.CompareTo(other.Id.Value);
}
public virtual bool Equals(Message other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Id.HasValue && Id == other.Id;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public override int GetHashCode() => Id.GetHashCode();
public override string ToString() => $"[{ChannelId}] ({Id}) {Sender}: {Content}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.Chat
{
public class Message : IComparable<Message>, IEquatable<Message>
{
[JsonProperty(@"message_id")]
public readonly long? Id;
[JsonProperty(@"channel_id")]
public long ChannelId;
[JsonProperty(@"is_action")]
public bool IsAction;
[JsonProperty(@"timestamp")]
public DateTimeOffset Timestamp;
[JsonProperty(@"content")]
public string Content;
[JsonProperty(@"sender")]
public APIUser Sender;
[JsonConstructor]
public Message()
{
}
/// <summary>
/// The text that is displayed in chat.
/// </summary>
public string DisplayContent { get; set; }
/// <summary>
/// The links found in this message.
/// </summary>
/// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks>
public List<Link> Links;
public Message(long? id)
{
Id = id;
}
public int CompareTo(Message other)
{
if (!Id.HasValue)
return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp);
if (!other.Id.HasValue)
return -1;
return Id.Value.CompareTo(other.Id.Value);
}
public virtual bool Equals(Message other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Id.HasValue && Id == other?.Id;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public override int GetHashCode() => Id.GetHashCode();
public override string ToString() => $"[{ChannelId}] ({Id}) {Sender}: {Content}";
}
}
| mit | C# |
3c1a4b89ff9cc61e45755ba9a9596b9345bdd6eb | test cases | jefking/King.Azure.Imaging,jefking/King.Azure.Imaging,jefking/King.Azure.Imaging | King.Azure.Imaging.Unit.Test/ImageTaskFactoryTests.cs | King.Azure.Imaging.Unit.Test/ImageTaskFactoryTests.cs | namespace King.Azure.Imaging.Unit.Test
{
using King.Service;
using NSubstitute;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[TestFixture]
public class ImageTaskFactoryTests
{
[Test]
public void Constructor()
{
new ImageTaskFactory(Guid.NewGuid().ToString());
}
[Test]
public void IsITaskFactory()
{
Assert.IsNotNull(new ImageTaskFactory(Guid.NewGuid().ToString()) as ITaskFactory<object>);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ConstructorConnectionStringNull()
{
new ImageTaskFactory(null);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ConstructorStorageElementsNull()
{
var versions = Substitute.For<IVersions>();
new ImageTaskFactory(Guid.NewGuid().ToString(), null, versions);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ConstructorVersionsNull()
{
var elements = Substitute.For<IStorageElements>();
new ImageTaskFactory(Guid.NewGuid().ToString(), elements, null);
}
}
} | namespace King.Azure.Imaging.Unit.Test
{
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[TestFixture]
public class ImageTaskFactoryTests
{
}
}
| mit | C# |
9eda2f2df126f28079b05e9c87955fb08dd63364 | Remove box surrounding close button | ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu | osu.Game/Overlays/Chat/ChannelList/ChannelListItemCloseButton.cs | osu.Game/Overlays/Chat/ChannelList/ChannelListItemCloseButton.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Chat.ChannelList
{
public class ChannelListItemCloseButton : OsuClickableContainer
{
private SpriteIcon icon = null!;
private Color4 normalColour;
private Color4 hoveredColour;
[BackgroundDependencyLoader]
private void load(OsuColour osuColour)
{
normalColour = osuColour.Red2;
hoveredColour = Color4.White;
Alpha = 0f;
Size = new Vector2(20);
Add(icon = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(0.75f),
Icon = FontAwesome.Solid.TimesCircle,
RelativeSizeAxes = Axes.Both,
Colour = normalColour,
});
}
// Transforms matching OsuAnimatedButton
protected override bool OnHover(HoverEvent e)
{
icon.FadeColour(hoveredColour, 300, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
icon.FadeColour(normalColour, 300, Easing.OutQuint);
base.OnHoverLost(e);
}
protected override bool OnMouseDown(MouseDownEvent e)
{
icon.ScaleTo(0.75f, 2000, Easing.OutQuint);
return base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseUpEvent e)
{
icon.ScaleTo(1, 1000, Easing.OutElastic);
base.OnMouseUp(e);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Overlays.Chat.ChannelList
{
public class ChannelListItemCloseButton : OsuAnimatedButton
{
[BackgroundDependencyLoader]
private void load(OsuColour osuColour)
{
Alpha = 0f;
Size = new Vector2(20);
Add(new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(0.75f),
Icon = FontAwesome.Solid.TimesCircle,
RelativeSizeAxes = Axes.Both,
Colour = osuColour.Red1,
});
}
}
}
| mit | C# |
d7b93012739c363ee42bddee59b0a4fc21015c3f | Update OptionAttribute.cs | primo-ppcg/BF-Crunch | src/argparse/OptionAttribute.cs | src/argparse/OptionAttribute.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using ppcg.math;
using ppcg.text;
namespace ppcg.argparse {
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class OptionAttribute : Attribute {
public string Name { get; set; }
public char ShortName { get; set; }
public string Placeholder { get; set; }
public bool Required { get; set; }
public string HelpText { get; set; }
public string ToString(PropertyInfo prop) {
StringBuilder sb = new StringBuilder();
string usage = string.Format("--{0}", Name);
if(MyMath.IsNumeric(prop.PropertyType)) {
usage = string.Format("{0}={1}", usage, Placeholder ?? "#");
} else if(prop.PropertyType != typeof(bool)) {
usage = string.Format("{0}={1}", usage, Placeholder ?? "value");
}
if(ShortName != default(char)) {
usage = string.Format("-{0}, {1}", ShortName, usage);
}
sb.Append(string.Format(" {0,-16} ", usage));
if(usage.Length > 16) {
sb.Append(Environment.NewLine);
sb.Append(' ', 20);
}
string helptext = HelpText;
DefaultValueAttribute dvattr = (DefaultValueAttribute)prop.GetCustomAttributes(typeof(DefaultValueAttribute), true).FirstOrDefault();
if(dvattr is DefaultValueAttribute) {
helptext = string.Format("{0} Default = {1}", helptext, dvattr.Value ?? "(empty)");
}
sb.Append(string.Join(Environment.NewLine + new string(' ', 20), helptext.WordWrap(Console.WindowWidth - 20)));
return sb.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using ppcg.math;
using ppcg.text;
namespace ppcg.argparse {
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class OptionAttribute : Attribute {
public string Name { get; set; }
public char ShortName { get; set; }
public string Placeholder { get; set; }
public bool Required { get; set; }
public string HelpText { get; set; }
public string ToString(PropertyInfo prop) {
StringBuilder sb = new StringBuilder();
string usage = string.Format("--{0}", Name);
if(MyMath.IsNumeric(prop.PropertyType)) {
usage = string.Format("{0}={1}", usage, Placeholder ?? "#");
} else if(prop.PropertyType != typeof(bool)) {
usage = string.Format("{0}={1}", usage, Placeholder ?? "value");
}
if(ShortName != default(char)) {
usage = string.Format("-{0}, {1}", ShortName, usage);
}
sb.Append(string.Format(" {0,-16} ", usage));
if(usage.Length > 16) {
sb.Append(Environment.NewLine);
sb.Append(' ', 20);
}
string helptext = HelpText;
DefaultValueAttribute dvattr = (DefaultValueAttribute)prop.GetCustomAttributes(typeof(DefaultValueAttribute), true).FirstOrDefault();
if(dvattr is DefaultValueAttribute) {
helptext = string.Format("{0} Default = {1}", helptext, dvattr.Value);
}
sb.Append(string.Join(Environment.NewLine + new string(' ', 20), helptext.WordWrap(Console.WindowWidth - 20)));
return sb.ToString();
}
}
}
| mit | C# |
4587928832abf3dc70a546e503b47a5a856ae617 | Fix max X position when moving paddle with keyboard | ZombieUnicornStudio/Arkapongout | Assets/Scripts/Paddle.cs | Assets/Scripts/Paddle.cs | using UnityEngine;
public class Paddle : MonoBehaviour {
public int lifes = 3;
public AudioClip powerUpSound;
[Range(0f, 40f)]
public float speed = 20;
public float minXpos = -15;
public float maxXpos = 15;
AudioSource audioSrc;
void Awake () {
audioSrc = GetComponent<AudioSource>();
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "PowerUp") {
Debug.Log("[Paddle] PowerUp Catched");
ApplyPowerUp(other.gameObject);
}
}
void OnMove (Vector3 newPos) {
newPos = new Vector3(Mathf.Clamp(newPos.x, minXpos, maxXpos), transform.position.y, transform.position.z);
if (speed == 0) {
transform.Translate(newPos);
} else {
float distance = Vector3.Distance(transform.position, newPos);
float step = Time.deltaTime * speed * distance;
transform.position = Vector3.MoveTowards(transform.position, newPos, step);
}
}
void ApplyPowerUp (GameObject powerUp) {
PowerUp.Type type = powerUp.GetComponent<PowerUp>().type;
if (type == PowerUp.Type.Enlarge) {
Vector3 gain = new Vector3(.2f, 0, 0);
transform.localScale += gain;
audioSrc.pitch = Random.Range(.9f, 1.1f);
audioSrc.PlayOneShot(powerUpSound);
ScoreController.instance.Add(100);
}
Destroy(powerUp);
}
void OnDrawGizmosSelected () {
Vector3 initialPos = new Vector3(0, transform.position.y, transform.position.z);
Gizmos.color = Color.yellow;
Gizmos.DrawLine(initialPos, initialPos + new Vector3(maxXpos, 0, 0));
Gizmos.DrawLine(initialPos, initialPos + new Vector3(minXpos, 0, 0));
}
}
| using UnityEngine;
public class Paddle : MonoBehaviour {
public int lifes = 3;
public AudioClip powerUpSound;
[Range(0f, 40f)]
public float speed = 20;
public float minXpos = -20;
public float maxXpos = 20;
AudioSource audioSrc;
void Awake () {
audioSrc = GetComponent<AudioSource>();
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "PowerUp") {
Debug.Log("[Paddle] PowerUp Catched");
ApplyPowerUp(other.gameObject);
}
}
void OnMove (Vector3 newPos) {
newPos = new Vector3(Mathf.Clamp(newPos.x, minXpos, maxXpos), transform.position.y, transform.position.z);
if (speed == 0) {
transform.Translate(newPos);
} else {
float distance = Vector3.Distance(transform.position, newPos);
float step = Time.deltaTime * speed * distance;
transform.position = Vector3.MoveTowards(transform.position, newPos, step);
}
}
void ApplyPowerUp (GameObject powerUp) {
PowerUp.Type type = powerUp.GetComponent<PowerUp>().type;
if (type == PowerUp.Type.Enlarge) {
Vector3 gain = new Vector3(.2f, 0, 0);
transform.localScale += gain;
audioSrc.pitch = Random.Range(.9f, 1.1f);
audioSrc.PlayOneShot(powerUpSound);
ScoreController.instance.Add(100);
}
Destroy(powerUp);
}
}
| mit | C# |
530563b73256f40a3f605d40c199266967448e5e | Implement IEquatable for Date | markaschell/SoftwareThresher | code/SoftwareThresher/SoftwareThresher/Utilities/Date.cs | code/SoftwareThresher/SoftwareThresher/Utilities/Date.cs | using System;
namespace SoftwareThresher.Utilities {
public class Date : IEquatable<Date> {
readonly DateTime date;
public static Date NullDate => new Date(DateTime.MinValue);
public Date(DateTime dateTime) {
date = dateTime.Date;
}
public double DaysOld => Math.Floor((DateTime.Today - date).TotalDays);
public bool Equals(Date other) {
if (other == null) {
return false;
}
var otherDate = other.date;
return date.Year == otherDate.Year && date.Month == otherDate.Month && date.Day == otherDate.Day;
}
public override bool Equals(object obj) {
if (!(obj is Date)) {
return false;
}
return Equals((Date)obj);
}
public override int GetHashCode() {
return date.Year.GetHashCode() ^ date.Month.GetHashCode() ^ date.Day.GetHashCode();
}
public static bool operator ==(Date date1, Date date2) {
if ((object)date1 == null || (object)date2 == null) {
return Equals(date1, date2);
}
return date1.Equals(date2);
}
public static bool operator !=(Date date1, Date date2) {
return !(date1 == date2);
}
public override string ToString() {
return $"{date:MM/dd/yyyy}";
}
}
}
| using System;
namespace SoftwareThresher.Utilities {
public class Date
{
readonly DateTime date;
public static Date NullDate => new Date(DateTime.MinValue);
public Date(DateTime dateTime)
{
date = dateTime.Date;
}
public double DaysOld => Math.Floor((DateTime.Today - date).TotalDays);
// TODO - ONLINE implement Equals
public override string ToString() {
return $"{date:MM/dd/yyyy}";
}
}
}
| mit | C# |
b9ee2272e1a86835b253e55d1af0e7e0ddd1925f | bump file version too | FacturAPI/facturapi-net | facturapi-net/Properties/AssemblyInfo.cs | facturapi-net/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Facturapi")]
[assembly: AssemblyDescription("Crea Facturas Electrónicas válidas en México lo más fácil posible (CFDI)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Facturapi")]
[assembly: AssemblyProduct("Facturapi")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("Facturapi")]
[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("a91d3cf3-1051-41f4-833e-c52ee8fbce20")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1.*")]
[assembly: AssemblyFileVersion("0.1.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Facturapi")]
[assembly: AssemblyDescription("Crea Facturas Electrónicas válidas en México lo más fácil posible (CFDI)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Facturapi")]
[assembly: AssemblyProduct("Facturapi")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("Facturapi")]
[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("a91d3cf3-1051-41f4-833e-c52ee8fbce20")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1.*")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| mit | C# |
ba53241df3ce7d89c5c8e3037c1b99de7602d6ed | Update Get.cs | ovation22/PragmaticTDD,ovation22/PragmaticTDD | Pragmatic.TDD.Services.Tests/HorseServiceTests/Get.cs | Pragmatic.TDD.Services.Tests/HorseServiceTests/Get.cs | using Autofac;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pragmatic.TDD.Services.Interfaces;
using Pragmatic.TDD.Services.Tests.Factories;
namespace Pragmatic.TDD.Services.Tests.HorseServiceTests
{
[TestClass]
public class Get : TestBase
{
private IHorseService _horseService;
[TestInitialize]
public void Setup()
{
HorseFactory.Create(Context).WithColor();
_horseService = Container.Resolve<IHorseService>();
}
[TestMethod]
public void ItExists()
{
// Arrange
// Act
// Assert
Assert.IsNotNull(_horseService.Get(1));
}
[TestMethod]
public void ItReturnsNullForUserThatDoesNotExist()
{
// Arrange
// Act
var horse = _horseService.Get(-1);
// Assert
Assert.IsNull(horse);
}
[TestMethod]
public void ItMapsProperties()
{
// Arrange
// Act
var horse = _horseService.Get(1);
// Assert
Assert.AreEqual(1, horse.Id);
Assert.AreEqual("Man o' War", horse.Name);
Assert.AreEqual("Chestnut", horse.Color);
}
}
}
| using Autofac;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pragmatic.TDD.Services.Interfaces;
using Pragmatic.TDD.Services.Tests.Factories;
namespace Pragmatic.TDD.Services.Tests.HorseServiceTests
{
[TestClass]
public class Get : TestBase
{
private IHorseService _horseService;
[TestInitialize]
public void Setup()
{
HorseFactory.Create(Context).WithColor();
_horseService = Container.Resolve<IHorseService>();
}
[TestMethod]
public void ItExists()
{
// Arrange
// Act
// Assert
Assert.IsNotNull(_horseService.Get(1));
}
[TestMethod]
public void ItReturnsNullForUserThatDoesNotExist()
{
// Arrange
// Act
var horse = _horseService.Get(-1);
// Assert
Assert.IsNull(horse);
}
[TestMethod]
public void ItMapsProperties()
{
// Arrange
// Act
var horse = _horseService.Get(1);
// Assert
Assert.AreEqual(horse.Id, 1);
Assert.AreEqual(horse.Name, "Man o' War");
Assert.AreEqual(horse.Color, "Chestnut");
}
}
}
| mit | C# |
ef6533c9987368f09048159449d7ababbdd05226 | Mark as sealed | DotNetKit/DotNetKit.Wpf.Printing | DotNetKit.Wpf.Printing.Demo/Printing/ScaleSelector.cs | DotNetKit.Wpf.Printing.Demo/Printing/ScaleSelector.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Mvvm;
namespace DotNetKit.Wpf.Printing.Demo.Printing
{
public sealed class ScaleSelector
: BindableBase
{
double scale = 1;
public double Scale
{
get { return scale; }
set { SetProperty(ref scale, value); }
}
#region Zoom
double ScaleFactor(int delta)
{
var d = Math.Sign(delta);
var tan = Math.Tan(Math.PI / 2);
var x = 0.1 / (2.0 * 1.1 * tan);
return 1 / (1 - (x * d) * tan * 2);
}
public void Zoom(int delta)
{
Scale *= ScaleFactor(delta);
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Mvvm;
namespace DotNetKit.Wpf.Printing.Demo.Printing
{
public class ScaleSelector
: BindableBase
{
double scale = 1;
public double Scale
{
get { return scale; }
set { SetProperty(ref scale, value); }
}
#region Zoom
double ScaleFactor(int delta)
{
var d = Math.Sign(delta);
var tan = Math.Tan(Math.PI / 2);
var x = 0.1 / (2.0 * 1.1 * tan);
return 1 / (1 - (x * d) * tan * 2);
}
public void Zoom(int delta)
{
Scale *= ScaleFactor(delta);
}
#endregion
}
}
| mit | C# |
9d4d6aaf8479ebf494b38a58976bc7c9da85764f | Change Any to Count as conversion might not always succeed | baks/code-cracker,giggio/code-cracker,adraut/code-cracker,carloscds/code-cracker,ElemarJR/code-cracker,thomaslevesque/code-cracker,AlbertoMonteiro/code-cracker,code-cracker/code-cracker,kindermannhubert/code-cracker,GuilhermeSa/code-cracker,code-cracker/code-cracker,carloscds/code-cracker,thorgeirk11/code-cracker,jhancock93/code-cracker,eriawan/code-cracker,andrecarlucci/code-cracker,jwooley/code-cracker,robsonalves/code-cracker,akamud/code-cracker | src/CSharp/CodeCracker/Refactoring/ParameterRefactoryAnalyzer.cs | src/CSharp/CodeCracker/Refactoring/ParameterRefactoryAnalyzer.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Refactoring
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterRefactoryAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "You should use a class";
internal const string MessageFormat = "When the method has more than three parameters, use new class.";
internal const string Category = SupportedCategories.Refactoring;
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.ParameterRefactory.ToDiagnosticId(),
Title,
MessageFormat,
Category,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.ParameterRefactory));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration);
private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (context.IsGenerated()) return;
var method = (MethodDeclarationSyntax)context.Node;
if (method.Modifiers.Any(SyntaxKind.ExternKeyword)) return;
var contentParameter = method.ParameterList;
if (!contentParameter.Parameters.Any() || contentParameter.Parameters.Count <= 3) return;
if (contentParameter.Parameters.SelectMany(parameter => parameter.Modifiers)
.Any(modifier => modifier.IsKind(SyntaxKind.RefKeyword) ||
modifier.IsKind(SyntaxKind.OutKeyword) ||
modifier.IsKind(SyntaxKind.ThisKeyword) ||
modifier.IsKind(SyntaxKind.ParamsKeyword))) return;
if (method.Body?.ChildNodes().Count() > 0) return;
var diagnostic = Diagnostic.Create(Rule, contentParameter.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
} | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Refactoring
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterRefactoryAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "You should use a class";
internal const string MessageFormat = "When the method has more than three parameters, use new class.";
internal const string Category = SupportedCategories.Refactoring;
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.ParameterRefactory.ToDiagnosticId(),
Title,
MessageFormat,
Category,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.ParameterRefactory));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration);
private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (context.IsGenerated()) return;
var method = (MethodDeclarationSyntax)context.Node;
if (method.Modifiers.Any(SyntaxKind.ExternKeyword)) return;
var contentParameter = method.ParameterList;
if (!contentParameter.Parameters.Any() || contentParameter.Parameters.Count <= 3) return;
if (contentParameter.Parameters.SelectMany(parameter => parameter.Modifiers)
.Any(modifier => modifier.IsKind(SyntaxKind.RefKeyword) ||
modifier.IsKind(SyntaxKind.OutKeyword) ||
modifier.IsKind(SyntaxKind.ThisKeyword) ||
modifier.IsKind(SyntaxKind.ParamsKeyword))) return;
if ((bool) method.Body?.ChildNodes().Any()) return;
var diagnostic = Diagnostic.Create(Rule, contentParameter.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
} | apache-2.0 | C# |
f511c89dcc60cce74a2d26c7ea099169bdb1367e | Format whitespace | milkshakesoftware/PreMailer.Net | PreMailer.Net/PreMailer.Net.Tests/CssAttributeTests.cs | PreMailer.Net/PreMailer.Net.Tests/CssAttributeTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PreMailer.Net.Tests
{
[TestClass]
public class CssAttributeTests
{
[TestMethod]
public void StandandUnimportantRule_ReturnsAttribute()
{
var attribute = CssAttribute.FromRule("color: red");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("red", attribute.Value);
}
[TestMethod]
public void MixedCaseRuleValue_RetainsCasing()
{
var attribute = CssAttribute.FromRule(" color: rED");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("rED", attribute.Value);
}
[TestMethod]
public void MixedCaseRule_RetainsCasing()
{
var attribute = CssAttribute.FromRule("Margin-bottom: 10px");
Assert.AreEqual("Margin-bottom", attribute.Style);
Assert.AreEqual("10px", attribute.Value);
}
[TestMethod]
public void ImportantRule_ReturnsImportantAttribute()
{
var attribute = CssAttribute.FromRule("color: red !important");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("red", attribute.Value);
Assert.IsTrue(attribute.Important);
}
[TestMethod]
public void ImportantRule_ReturnsValidCssWithoutWhitespaces()
{
var attribute = CssAttribute.FromRule("color:red!important");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("red", attribute.Value);
Assert.IsTrue(attribute.Important);
}
[TestMethod]
public void NonRule_ReturnsNull()
{
var attribute = CssAttribute.FromRule(" ");
Assert.IsNull(attribute);
}
[TestMethod]
public void FromRule_OnlySplitsTheRuleAtTheFirstColonToSupportUrls()
{
var attribute = CssAttribute.FromRule("background: url('http://my.web.site.com/Content/email/content.png') repeat-y");
Assert.AreEqual("url('http://my.web.site.com/Content/email/content.png') repeat-y", attribute.Value);
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PreMailer.Net.Tests
{
[TestClass]
public class CssAttributeTests
{
[TestMethod]
public void StandandUnimportantRule_ReturnsAttribute()
{
var attribute = CssAttribute.FromRule("color: red");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("red", attribute.Value);
}
[TestMethod]
public void MixedCaseRuleValue_RetainsCasing()
{
var attribute = CssAttribute.FromRule(" color: rED");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("rED", attribute.Value);
}
[TestMethod]
public void MixedCaseRule_RetainsCasing()
{
var attribute = CssAttribute.FromRule("Margin-bottom: 10px");
Assert.AreEqual("Margin-bottom", attribute.Style);
Assert.AreEqual("10px", attribute.Value);
}
[TestMethod]
public void ImportantRule_ReturnsImportantAttribute()
{
var attribute = CssAttribute.FromRule("color: red !important");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("red", attribute.Value);
Assert.IsTrue(attribute.Important);
}
[TestMethod]
public void ImportantRule_ReturnsValidCssWithoutWhitespaces()
{
var attribute = CssAttribute.FromRule("color:red!important");
Assert.AreEqual("color", attribute.Style);
Assert.AreEqual("red", attribute.Value);
Assert.IsTrue(attribute.Important);
}
[TestMethod]
public void NonRule_ReturnsNull()
{
var attribute = CssAttribute.FromRule(" ");
Assert.IsNull(attribute);
}
[TestMethod]
public void FromRule_OnlySplitsTheRuleAtTheFirstColonToSupportUrls()
{
var attribute = CssAttribute.FromRule("background: url('http://my.web.site.com/Content/email/content.png') repeat-y");
Assert.AreEqual("url('http://my.web.site.com/Content/email/content.png') repeat-y", attribute.Value);
}
}
} | mit | C# |
e7b0aadbcb4932770f3d6dffd6d83e9d3ec8dde3 | Add code task | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University.Division/Components/DivisionSettings.cs | R7.University.Division/Components/DivisionSettings.cs | //
// DivisionSettings.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2014-2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Modules;
using R7.DotNetNuke.Extensions.Modules;
namespace R7.University.Division.Components
{
/// <summary>
/// Provides strong typed access to settings used by module
/// </summary>
public class DivisionSettings : SettingsWrapper
{
public DivisionSettings ()
{
}
public DivisionSettings (IModuleControl module) : base (module)
{
}
public DivisionSettings (ModuleInfo module) : base (module)
{
}
#region Properties for settings
private int? divisionId;
/// <summary>
/// Division ID
/// </summary>
// TODO: Convert to Nullable<int>
public int DivisionID
{
get {
if (divisionId == null)
divisionId = ReadSetting<int> ("Division_DivisionID", Null.NullInteger);
return divisionId.Value;
}
set {
WriteModuleSetting<int> ("Division_DivisionID", value);
divisionId = value;
}
}
public bool ShowAddress
{
get { return ReadSetting ("Division_ShowAddress", false); }
set { WriteTabModuleSetting ("Division_ShowAddress", value); }
}
#endregion
}
}
| //
// DivisionSettings.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2014-2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Modules;
using R7.DotNetNuke.Extensions.Modules;
namespace R7.University.Division.Components
{
/// <summary>
/// Provides strong typed access to settings used by module
/// </summary>
public class DivisionSettings : SettingsWrapper
{
public DivisionSettings ()
{
}
public DivisionSettings (IModuleControl module) : base (module)
{
}
public DivisionSettings (ModuleInfo module) : base (module)
{
}
#region Properties for settings
private int? divisionId;
/// <summary>
/// Division ID
/// </summary>
public int DivisionID
{
get {
if (divisionId == null)
divisionId = ReadSetting<int> ("Division_DivisionID", Null.NullInteger);
return divisionId.Value;
}
set {
WriteModuleSetting<int> ("Division_DivisionID", value);
divisionId = value;
}
}
public bool ShowAddress
{
get { return ReadSetting ("Division_ShowAddress", false); }
set { WriteTabModuleSetting ("Division_ShowAddress", value); }
}
#endregion
}
}
| agpl-3.0 | C# |
90d0a6638bc6e696941eddb8064fe1ac97cd6649 | bump version to 5.2.2.13807 | HearthSim/HearthDb | HearthDb/Properties/AssemblyInfo.cs | HearthDb/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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// 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("5.2.2.13807")]
[assembly: AssemblyFileVersion("5.2.2.13807")]
| 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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// 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("5.2.0.13740")]
[assembly: AssemblyFileVersion("5.2.0.13740")]
| mit | C# |
c93cfc922939be6a2503154b65280257b0246d2b | fix tests | arsouza/Aritter,arsouza/Aritter,aritters/Ritter | tests/Application.Seedwork.Tests/Services/AppService_Constructor.cs | tests/Application.Seedwork.Tests/Services/AppService_Constructor.cs | using FluentAssertions;
using Xunit;
namespace Application.Seedwork.Tests.Services
{
public class AppService_Constructor
{
[Fact]
public void CreateAnInstanceOfAppService()
{
var appService = new TestAppService(null);
appService.Should().NotBeNull();
}
}
}
| using FluentAssertions;
namespace Application.Seedwork.Tests.Services
{
public class AppService_Constructor
{
public void CreateAnInstanceOfAppService()
{
var appService = new TestAppService(null);
appService.Should().NotBeNull();
}
}
}
| mit | C# |
66ebe2ee6679866d46b497a6b1318d8bc5cab5e3 | Change anchors in line with new ScrollingPlayfield implementation | smoogipoo/osu,NeoAdonis/osu,ppy/osu,ppy/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,UselessToucan/osu,smoogipooo/osu,ZLima12/osu,naoey/osu,DrabWeb/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,peppy/osu,Frontear/osuKyzer,UselessToucan/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,naoey/osu,EVAST9919/osu,2yangk23/osu,DrabWeb/osu,Nabile-Rahmani/osu,peppy/osu-new,peppy/osu,naoey/osu,johnneijzen/osu | osu.Game.Rulesets.Catch/Objects/Drawable/DrawableCatchHitObject.cs | osu.Game.Rulesets.Catch/Objects/Drawable/DrawableCatchHitObject.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
using OpenTK;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Catch.Objects.Drawable
{
public abstract class DrawableCatchHitObject<TObject> : DrawableCatchHitObject
where TObject : CatchHitObject
{
public new TObject HitObject;
protected DrawableCatchHitObject(TObject hitObject)
: base(hitObject)
{
HitObject = hitObject;
Scale = new Vector2(HitObject.Scale);
Anchor = Anchor.BottomLeft;
}
}
public abstract class DrawableCatchHitObject : DrawableHitObject<CatchHitObject>
{
protected DrawableCatchHitObject(CatchHitObject hitObject)
: base(hitObject)
{
RelativePositionAxes = Axes.X;
X = hitObject.X;
}
public Func<CatchHitObject, bool> CheckPosition;
protected override void CheckForJudgements(bool userTriggered, double timeOffset)
{
if (timeOffset > 0)
AddJudgement(new Judgement { Result = CheckPosition?.Invoke(HitObject) ?? false ? HitResult.Perfect : HitResult.Miss });
}
private const float preempt = 1000;
protected override void UpdateState(ArmedState state)
{
using (BeginAbsoluteSequence(HitObject.StartTime - preempt))
{
// animation
this.FadeIn(200);
}
switch (state)
{
case ArmedState.Miss:
using (BeginAbsoluteSequence(HitObject.StartTime, true))
this.FadeOut(250).RotateTo(Rotation * 2, 250, Easing.Out);
break;
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
using OpenTK;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Catch.Objects.Drawable
{
public abstract class DrawableCatchHitObject<TObject> : DrawableCatchHitObject
where TObject : CatchHitObject
{
public new TObject HitObject;
protected DrawableCatchHitObject(TObject hitObject)
: base(hitObject)
{
HitObject = hitObject;
Scale = new Vector2(HitObject.Scale);
}
}
public abstract class DrawableCatchHitObject : DrawableHitObject<CatchHitObject>
{
protected DrawableCatchHitObject(CatchHitObject hitObject)
: base(hitObject)
{
RelativePositionAxes = Axes.X;
X = hitObject.X;
}
public Func<CatchHitObject, bool> CheckPosition;
protected override void CheckForJudgements(bool userTriggered, double timeOffset)
{
if (timeOffset > 0)
AddJudgement(new Judgement { Result = CheckPosition?.Invoke(HitObject) ?? false ? HitResult.Perfect : HitResult.Miss });
}
private const float preempt = 1000;
protected override void UpdateState(ArmedState state)
{
using (BeginAbsoluteSequence(HitObject.StartTime - preempt))
{
// animation
this.FadeIn(200);
}
switch (state)
{
case ArmedState.Miss:
using (BeginAbsoluteSequence(HitObject.StartTime, true))
this.FadeOut(250).RotateTo(Rotation * 2, 250, Easing.Out);
break;
}
}
}
}
| mit | C# |
b1b305c150aeb2bb5c6df0a7d62a9f72e5fcba3e | add method AddToc | peppy/osu,peppy/osu-new,peppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu | osu.Game/Overlays/Wiki/WikiSidebar.cs | osu.Game/Overlays/Wiki/WikiSidebar.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Overlays.Wiki
{
public class WikiSidebar : OverlaySidebar
{
private FillFlowContainer tableOfContents;
protected override Drawable CreateContent() => new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new OsuSpriteText
{
Text = "CONTENTS",
Font = OsuFont.GetFont(size: 12, weight: FontWeight.Bold),
},
tableOfContents = new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
}
},
};
public void AddToc(string title, MarkdownHeading heading, int level)
{
switch (level)
{
case 2:
tableOfContents.Add(new OsuSpriteText
{
Text = title,
Font = OsuFont.GetFont(size: 15),
});
break;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Overlays.Wiki
{
public class WikiSidebar : OverlaySidebar
{
private FillFlowContainer tableOfContents;
protected override Drawable CreateContent() => new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new OsuSpriteText
{
Text = "CONTENTS",
Font = OsuFont.GetFont(size: 12, weight: FontWeight.Bold),
},
tableOfContents = new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
}
},
};
}
}
| mit | C# |
ab3b257d9bc2225345751be07a90ec5825ecfadd | Update ExceptionContractResolver - add namespace, update to use var as standard | mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX | Modix.Services/Utilities/ExceptionContractResolver.cs | Modix.Services/Utilities/ExceptionContractResolver.cs | using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Modix.Services.Utilities
{
public class ExceptionContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MethodBase) && property.PropertyName == "TargetSite")
{
property.ShouldSerialize =
instance =>
{
return false;
};
}
return property;
}
}
} | using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class ExceptionContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MethodBase) && property.PropertyName == "TargetSite")
{
property.ShouldSerialize =
instance =>
{
return false;
};
}
return property;
}
} | mit | C# |
8b65c37a5807a7eeacf43c084314c5500011265e | Make sure Fiddler is turned off by default | Jericho/CakeMail.RestClient | Source/CakeMail.RestClient.IntegrationTests/Program.cs | Source/CakeMail.RestClient.IntegrationTests/Program.cs | using System;
namespace CakeMail.RestClient.IntegrationTests
{
public class Program
{
public static void Main()
{
Console.WriteLine("{0} Executing all CakeMail API methods ... {0}", new string('=', 10));
try
{
ExecuteAllMethods();
}
catch (Exception e)
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("An error has occured: {0}", (e.InnerException ?? e).Message);
}
finally
{
// Clear the keyboard buffer
while (Console.KeyAvailable)
{
Console.ReadKey();
}
Console.WriteLine("");
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
private static void ExecuteAllMethods()
{
// -----------------------------------------------------------------------------
// Do you want to proxy requests through Fiddler (useful for debugging)?
var useFiddler = false;
// -----------------------------------------------------------------------------
var proxy = useFiddler ? new WebProxy("http://localhost:8888") : null;
var apiKey = Environment.GetEnvironmentVariable("CAKEMAIL_APIKEY");
var userName = Environment.GetEnvironmentVariable("CAKEMAIL_USERNAME");
var password = Environment.GetEnvironmentVariable("CAKEMAIL_PASSWORD");
var overrideClientId = Environment.GetEnvironmentVariable("CAKEMAIL_OVERRIDECLIENTID");
var api = new CakeMailRestClient(apiKey, proxy);
var loginInfo = api.Users.LoginAsync(userName, password).Result;
var clientId = string.IsNullOrEmpty(overrideClientId) ? loginInfo.ClientId : long.Parse(overrideClientId);
var userKey = loginInfo.UserKey;
TimezonesTests.ExecuteAllMethods(api).Wait();
CountriesTests.ExecuteAllMethods(api).Wait();
ClientsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
UsersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
PermissionsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
CampaignsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
ListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TemplatesTests.ExecuteAllMethods(api, userKey, clientId).Wait();
SuppressionListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
RelaysTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TriggersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
MailingsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
}
}
}
| using System;
namespace CakeMail.RestClient.IntegrationTests
{
public class Program
{
public static void Main()
{
Console.WriteLine("{0} Executing all CakeMail API methods ... {0}", new string('=', 10));
try
{
ExecuteAllMethods();
}
catch (Exception e)
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("An error has occured: {0}", (e.InnerException ?? e).Message);
}
finally
{
// Clear the keyboard buffer
while (Console.KeyAvailable)
{
Console.ReadKey();
}
Console.WriteLine("");
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
private static void ExecuteAllMethods()
{
// -----------------------------------------------------------------------------
// Do you want to proxy requests through Fiddler (useful for debugging)?
var useFiddler = true;
// -----------------------------------------------------------------------------
var proxy = useFiddler ? new WebProxy("http://localhost:8888") : null;
var apiKey = Environment.GetEnvironmentVariable("CAKEMAIL_APIKEY");
var userName = Environment.GetEnvironmentVariable("CAKEMAIL_USERNAME");
var password = Environment.GetEnvironmentVariable("CAKEMAIL_PASSWORD");
var overrideClientId = Environment.GetEnvironmentVariable("CAKEMAIL_OVERRIDECLIENTID");
var api = new CakeMailRestClient(apiKey, proxy);
var loginInfo = api.Users.LoginAsync(userName, password).Result;
var clientId = string.IsNullOrEmpty(overrideClientId) ? loginInfo.ClientId : long.Parse(overrideClientId);
var userKey = loginInfo.UserKey;
TimezonesTests.ExecuteAllMethods(api).Wait();
CountriesTests.ExecuteAllMethods(api).Wait();
ClientsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
UsersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
PermissionsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
CampaignsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
ListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TemplatesTests.ExecuteAllMethods(api, userKey, clientId).Wait();
SuppressionListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
RelaysTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TriggersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
MailingsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
}
}
}
| mit | C# |
912909da785b0e1f4c234809aa39ea1abbf12073 | Update FluentEmailSmtpBuilderExtensions.cs | lukencode/FluentEmail,lukencode/FluentEmail | src/Senders/FluentEmail.Smtp/FluentEmailSmtpBuilderExtensions.cs | src/Senders/FluentEmail.Smtp/FluentEmailSmtpBuilderExtensions.cs | using FluentEmail.Core.Interfaces;
using FluentEmail.Smtp;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Mail;
namespace Microsoft.Extensions.DependencyInjection
{
public static class FluentEmailSmtpBuilderExtensions
{
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient)
{
builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(smtpClient)));
return builder;
}
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, new SmtpClient(host, port));
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder,
new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) });
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory)
{
builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory)));
return builder;
}
}
}
| using FluentEmail.Core.Interfaces;
using FluentEmail.Smtp;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Mail;
namespace Microsoft.Extensions.DependencyInjection
{
public static class FluentEmailSmtpBuilderExtensions
{
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient)
{
builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(smtpClient)));
return builder;
}
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, new SmtpClient(host, port));
public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory)
{
builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory)));
return builder;
}
}
}
| mit | C# |
02356030c87f2395f2c595c08bddff2a57ec9530 | fix merge mistake | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/Login/LoginViewModel.cs | WalletWasabi.Fluent/ViewModels/Login/LoginViewModel.cs | using System.Threading.Tasks;
using System.Windows.Input;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.ViewModels.Login.PasswordFinder;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Fluent.ViewModels.Wallets;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Fluent.ViewModels.Login
{
public partial class LoginViewModel : RoutableViewModel
{
[AutoNotify] private string _password;
[AutoNotify] private bool _isPasswordIncorrect;
[AutoNotify] private bool _isPasswordNeeded;
[AutoNotify] private string _walletName;
public LoginViewModel(WalletViewModelBase walletViewModelBase)
{
Title = "Login";
KeyManager = walletViewModelBase.Wallet.KeyManager;
IsPasswordNeeded = !KeyManager.IsWatchOnly;
_walletName = walletViewModelBase.WalletName;
_password = "";
var wallet = walletViewModelBase.Wallet;
NextCommand = ReactiveCommand.CreateFromTask(async () =>
{
IsPasswordIncorrect = await Task.Run(async () =>
{
if (!IsPasswordNeeded)
{
return false;
}
if (PasswordHelper.TryPassword(KeyManager, Password, out var compatibilityPasswordUsed))
{
if (compatibilityPasswordUsed is { })
{
await ShowErrorAsync(PasswordHelper.CompatibilityPasswordWarnMessage, "Compatibility password was used");
}
return false;
}
return true;
});
if (!IsPasswordIncorrect)
{
wallet.Login();
// TODO: navigate to the wallet welcome page
Navigate().To(walletViewModelBase, NavigationMode.Clear);
}
});
OkCommand = ReactiveCommand.Create(() =>
{
Password = "";
IsPasswordIncorrect = false;
});
ForgotPasswordCommand = ReactiveCommand.Create(() =>
Navigate(NavigationTarget.DialogScreen).To(new PasswordFinderIntroduceViewModel(wallet)));
EnableAutoBusyOn(NextCommand);
}
public ICommand OkCommand { get; }
public ICommand ForgotPasswordCommand { get; }
public KeyManager KeyManager { get; }
}
} | using System.Threading.Tasks;
using System.Windows.Input;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.ViewModels.Login.PasswordFinder;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Fluent.ViewModels.Wallets;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Fluent.ViewModels.Login
{
public partial class LoginViewModel : RoutableViewModel
{
[AutoNotify] private string _password;
[AutoNotify] private bool _isPasswordIncorrect;
[AutoNotify] private bool _isPasswordNeeded;
[AutoNotify] private string _walletName;
public LoginViewModel(WalletViewModelBase walletViewModelBase)
{
Title = "Login";
KeyManager = walletViewModelBase.Wallet.KeyManager;
IsPasswordNeeded = !KeyManager.IsWatchOnly;
_walletName = walletViewModelBase.WalletName;
_password = "";
var wallet = walletViewModelBase.Wallet;
NextCommand = ReactiveCommand.CreateFromTask(async () =>
{
var wallet = walletViewModelBase.Wallet;
IsPasswordIncorrect = await Task.Run(async () =>
{
if (!IsPasswordNeeded)
{
return false;
}
if (PasswordHelper.TryPassword(KeyManager, Password, out var compatibilityPasswordUsed))
{
if (compatibilityPasswordUsed is { })
{
await ShowErrorAsync(PasswordHelper.CompatibilityPasswordWarnMessage, "Compatibility password was used");
}
return false;
}
return true;
});
if (!IsPasswordIncorrect)
{
wallet.Login();
// TODO: navigate to the wallet welcome page
Navigate().To(walletViewModelBase, NavigationMode.Clear);
}
});
OkCommand = ReactiveCommand.Create(() =>
{
Password = "";
IsPasswordIncorrect = false;
});
ForgotPasswordCommand = ReactiveCommand.Create(() =>
Navigate(NavigationTarget.DialogScreen).To(new PasswordFinderIntroduceViewModel(wallet)));
EnableAutoBusyOn(NextCommand);
}
public ICommand OkCommand { get; }
public ICommand ForgotPasswordCommand { get; }
public KeyManager KeyManager { get; }
}
} | mit | C# |
dc343996693cda5ec85b95ffffccecd897968e82 | fix link. | zhukaixy/open3mod,zhukaixy/open3mod,dayo7116/open3mod,acgessler/open3mod,dayo7116/open3mod,acgessler/open3mod | open3mod/DonationDialog.cs | open3mod/DonationDialog.cs | ///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v0.1)
// [DonationDialog.cs]
// (c) 2012-2013, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS 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.
///////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace open3mod
{
public partial class DonationDialog : Form
{
public DonationDialog()
{
InitializeComponent();
labelCount.Text = "In total, you have opened " + CoreSettings.CoreSettings.Default.CountFilesOpened + " 3D models";
}
private void NotNowAskAgain(object sender, EventArgs e)
{
Close();
}
private void DontAskAgain(object sender, EventArgs e)
{
CoreSettings.CoreSettings.Default.DonationUseCountDown = -1;
Close();
}
private void Donate(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.open3mod.com/donate.htm?ref=inapp");
Close();
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */ | ///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v0.1)
// [DonationDialog.cs]
// (c) 2012-2013, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS 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.
///////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace open3mod
{
public partial class DonationDialog : Form
{
public DonationDialog()
{
InitializeComponent();
labelCount.Text = "In total, you have opened " + CoreSettings.CoreSettings.Default.CountFilesOpened + " 3D models";
}
private void NotNowAskAgain(object sender, EventArgs e)
{
Close();
}
private void DontAskAgain(object sender, EventArgs e)
{
CoreSettings.CoreSettings.Default.DonationUseCountDown = -1;
Close();
}
private void Donate(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.open3mod.com/donate");
Close();
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */ | bsd-3-clause | C# |
a34433c042eeb2df8c47a43181852afbb091293f | remove unused stuff in notification area vm | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Windows/Widgets/NotificationAreaViewModel.cs | TCC.Core/Windows/Widgets/NotificationAreaViewModel.cs | using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Windows.Threading;
using TCC.Data;
using TCC.Settings;
using TCC.ViewModels;
namespace TCC.Windows.Widgets
{
public class NotificationAreaViewModel : TccWindowViewModel
{
private readonly ConcurrentQueue<NotificationInfo> _queue;
public SynchronizedObservableCollection<NotificationInfo> Notifications { get; }
public NotificationAreaViewModel(WindowSettings settings) : base(settings)
{
_queue = new ConcurrentQueue<NotificationInfo>();
Notifications = new SynchronizedObservableCollection<NotificationInfo>(Dispatcher);
}
private void CheckShow()
{
Dispatcher.BeginInvoke(new Action(() =>
{
while (Notifications.Count < ((NotificationAreaSettings) Settings).MaxNotifications)
{
if (_queue.IsEmpty) break;
if (!_queue.TryDequeue(out var next)) continue;
if (!Pass(next)) continue;
Notifications.Add(next);
}
}));
}
private bool Pass(NotificationInfo info)
{
return Notifications.ToSyncList().All(n => n.Message != info.Message);
}
public void Enqueue(string title, string message, NotificationType type, uint duration = 4000U)
{
_queue.Enqueue(new NotificationInfo(title, message, type, duration));
CheckShow();
}
public void DeleteNotification(NotificationInfo dc)
{
Dispatcher.BeginInvoke(new Action(() =>
{
Notifications.Remove(dc);
CheckShow();
}), DispatcherPriority.Background);
}
}
} | using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Windows.Threading;
using TCC.Data;
using TCC.Settings;
using TCC.ViewModels;
namespace TCC.Windows.Widgets
{
public class NotificationAreaViewModel : TccWindowViewModel
{
public event Action NotificationAddedEvent;
private readonly ConcurrentQueue<NotificationInfo> _queue;
public SynchronizedObservableCollection<NotificationInfo /*TODO: use VM if needed*/> Notifications { get; }
public NotificationInfo Current { get; set; }
public NotificationAreaViewModel(WindowSettings settings) : base(settings)
{
_queue = new ConcurrentQueue<NotificationInfo>();
Notifications = new SynchronizedObservableCollection<NotificationInfo>(Dispatcher);
}
private void CheckShow()
{
while (Notifications.Count < ((NotificationAreaSettings)Settings).MaxNotifications)
{
if (_queue.IsEmpty) break;
if (!_queue.TryDequeue(out var next)) continue;
if (!Pass(next)) continue;
Notifications.Add(next);
Current = Notifications[0];
N(nameof(Current));
NotificationAddedEvent?.Invoke();
}
}
private bool Pass(NotificationInfo info)
{
return Notifications.ToSyncList().All(n => n.Message != info.Message);
}
public void Enqueue(string title, string message, NotificationType type, uint duration = 4000U)
{
_queue.Enqueue(new NotificationInfo(title, message, type, duration));
CheckShow();
}
public void DeleteNotification(NotificationInfo dc)
{
Dispatcher.BeginInvoke(new Action(() =>
{
Notifications.Remove(dc);
CheckShow();
}), DispatcherPriority.Background);
}
}
} | mit | C# |
cc8a99b75a7f80dd858bdab50c34d06438e5e2da | add FormatVersion to LogEventDataSerializer | vostok/core | Vostok.Core/Logging/Airlock/LogEventDataSerializer.cs | Vostok.Core/Logging/Airlock/LogEventDataSerializer.cs | using System;
using System.IO;
using Vostok.Airlock;
using Vostok.Commons.Binary;
namespace Vostok.Logging.Airlock
{
public class LogEventDataSerializer : IAirlockSerializer<LogEventData>, IAirlockDeserializer<LogEventData>
{
private const byte FormatVersion = 1;
public LogEventData Deserialize(IAirlockSource source)
{
var reader = source.Reader;
var version = reader.ReadByte();
if (version != FormatVersion)
throw new InvalidDataException("invalid format version: " + version);
return new LogEventData
{
Timestamp = new DateTimeOffset(reader.ReadInt64(), TimeSpan.Zero),
Level = (LogLevel) reader.ReadInt32(),
Message = reader.ReadString(),
Exception = reader.ReadString(),
Properties = reader.ReadDictionary(r => r.ReadString(), r => r.ReadString())
};
}
public void Serialize(LogEventData item, IAirlockSink sink)
{
var writer = sink.Writer;
writer.Write(FormatVersion);
writer.Write(item.Timestamp.UtcTicks);
writer.Write((int) item.Level);
writer.Write(item.Message);
writer.Write(item.Exception);
writer.WriteDictionary(item.Properties, (w, s) => w.Write(s), (w, o) => w.Write(o));
}
}
} | using System;
using Vostok.Airlock;
using Vostok.Commons.Binary;
namespace Vostok.Logging.Airlock
{
public class LogEventDataSerializer : IAirlockSerializer<LogEventData>, IAirlockDeserializer<LogEventData>
{
public LogEventData Deserialize(IAirlockSource source)
{
var reader = source.Reader;
return new LogEventData
{
Timestamp = new DateTimeOffset(reader.ReadInt64(), TimeSpan.Zero),
Level = (LogLevel) reader.ReadInt32(),
Message = reader.ReadString(),
Exception = reader.ReadString(),
Properties = reader.ReadDictionary(r => r.ReadString(), r => r.ReadString())
};
}
public void Serialize(LogEventData item, IAirlockSink sink)
{
var writer = sink.Writer;
writer.Write(item.Timestamp.UtcTicks);
writer.Write((int) item.Level);
writer.Write(item.Message);
writer.Write(item.Exception);
writer.WriteDictionary(item.Properties, (w, s) => w.Write(s), (w, o) => w.Write(o));
}
}
} | mit | C# |
6b2b47a8e6718456410036e42fe4b3728387a2db | Fix code completion disappearing/reseting because C# part of .cshtml in regenerated Razor AddIn generation of C# projection content inside .cshtml depends on code completion being visible hence it needs to know state. Since we are using Roslyn code completion API which doesn't have method to check if code completion is visible and also it's internal, only other way would be to make some public static field inside CSharpBinding which indicates visibility of code completion, hence it's better to just store this value inside textView.Properties. We should be able to remove this in 15.8 when we switch to new VSEditor code completion API. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.VisualStudio.Mac.LanguageServices.Razor/Editor/DefaultVisualStudioCompletionBroker.cs | src/Microsoft.VisualStudio.Mac.LanguageServices.Razor/Editor/DefaultVisualStudioCompletionBroker.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Editor.Razor;
using Microsoft.VisualStudio.Text.Editor;
using MonoDevelop.Ide.CodeCompletion;
namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor.Editor
{
internal class DefaultVisualStudioCompletionBroker : VisualStudioCompletionBroker
{
public override bool IsCompletionActive(ITextView textView)
{
if (textView == null)
{
throw new ArgumentNullException(nameof(textView));
}
if (textView.HasAggregateFocus)
{
return CompletionWindowManager.IsVisible ||
(textView.Properties.TryGetProperty<bool>("RoslynCompletionPresenterSession.IsCompletionActive", out var visible)
&& visible);
}
// Text view does not have focus, if the completion window is visible it's for a different text view.
return false;
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Editor.Razor;
using Microsoft.VisualStudio.Text.Editor;
using MonoDevelop.Ide.CodeCompletion;
namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor.Editor
{
internal class DefaultVisualStudioCompletionBroker : VisualStudioCompletionBroker
{
public override bool IsCompletionActive(ITextView textView)
{
if (textView == null)
{
throw new ArgumentNullException(nameof(textView));
}
if (textView.HasAggregateFocus)
{
return CompletionWindowManager.IsVisible;
}
// Text view does not have focus, if the completion window is visible it's for a different text view.
return false;
}
}
}
| apache-2.0 | C# |
eaedc84c4c221d3d6f7ca4f25d5341a8079558f6 | Update AssemblyInfo | atata-framework/atata-webdriverextras,atata-framework/atata-webdriverextras | src/Atata.WebDriverExtras/Properties/AssemblyInfo.cs | src/Atata.WebDriverExtras/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Atata.WebDriverExtras")]
[assembly: AssemblyDescription("A set of extension methods and other extra classes for Selenium WebDriver.")]
[assembly: Guid("a08c24d1-7904-4a0c-bf07-5aef4a520d82")]
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.12.0")]
[assembly: AssemblyFileVersion("0.12.0")] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Atata.WebDriverExtras")]
[assembly: AssemblyDescription("A set of extension methods and other extra classes for Selenium WebDriver.")]
[assembly: Guid("a08c24d1-7904-4a0c-bf07-5aef4a520d82")]
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.11.0")]
[assembly: AssemblyFileVersion("0.11.0")] | apache-2.0 | C# |
33a9c7b5f9b2262fd2103155def0c9427f2d18ba | Create a valid order | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Test/Helpers/CreateValidEntities.cs | Test/Helpers/CreateValidEntities.cs | using System;
using System.Collections.Generic;
using System.Text;
using Anlab.Core.Domain;
namespace Test.Helpers
{
public static class CreateValidEntities
{
public static Order Order(int? counter, bool populateAllFields = false)
{
var rtValue = new Order();
rtValue.CreatorId = string.Format("CreatorId{0}", counter);
rtValue.Project = string.Format("Project{0}", counter);
if (populateAllFields)
{
rtValue.Creator = new User(); //Meh? test later
rtValue.LabId = string.Format("LabId{0}", counter);
rtValue.ClientId = string.Format("ClientId{0}", counter);
rtValue.AdditionalEmails = string.Format("AdditionalEmails{0}", counter);
rtValue.JsonDetails = string.Format("JsonDetails{0}", counter);
rtValue.Created = DateTime.Now;
rtValue.Updated = DateTime.Now;
}
rtValue.Id = counter ?? 99;
return rtValue;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Test.Helpers
{
public static class CreateValidEntities
{
}
}
| mit | C# |
f9e89adba843cde475639c6bb8b829afa30179c6 | Add missing docs. | SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.Controls/TransitioningContentControl.cs | src/Avalonia.Controls/TransitioningContentControl.cs | using System;
using System.Threading;
using Avalonia.Animation;
namespace Avalonia.Controls;
/// <summary>
/// Displays <see cref="Content"/> according to a <see cref="FuncDataTemplate"/>.
/// Uses <see cref="PageTransition"/> to move between the old and new content values.
/// </summary>
public class TransitioningContentControl : ContentControl
{
private CancellationTokenSource? _lastTransitionCts;
private object? _displayedContent;
/// <summary>
/// Defines the <see cref="PageTransition"/> property.
/// </summary>
public static readonly StyledProperty<IPageTransition?> PageTransitionProperty =
AvaloniaProperty.Register<TransitioningContentControl, IPageTransition?>(nameof(PageTransition),
new CrossFade(TimeSpan.FromSeconds(0.5)));
/// <summary>
/// Defines the <see cref="DisplayedContent"/> property.
/// </summary>
public static readonly DirectProperty<TransitioningContentControl, object?> DisplayedContentProperty =
AvaloniaProperty.RegisterDirect<TransitioningContentControl, object?>(nameof(DisplayedContent),
o => o.DisplayedContent);
/// <summary>
/// Gets or sets the animation played when content appears and disappears.
/// </summary>
public IPageTransition? PageTransition
{
get => GetValue(PageTransitionProperty);
set => SetValue(PageTransitionProperty, value);
}
/// <summary>
/// Gets or sets the content displayed whenever there is no page currently routed.
/// </summary>
public object? DisplayedContent
{
get => _displayedContent;
private set => SetAndRaise(DisplayedContentProperty, ref _displayedContent, value);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == ContentProperty)
{
UpdateContentWithTransition(change.NewValue.GetValueOrDefault());
}
}
/// <summary>
/// Updates the content with transitions.
/// </summary>
/// <param name="content">New content to set.</param>
private async void UpdateContentWithTransition(object? content)
{
_lastTransitionCts?.Cancel();
_lastTransitionCts = new CancellationTokenSource();
if (PageTransition != null)
await PageTransition.Start(this, null, true, _lastTransitionCts.Token);
DisplayedContent = content;
if (PageTransition != null)
await PageTransition.Start(null, this, true, _lastTransitionCts.Token);
}
}
| using System;
using System.Threading;
using Avalonia.Animation;
namespace Avalonia.Controls;
public class TransitioningContentControl : ContentControl
{
private CancellationTokenSource? _lastTransitionCts;
private object? _displayedContent;
/// <summary>
/// Defines the <see cref="PageTransition"/> property.
/// </summary>
public static readonly StyledProperty<IPageTransition?> PageTransitionProperty =
AvaloniaProperty.Register<TransitioningContentControl, IPageTransition?>(nameof(PageTransition),
new CrossFade(TimeSpan.FromSeconds(0.5)));
/// <summary>
/// Defines the <see cref="DisplayedContent"/> property.
/// </summary>
public static readonly DirectProperty<TransitioningContentControl, object?> DisplayedContentProperty =
AvaloniaProperty.RegisterDirect<TransitioningContentControl, object?>(nameof(DisplayedContent),
o => o.DisplayedContent);
/// <summary>
/// Gets or sets the animation played when content appears and disappears.
/// </summary>
public IPageTransition? PageTransition
{
get => GetValue(PageTransitionProperty);
set => SetValue(PageTransitionProperty, value);
}
/// <summary>
/// Gets or sets the content displayed whenever there is no page currently routed.
/// </summary>
public object? DisplayedContent
{
get => _displayedContent;
private set => SetAndRaise(DisplayedContentProperty, ref _displayedContent, value);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == ContentProperty)
{
UpdateContentWithTransition(change.NewValue.GetValueOrDefault());
}
}
/// <summary>
/// Updates the content with transitions.
/// </summary>
/// <param name="content">New content to set.</param>
private async void UpdateContentWithTransition(object? content)
{
_lastTransitionCts?.Cancel();
_lastTransitionCts = new CancellationTokenSource();
if (PageTransition != null)
await PageTransition.Start(this, null, true, _lastTransitionCts.Token);
DisplayedContent = content;
if (PageTransition != null)
await PageTransition.Start(null, this, true, _lastTransitionCts.Token);
}
}
| mit | C# |
e1addac69b6a442671c17fa1f948754f125c50a5 | Update seated mode. | Eusth/VRGIN.Template | VRGIN.Template/GenericSeatedMode.cs | VRGIN.Template/GenericSeatedMode.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using VRGIN.Controls;
using VRGIN.Core;
using VRGIN.Helpers;
using VRGIN.Modes;
namespace VRGIN.Template
{
class GenericSeatedMode : SeatedMode
{
protected override IEnumerable<IShortcut> CreateShortcuts()
{
return base.CreateShortcuts().Concat(new IShortcut[] {
new MultiKeyboardShortcut(new KeyStroke("Ctrl+C"), new KeyStroke("Ctrl+C"), () => { VR.Manager.SetMode<GenericStandingMode>(); })
});
}
/// <summary>
/// Disables controllers for seated mode.
/// </summary>
protected override void CreateControllers()
{
}
/// <summary>
/// Uncomment to automatically switch into Standing Mode when controllers have been detected.
/// </summary>
//protected override void ChangeModeOnControllersDetected()
//{
// VR.Manager.SetMode<GenericStandingMode>();
//}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VRGIN.Controls;
using VRGIN.Core;
using VRGIN.Helpers;
using VRGIN.Modes;
namespace VRGIN.Template
{
class GenericSeatedMode : SeatedMode
{
protected override IEnumerable<IShortcut> CreateShortcuts()
{
return base.CreateShortcuts().Concat(new IShortcut[] {
new MultiKeyboardShortcut(new KeyStroke("Ctrl+C"), new KeyStroke("Ctrl+C"), () => { VR.Manager.SetMode<GenericStandingMode>(); })
});
}
protected override void ChangeModeOnControllersDetected()
{
VR.Manager.SetMode<GenericStandingMode>();
}
}
}
| mit | C# |
b82c717ab965c997bae038ead72d75c2468dcf27 | Update ImageShapeControl.xaml.cs | wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | src/Core2D.UI/Views/Shapes/ImageShapeControl.xaml.cs | src/Core2D.UI/Views/Shapes/ImageShapeControl.xaml.cs | using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Core2D.Editor;
using Core2D.Editors;
using Core2D.Shapes;
using Core2D.UI.Views.Editors;
namespace Core2D.UI.Views.Shapes
{
/// <summary>
/// Interaction logic for <see cref="ImageShapeControl"/> xaml.
/// </summary>
public class ImageShapeControl : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="ImageShapeControl"/> class.
/// </summary>
public ImageShapeControl()
{
InitializeComponent();
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
/// <summary>
/// Edit shape text binding.
/// </summary>
public void OnEditTextBinding(object shape)
{
if (this.VisualRoot is TopLevel topLevel
&& topLevel.DataContext is IProjectEditor editor
&& shape is ITextShape text)
{
var window = new TextBindingEditorWindow()
{
DataContext = new TextBindingEditor()
{
Editor = editor,
Text = text
}
};
window.ShowDialog(topLevel as Window);
}
}
}
}
| using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Core2D.Editor;
using Core2D.Editors;
using Core2D.Shapes;
using Core2D.UI.Views.Editors;
namespace Core2D.UI.Views.Shapes
{
/// <summary>
/// Interaction logic for <see cref="ImageShapeControl"/> xaml.
/// </summary>
public class ImageShapeControl : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="ImageShapeControl"/> class.
/// </summary>
public ImageShapeControl()
{
InitializeComponent();
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
/// <summary>
/// Edit shape text binding.
/// </summary>
public void OnEditTextBinding(object shape)
{
if (this.VisualRoot is TopLevel topLevel
&& topLevel.DataContext is IProjectEditor editor
&& shape is ITextShape text)
{
var window = new TextBindingEditorWindow()
{
DataContext = new TextBindingEditor()
{
Editor = editor,
Text = text,
CaretIndex = text.Text.Length
}
};
window.ShowDialog(topLevel as Window);
}
}
}
}
| mit | C# |
44e44931fe4050e82b2877047b5104d779147f78 | Remove nameof for log event name (#17807) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Middleware/HostFiltering/src/LoggerExtensions.cs | src/Middleware/HostFiltering/src/LoggerExtensions.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.HostFiltering
{
internal static class LoggerExtensions
{
private static readonly Action<ILogger, Exception> _wildcardDetected =
LoggerMessage.Define(LogLevel.Debug, new EventId(0, "WildcardDetected"), "Wildcard detected, all requests with hosts will be allowed.");
private static readonly Action<ILogger, string, Exception> _allowedHosts =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1, "AllowedHosts"), "Allowed hosts: {Hosts}");
private static readonly Action<ILogger, Exception> _allHostsAllowed =
LoggerMessage.Define(LogLevel.Trace, new EventId(2, "AllHostsAllowed"), "All hosts are allowed.");
private static readonly Action<ILogger, string, Exception> _requestRejectedMissingHost =
LoggerMessage.Define<string>(LogLevel.Information, new EventId(3, "RequestRejectedMissingHost"), "{Protocol} request rejected due to missing or empty host header.");
private static readonly Action<ILogger, string, Exception> _requestAllowedMissingHost =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(4, "RequestAllowedMissingHost"), "{Protocol} request allowed with missing or empty host header.");
private static readonly Action<ILogger, string, Exception> _allowedHostMatched =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(5, "AllowedHostMatched"), "The host '{Host}' matches an allowed host.");
private static readonly Action<ILogger, string, Exception> _noAllowedHostMatched =
LoggerMessage.Define<string>(LogLevel.Information, new EventId(6, "NoAllowedHostMatched"), "The host '{Host}' does not match an allowed host.");
public static void WildcardDetected(this ILogger logger) => _wildcardDetected(logger, null);
public static void AllowedHosts(this ILogger logger, string allowedHosts) => _allowedHosts(logger, allowedHosts, null);
public static void AllHostsAllowed(this ILogger logger) => _allHostsAllowed(logger, null);
public static void RequestRejectedMissingHost(this ILogger logger, string protocol) => _requestRejectedMissingHost(logger, protocol, null);
public static void RequestAllowedMissingHost(this ILogger logger, string protocol) => _requestAllowedMissingHost(logger, protocol, null);
public static void AllowedHostMatched(this ILogger logger, string host) => _allowedHostMatched(logger, host, null);
public static void NoAllowedHostMatched(this ILogger logger, string host) => _noAllowedHostMatched(logger, host, null);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.HostFiltering
{
internal static class LoggerExtensions
{
private static readonly Action<ILogger, Exception> _wildcardDetected =
LoggerMessage.Define(LogLevel.Debug, new EventId(0, nameof(WildcardDetected)), "Wildcard detected, all requests with hosts will be allowed.");
private static readonly Action<ILogger, string, Exception> _allowedHosts =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1, nameof(AllowedHosts)), "Allowed hosts: {Hosts}");
private static readonly Action<ILogger, Exception> _allHostsAllowed =
LoggerMessage.Define(LogLevel.Trace, new EventId(2, nameof(AllHostsAllowed)), "All hosts are allowed.");
private static readonly Action<ILogger, string, Exception> _requestRejectedMissingHost =
LoggerMessage.Define<string>(LogLevel.Information, new EventId(3, nameof(RequestRejectedMissingHost)), "{Protocol} request rejected due to missing or empty host header.");
private static readonly Action<ILogger, string, Exception> _requestAllowedMissingHost =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(4, nameof(RequestAllowedMissingHost)), "{Protocol} request allowed with missing or empty host header.");
private static readonly Action<ILogger, string, Exception> _allowedHostMatched =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(5, nameof(AllowedHostMatched)), "The host '{Host}' matches an allowed host.");
private static readonly Action<ILogger, string, Exception> _noAllowedHostMatched =
LoggerMessage.Define<string>(LogLevel.Information, new EventId(6, nameof(NoAllowedHostMatched)), "The host '{Host}' does not match an allowed host.");
public static void WildcardDetected(this ILogger logger) => _wildcardDetected(logger, null);
public static void AllowedHosts(this ILogger logger, string allowedHosts) => _allowedHosts(logger, allowedHosts, null);
public static void AllHostsAllowed(this ILogger logger) => _allHostsAllowed(logger, null);
public static void RequestRejectedMissingHost(this ILogger logger, string protocol) => _requestRejectedMissingHost(logger, protocol, null);
public static void RequestAllowedMissingHost(this ILogger logger, string protocol) => _requestAllowedMissingHost(logger, protocol, null);
public static void AllowedHostMatched(this ILogger logger, string host) => _allowedHostMatched(logger, host, null);
public static void NoAllowedHostMatched(this ILogger logger, string host) => _noAllowedHostMatched(logger, host, null);
}
}
| apache-2.0 | C# |
56c7dba38a6efaadc390b2e360f2ffa20f2739e3 | Fix API Key Authentication attribute which wasn't picking up apiKey value. | skbkontur/NuGetGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,grenade/NuGetGallery_download-count-patch,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,ScottShingler/NuGetGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,JetBrains/ReSharperGallery,projectkudu/SiteExtensionGallery | src/NuGetGallery/Filters/ApiKeyAuthorizeAttribute.cs | src/NuGetGallery/Filters/ApiKeyAuthorizeAttribute.cs | using System;
using System.Globalization;
using System.Net;
using System.Web.Mvc;
using Ninject;
namespace NuGetGallery.Filters
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public sealed class ApiKeyAuthorizeAttribute : ActionFilterAttribute
{
private IUserService _userService; // for tests
public IUserService UserService
{
get { return _userService ?? Container.Kernel.TryGet<IUserService>(); }
set { _userService = value; }
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
var controller = filterContext.Controller;
string apiKeyStr = (string)filterContext.ActionParameters["apiKey"];
filterContext.Result = CheckForResult(apiKeyStr);
}
public ActionResult CheckForResult(string apiKeyStr)
{
if (String.IsNullOrEmpty(apiKeyStr))
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, String.Format(CultureInfo.CurrentCulture, Strings.InvalidApiKey, apiKeyStr));
}
Guid apiKey;
try
{
apiKey = new Guid(apiKeyStr);
}
catch
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, String.Format(CultureInfo.CurrentCulture, Strings.InvalidApiKey, apiKeyStr));
}
User user = UserService.FindByApiKey(apiKey);
if (user == null)
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push"));
}
if (!user.Confirmed)
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, Strings.ApiKeyUserAccountIsUnconfirmed);
}
return null;
}
}
} | using System;
using System.Globalization;
using System.Net;
using System.Web.Mvc;
using Ninject;
namespace NuGetGallery.Filters
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public sealed class ApiKeyAuthorizeAttribute : ActionFilterAttribute
{
private IUserService _userService; // for tests
public IUserService UserService
{
get { return _userService ?? Container.Kernel.TryGet<IUserService>(); }
set { _userService = value; }
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
var controller = filterContext.Controller;
string apiKeyStr = (string)((Controller)controller).RouteData.Values["apiKey"];
filterContext.Result = CheckForResult(apiKeyStr);
}
public ActionResult CheckForResult(string apiKeyStr)
{
if (String.IsNullOrEmpty(apiKeyStr))
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, String.Format(CultureInfo.CurrentCulture, Strings.InvalidApiKey, apiKeyStr));
}
Guid apiKey;
try
{
apiKey = new Guid(apiKeyStr);
}
catch
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, String.Format(CultureInfo.CurrentCulture, Strings.InvalidApiKey, apiKeyStr));
}
User user = UserService.FindByApiKey(apiKey);
if (user == null)
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push"));
}
if (!user.Confirmed)
{
return new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, Strings.ApiKeyUserAccountIsUnconfirmed);
}
return null;
}
}
} | apache-2.0 | C# |
2f20e1bf49a709f51e685e0c6a466cc876168a2e | Fix Bamboo detection (#943) | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/CI/Bamboo/Bamboo.cs | source/Nuke.Common/CI/Bamboo/Bamboo.cs | // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.CI.Bamboo
{
/// <summary>
/// Interface according to the <a href="https://confluence.atlassian.com/bamboo/bamboo-variables-289277087.html">official website</a>.
/// </summary>
[PublicAPI]
[CI]
[ExcludeFromCodeCoverage]
public class Bamboo : Host, IBuildServer
{
public new static Bamboo Instance => Host.Instance as Bamboo;
internal static bool IsRunningBamboo => !Environment.GetEnvironmentVariable("bamboo_planKey").IsNullOrEmpty();
internal Bamboo()
{
}
string IBuildServer.Branch => null;
string IBuildServer.Commit => null;
public long AgentId => EnvironmentInfo.GetVariable<long>("bamboo_agentId");
public string AgentWorkingDirectory => EnvironmentInfo.GetVariable<string>("bamboo_agentWorkingDirectory");
public string AgentHome => EnvironmentInfo.GetVariable<string>("BAMBOO_AGENT_HOME");
public string BuildKey => EnvironmentInfo.GetVariable<string>("bamboo_buildKey");
public long BuildNumber => EnvironmentInfo.GetVariable<long>("bamboo_buildNumber");
public string BuildPlanName => EnvironmentInfo.GetVariable<string>("bamboo_buildPlanName");
public string BuildResultsKey => EnvironmentInfo.GetVariable<string>("bamboo_buildResultKey");
public string BuildResultsUrl => EnvironmentInfo.GetVariable<string>("bamboo_buildResultsUrl");
public DateTime BuildTimeStamp => DateTime.Parse(EnvironmentInfo.GetVariable<string>("bamboo_buildTimeStamp"));
public string BuildWorkingDirectory => EnvironmentInfo.GetVariable<string>("bamboo_build_working_directory");
public bool BuildFailed => EnvironmentInfo.GetVariable<bool>("bamboo_buildFailed");
public string PlanKey => EnvironmentInfo.GetVariable<string>("bamboo_planKey");
public string ShortPlanKey => EnvironmentInfo.GetVariable<string>("bamboo_shortPlanKey");
public string PlanName => EnvironmentInfo.GetVariable<string>("bamboo_planName");
public string ShortPlanName => EnvironmentInfo.GetVariable<string>("bamboo_shortPlanName");
public string PlanStorageTag => EnvironmentInfo.GetVariable<string>("bamboo_plan_storageTag");
public string PlanResultsUrl => EnvironmentInfo.GetVariable<string>("bamboo_resultsUrl");
public string ShortJobKey => EnvironmentInfo.GetVariable<string>("bamboo_shortJobKey");
public string ShortJobName => EnvironmentInfo.GetVariable<string>("bamboo_shortJobName");
}
}
| // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.CI.Bamboo
{
/// <summary>
/// Interface according to the <a href="https://confluence.atlassian.com/bamboo/bamboo-variables-289277087.html">official website</a>.
/// </summary>
[PublicAPI]
[CI]
[ExcludeFromCodeCoverage]
public class Bamboo : Host, IBuildServer
{
public new static Bamboo Instance => Host.Instance as Bamboo;
internal static bool IsRunningBamboo => !Environment.GetEnvironmentVariable("BAMBOO_SERVER").IsNullOrEmpty();
internal Bamboo()
{
}
string IBuildServer.Branch => null;
string IBuildServer.Commit => null;
public long AgentId => EnvironmentInfo.GetVariable<long>("bamboo_agentId");
public string AgentWorkingDirectory => EnvironmentInfo.GetVariable<string>("bamboo_agentWorkingDirectory");
public string AgentHome => EnvironmentInfo.GetVariable<string>("BAMBOO_AGENT_HOME");
public string BuildKey => EnvironmentInfo.GetVariable<string>("bamboo_buildKey");
public long BuildNumber => EnvironmentInfo.GetVariable<long>("bamboo_buildNumber");
public string BuildPlanName => EnvironmentInfo.GetVariable<string>("bamboo_buildPlanName");
public string BuildResultsKey => EnvironmentInfo.GetVariable<string>("bamboo_buildResultKey");
public string BuildResultsUrl => EnvironmentInfo.GetVariable<string>("bamboo_buildResultsUrl");
public DateTime BuildTimeStamp => DateTime.Parse(EnvironmentInfo.GetVariable<string>("bamboo_buildTimeStamp"));
public string BuildWorkingDirectory => EnvironmentInfo.GetVariable<string>("bamboo_build_working_directory");
public bool BuildFailed => EnvironmentInfo.GetVariable<bool>("bamboo_buildFailed");
public string PlanKey => EnvironmentInfo.GetVariable<string>("bamboo_planKey");
public string ShortPlanKey => EnvironmentInfo.GetVariable<string>("bamboo_shortPlanKey");
public string PlanName => EnvironmentInfo.GetVariable<string>("bamboo_planName");
public string ShortPlanName => EnvironmentInfo.GetVariable<string>("bamboo_shortPlanName");
public string PlanStorageTag => EnvironmentInfo.GetVariable<string>("bamboo_plan_storageTag");
public string PlanResultsUrl => EnvironmentInfo.GetVariable<string>("bamboo_resultsUrl");
public string ShortJobKey => EnvironmentInfo.GetVariable<string>("bamboo_shortJobKey");
public string ShortJobName => EnvironmentInfo.GetVariable<string>("bamboo_shortJobName");
}
}
| mit | C# |
1745dfd162cde419194c0bd26bfa92c8c2d7fb8b | Apply security policy to Glimpse so only I can use it for now | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | BatteryCommander.Web/GlimpseSecurityPolicy.cs | BatteryCommander.Web/GlimpseSecurityPolicy.cs | using Glimpse.AspNet.Extensions;
using Glimpse.Core.Extensibility;
namespace BatteryCommander.Web
{
public class GlimpseSecurityPolicy : IRuntimePolicy
{
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
// You can perform a check like the one below to control Glimpse's permissions within your application.
// More information about RuntimePolicies can be found at http://getglimpse.com/Help/Custom-Runtime-Policy
var httpContext = policyContext.GetHttpContext();
if (httpContext.User.Identity.Name != "mattgwagner@gmail.com")
{
return RuntimePolicy.Off;
}
return RuntimePolicy.On;
}
public RuntimeEvent ExecuteOn
{
// The RuntimeEvent.ExecuteResource is only needed in case you create a security policy
// Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details
get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
}
}
} | /*
// Uncomment this class to provide custom runtime policy for Glimpse
using Glimpse.AspNet.Extensions;
using Glimpse.Core.Extensibility;
namespace BatteryCommander.Web
{
public class GlimpseSecurityPolicy:IRuntimePolicy
{
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
// You can perform a check like the one below to control Glimpse's permissions within your application.
// More information about RuntimePolicies can be found at http://getglimpse.com/Help/Custom-Runtime-Policy
// var httpContext = policyContext.GetHttpContext();
// if (!httpContext.User.IsInRole("Administrator"))
// {
// return RuntimePolicy.Off;
// }
return RuntimePolicy.On;
}
public RuntimeEvent ExecuteOn
{
// The RuntimeEvent.ExecuteResource is only needed in case you create a security policy
// Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details
get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
}
}
}
*/ | mit | C# |
a06638f663547d06bde9ee29f70559cbdafe91c2 | Make S3HeaderNames const | carbon/Amazon | src/Amazon.S3/Helpers/S3HeaderNames.cs | src/Amazon.S3/Helpers/S3HeaderNames.cs | namespace Amazon.S3
{
internal static class S3HeaderNames
{
public const string StorageClass = "x-amz-storage-class";
public const string VersionId = "x-amz-version-id";
public const string ContentSha256 = "x-amz-content-sha256";
public const string MetadataDirective = "x-amz-metadata-directive";
public const string Tagging = "x-amz-tagging";
public const string CopySourceIfMatch = "x-amz-copy-source-if-match";
public const string CopySourceIfNoneMatch = "x-amz-copy-source-if-none-match";
public const string CopySourceIfUnmodifiedSince = "x-amz-copy-source-if-unmodified-since";
public const string CopySourceIfModifiedSince = "x-amz-copy-source-if-modified-since";
public const string ServerSideEncryptionCustomerAlgorithm = "x-amz-server-side-encryption-customer-algorithm";
public const string ServerSideEncryptionCustomerKey = "x-amz-server-side-encryption-customer-key";
public const string ServerSideEncryptionCustomerKeyMD5 = "x-amz-server-side-encryption-customer-key-MD5";
}
}
// x-amz-replication-status
// x-amz-restore
// x-amz-object-lock-mode
// x-amz-object-lock-retain-until-date
// x-amz-object-lock-legal-hold | namespace Amazon.S3
{
internal static class S3HeaderNames
{
public static readonly string StorageClass = "x-amz-storage-class";
public static readonly string VersionId = "x-amz-version-id";
public static readonly string ContentSha256 = "x-amz-content-sha256";
public static readonly string MetadataDirective = "x-amz-metadata-directive";
public static readonly string CopySourceIfMatch = "x-amz-copy-source-if-match";
public static readonly string CopySourceIfNoneMatch = "x-amz-copy-source-if-none-match";
public static readonly string CopySourceIfUnmodifiedSince = "x-amz-copy-source-if-unmodified-since";
public static readonly string CopySourceIfModifiedSince = "x-amz-copy-source-if-modified-since";
public static readonly string ServerSideEncryptionCustomerAlgorithm = "x-amz-server-side-encryption-customer-algorithm";
public static readonly string ServerSideEncryptionCustomerKey = "x-amz-server-side-encryption-customer-key";
public static readonly string ServerSideEncryptionCustomerKeyMD5 = "x-amz-server-side-encryption-customer-key-MD5";
}
}
// x-amz-replication-status
// x-amz-restore
// x-amz-object-lock-mode
// x-amz-object-lock-retain-until-date
// x-amz-object-lock-legal-hold | mit | C# |
1852539b9c4bb20c0670d3fd1d073732137a0097 | Add random tags | Auxes/Dogey | src/Dogey.SQLite/Modules/TagsModule.cs | src/Dogey.SQLite/Modules/TagsModule.cs | using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Dogey.SQLite.Modules
{
[Group("tags")]
[Remarks("Search and view available tags.")]
public class TagsModule : ModuleBase<SocketCommandContext>
{
private TagDatabase _db;
protected override void BeforeExecute()
{
_db = new TagDatabase();
}
protected override void AfterExecute()
{
_db.Dispose();
}
[Command]
public async Task TagsAsync()
{
var tags = await _db.GetTagsAsync(Context.Guild.Id);
if (tags.Count() == 0)
{
await ReplyAsync("This guild has no tags yet!");
return;
}
var builder = GetEmbed(tags, Context.Guild.Name, Context.Guild.IconUrl);
await ReplyAsync("", embed: builder);
}
[Command]
public async Task TagsAsync([Remainder]SocketUser user)
{
var tags = await _db.GetTagsAsync(Context.Guild.Id, user.Id);
if (tags.Count() == 0)
{
await ReplyAsync("This user has no tags yet!");
return;
}
var builder = GetEmbed(tags, user.ToString(), user.GetAvatarUrl());
await ReplyAsync("", embed: builder);
}
[Command("random")]
public async Task RandomAsync()
{
var tags = await _db.GetTagsAsync(Context.Guild.Id);
if (tags.Count() == 0)
{
await ReplyAsync("This guild does not have any tags!");
return;
}
var selectedIndex = new Random().Next(0, tags.Count());
var tag = tags.ElementAt(selectedIndex);
await ReplyAsync($"{tag.Aliases.First()}: {tag.Content}");
}
private EmbedBuilder GetEmbed(LiteTag[] tags, string name, string image)
{
string tagMessage = string.Join(", ", tags.Select(x => x.Aliases.First()));
var builder = new EmbedBuilder();
builder.ThumbnailUrl = image;
builder.Title = $"Tags for {name}";
builder.Description = tagMessage;
return builder;
}
}
}
| using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Linq;
using System.Threading.Tasks;
namespace Dogey.SQLite.Modules
{
[Group("tags")]
[Remarks("Search and view available tags.")]
public class TagsModule : ModuleBase<SocketCommandContext>
{
private TagDatabase _db;
protected override void BeforeExecute()
{
_db = new TagDatabase();
}
protected override void AfterExecute()
{
_db.Dispose();
}
[Command]
public async Task TagsAsync()
{
var tags = await _db.GetTagsAsync(Context.Guild.Id);
if (tags.Count() == 0)
{
await ReplyAsync("This guild has no tags yet!");
return;
}
var builder = GetEmbed(tags, Context.Guild.Name, Context.Guild.IconUrl);
await ReplyAsync("", embed: builder);
}
[Command]
public async Task TagsAsync([Remainder]SocketUser user)
{
var tags = await _db.GetTagsAsync(Context.Guild.Id, user.Id);
if (tags.Count() == 0)
{
await ReplyAsync("This user has no tags yet!");
return;
}
var builder = GetEmbed(tags, user.ToString(), user.GetAvatarUrl());
await ReplyAsync("", embed: builder);
}
private EmbedBuilder GetEmbed(LiteTag[] tags, string name, string image)
{
string tagMessage = string.Join(", ", tags.Select(x => x.Aliases.First()));
var builder = new EmbedBuilder();
builder.ThumbnailUrl = image;
builder.Title = $"Tags for {name}";
builder.Description = tagMessage;
return builder;
}
}
}
| apache-2.0 | C# |
b86a9861b581694d81f02cc6dd813c742bffc950 | Update AutofacCompositionRootSetupBase.cs | tiksn/TIKSN-Framework | TIKSN.Core/DependencyInjection/AutofacCompositionRootSetupBase.cs | TIKSN.Core/DependencyInjection/AutofacCompositionRootSetupBase.cs | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using TIKSN.PowerShell;
namespace TIKSN.DependencyInjection
{
public abstract class AutofacCompositionRootSetupBase : CompositionRootSetupBase
{
protected AutofacCompositionRootSetupBase(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
public IContainer CreateContainer()
{
var container = this.CreateContainerInternal();
var serviceProvider = new AutofacServiceProvider(container);
this.ValidateOptions(this._services.Value, serviceProvider);
return container;
}
protected abstract void ConfigureContainerBuilder(ContainerBuilder builder);
protected IContainer CreateContainerInternal()
{
var builder = new ContainerBuilder();
builder.Populate(this._services.Value);
foreach (var module in this.GetAutofacModules())
{
builder.RegisterModule(module);
}
this.ConfigureContainerBuilder(builder);
return builder.Build();
}
protected override IServiceProvider CreateServiceProviderInternal() =>
new AutofacServiceProvider(this.CreateContainerInternal());
protected virtual IEnumerable<IModule> GetAutofacModules()
{
yield return new CoreModule();
yield return new PowerShellModule();
}
}
}
| using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using TIKSN.PowerShell;
namespace TIKSN.DependencyInjection
{
public abstract class AutofacCompositionRootSetupBase : CompositionRootSetupBase
{
protected AutofacCompositionRootSetupBase(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
public IContainer CreateContainer()
{
var container = CreateContainerInternal();
var serviceProvider = new AutofacServiceProvider(container);
ValidateOptions(_services.Value, serviceProvider);
return container;
}
protected abstract void ConfigureContainerBuilder(ContainerBuilder builder);
protected IContainer CreateContainerInternal()
{
var builder = new ContainerBuilder();
builder.Populate(_services.Value);
foreach (var module in GetAutofacModules())
{
builder.RegisterModule(module);
}
ConfigureContainerBuilder(builder);
return builder.Build();
}
protected override IServiceProvider CreateServiceProviderInternal()
{
return new AutofacServiceProvider(CreateContainerInternal());
}
protected virtual IEnumerable<IModule> GetAutofacModules()
{
yield return new CoreModule();
yield return new PowerShellModule();
}
}
} | mit | C# |
c51d6402416bbf1f15c248e1070fde74a36bdfd1 | Add support for searching beatmap author at song select | EVAST9919/osu,2yangk23/osu,UselessToucan/osu,Drezi126/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,peppy/osu,naoey/osu,DrabWeb/osu,Nabile-Rahmani/osu,tacchinotacchi/osu,ZLima12/osu,johnneijzen/osu,peppy/osu,Damnae/osu,peppy/osu-new,naoey/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,Frontear/osuKyzer,naoey/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,DrabWeb/osu,UselessToucan/osu,DrabWeb/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,UselessToucan/osu,osu-RP/osu-RP,ppy/osu,2yangk23/osu | osu.Game/Database/BeatmapMetadata.cs | osu.Game/Database/BeatmapMetadata.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using SQLite.Net.Attributes;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int? OnlineBeatmapSetID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
public string[] SearchableTerms => new[]
{
Author,
Artist,
ArtistUnicode,
Title,
TitleUnicode,
Source,
Tags
}.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using SQLite.Net.Attributes;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int? OnlineBeatmapSetID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
public string[] SearchableTerms => new[]
{
Artist,
ArtistUnicode,
Title,
TitleUnicode,
Source,
Tags
}.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
} | mit | C# |
5c2d5d9ee49f57bf11cd6cc49bd364333d5ad2ef | Fix bug when hitting Enter on last row (PG-234) | sillsdev/Glyssen,sillsdev/Glyssen | Glyssen/Controls/DataGridViewOverrideEnter.cs | Glyssen/Controls/DataGridViewOverrideEnter.cs | using System.Windows.Forms;
using SIL.Windows.Forms.Widgets.BetterGrid;
namespace Glyssen.Controls
{
/// <summary>
/// DataGridView with Enter moving to right (instead of down)
/// </summary>
public class DataGridViewOverrideEnter : BetterGrid
{
public DataGridViewOverrideEnter()
{
AllowUserToAddRows = true;
MultiSelect = true;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
MoveToNextField();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public void MoveToNextField()
{
int nextColumn, nextRow;
if (CurrentCell.ColumnIndex + 1 < ColumnCount)
{
nextColumn = CurrentCell.ColumnIndex + 1;
nextRow = CurrentCell.RowIndex;
}
else if (CurrentCell.RowIndex + 1 < RowCount)
{
nextColumn = 0;
nextRow = CurrentCell.RowIndex + 1;
}
else
{
return;
}
CurrentCell = Rows[nextRow].Cells[nextColumn];
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SIL.Windows.Forms.Widgets.BetterGrid;
namespace Glyssen.Controls
{
//DataGridView with Enter moving to right (instead of down)
public class DataGridViewOverrideEnter : BetterGrid
{
public DataGridViewOverrideEnter()
{
AllowUserToAddRows = true;
MultiSelect = true;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
MoveToNextField();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public void MoveToNextField()
{
int nextColumn, nextRow;
if (CurrentCell.ColumnIndex + 1 < ColumnCount)
{
nextColumn = CurrentCell.ColumnIndex + 1;
nextRow = CurrentCell.RowIndex;
}
else
{
nextColumn = 0;
nextRow = CurrentCell.RowIndex + 1;
}
CurrentCell = Rows[nextRow].Cells[nextColumn];
}
private void InitializeComponent()
{
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
}
}
| mit | C# |
e2091ed4d4732795965f01823b88634c9c17e5d8 | fix MahApps Progress sample | DingpingZhang/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit | MahMaterialDragablzMashUp/DialogsViewModel.cs | MahMaterialDragablzMashUp/DialogsViewModel.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
namespace MahMaterialDragablzMashUp
{
public class DialogsViewModel
{
public ICommand ShowInputDialogCommand { get; }
public ICommand ShowProgressDialogCommand { get; }
public ICommand ShowLeftFlyoutCommand { get; }
private ResourceDictionary DialogDictionary = new ResourceDictionary() { Source = new Uri("pack://application:,,,/MaterialDesignThemes.MahApps;component/Themes/MaterialDesignTheme.MahApps.Dialogs.xaml") };
public DialogsViewModel()
{
ShowInputDialogCommand = new AnotherCommandImplementation(_ => InputDialog());
ShowProgressDialogCommand = new AnotherCommandImplementation(_ => ProgressDialog());
ShowLeftFlyoutCommand = new AnotherCommandImplementation(_ => ShowLeftFlyout());
}
public Flyout LeftFlyout { get; set; }
private void InputDialog()
{
var metroDialogSettings = new MetroDialogSettings
{
CustomResourceDictionary = DialogDictionary,
NegativeButtonText = "CANCEL",
SuppressDefaultResources = true
};
DialogCoordinator.Instance.ShowInputAsync(this, "MahApps Dialog", "Using Material Design Themes", metroDialogSettings);
}
private async void ProgressDialog()
{
var metroDialogSettings = new MetroDialogSettings
{
CustomResourceDictionary = DialogDictionary,
NegativeButtonText = "CANCEL",
SuppressDefaultResources = true
};
var controller = await DialogCoordinator.Instance.ShowProgressAsync(this, "MahApps Dialog", "Using Material Design Themes (WORK IN PROGRESS)", true, metroDialogSettings);
controller.SetIndeterminate();
await Task.Delay(3000);
await controller.CloseAsync();
}
private void ShowLeftFlyout()
{
((MainWindow)Application.Current.MainWindow).LeftFlyout.IsOpen = !((MainWindow)Application.Current.MainWindow).LeftFlyout.IsOpen;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
namespace MahMaterialDragablzMashUp
{
public class DialogsViewModel
{
public ICommand ShowInputDialogCommand { get; }
public ICommand ShowProgressDialogCommand { get; }
public ICommand ShowLeftFlyoutCommand { get; }
private ResourceDictionary DialogDictionary = new ResourceDictionary() { Source = new Uri("pack://application:,,,/MaterialDesignThemes.MahApps;component/Themes/MaterialDesignTheme.MahApps.Dialogs.xaml") };
public DialogsViewModel()
{
ShowInputDialogCommand = new AnotherCommandImplementation(_ => InputDialog());
ShowProgressDialogCommand = new AnotherCommandImplementation(_ => ProgressDialog());
ShowLeftFlyoutCommand = new AnotherCommandImplementation(_ => ShowLeftFlyout());
}
public Flyout LeftFlyout { get; set; }
private void InputDialog()
{
var metroDialogSettings = new MetroDialogSettings
{
CustomResourceDictionary = DialogDictionary,
NegativeButtonText = "CANCEL",
SuppressDefaultResources = true
};
DialogCoordinator.Instance.ShowInputAsync(this, "MahApps Dialog", "Using Material Design Themes", metroDialogSettings);
}
private void ProgressDialog()
{
var metroDialogSettings = new MetroDialogSettings
{
CustomResourceDictionary = DialogDictionary,
NegativeButtonText = "CANCEL",
SuppressDefaultResources = true
};
DialogCoordinator.Instance.ShowProgressAsync(this, "MahApps Dialog", "Using Material Design Themes (WORK IN PROGRESS)", true, metroDialogSettings);
}
private void ShowLeftFlyout()
{
((MainWindow)Application.Current.MainWindow).LeftFlyout.IsOpen = true;
}
}
}
| mit | C# |
3218b8a6aff7cebbfa963eb9df145e93580f522c | Fix press space to start game launch bomb | solfen/Rogue_Cadet | Assets/Scripts/SpecialPowers/SpecialPower.cs | Assets/Scripts/SpecialPowers/SpecialPower.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpecialPower : MonoBehaviour {
public float manaCost;
public float coolDownDuration;
public string button;
public bool isBomb = false; //tmp
[HideInInspector]
public float mana;
public float maxMana;
public float coolDownTimer = 0;
private ISpecialPower power;
void Start () {
power = GetComponent<ISpecialPower>();
if(!isBomb) {
maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp
}
mana = maxMana;
NotifyUI();
enabled = false;
EventDispatcher.AddEventListener(Events.GAME_LOADED, OnLoaded);
}
void OnDestroy() {
EventDispatcher.RemoveEventListener(Events.GAME_LOADED, OnLoaded);
}
private void OnLoaded(object useless) {
enabled = true;
}
// Update is called once per frame
void Update () {
coolDownTimer -= Time.deltaTime;
if(Input.GetButtonDown(button)) {
if (coolDownTimer < 0 && mana >= manaCost) {
power.Activate();
coolDownTimer = coolDownDuration;
mana -= manaCost;
NotifyUI();
}
else {
SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR);
}
}
}
private void NotifyUI() {
if (isBomb) {
BombUI.instance.OnUsePower(this);
}
else {
PowerUI.instance.OnUsePower(this);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpecialPower : MonoBehaviour {
public float manaCost;
public float coolDownDuration;
public string button;
public bool isBomb = false; //tmp
[HideInInspector]
public float mana;
public float maxMana;
public float coolDownTimer = 0;
private ISpecialPower power;
void Start () {
power = GetComponent<ISpecialPower>();
if(!isBomb) {
maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp
}
mana = maxMana;
NotifyUI();
}
// Update is called once per frame
void Update () {
coolDownTimer -= Time.deltaTime;
if(Input.GetButtonDown(button)) {
if (coolDownTimer < 0 && mana >= manaCost) {
power.Activate();
coolDownTimer = coolDownDuration;
mana -= manaCost;
NotifyUI();
}
else {
SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR);
}
}
}
private void NotifyUI() {
if (isBomb) {
BombUI.instance.OnUsePower(this);
}
else {
PowerUI.instance.OnUsePower(this);
}
}
}
| mit | C# |
f279719a66c0aa9891204632d578697d797a3005 | Change version to 1.3 | BoBiene/ContromeToOpenHAB | ContromeToOpenHAB/Properties/AssemblyInfo.cs | ContromeToOpenHAB/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 einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("ContromeToOpenHAB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ContromeToOpenHAB")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("2270efb8-7f26-4071-84bb-0e0824156e53")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.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 einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("ContromeToOpenHAB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ContromeToOpenHAB")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("2270efb8-7f26-4071-84bb-0e0824156e53")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| apache-2.0 | C# |
c7d5d28b8cc5abcefe5e51807bc92ac3dc428610 | Fix overlay hide animation playing at the wrong point in time. | paparony03/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,naoey/osu-framework,Tom94/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,paparony03/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,NeoAdonis/osu-framework,EVAST9919/osu-framework,default0/osu-framework,default0/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,naoey/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,NeoAdonis/osu-framework,smoogipooo/osu-framework,RedNesto/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework | osu.Framework/Graphics/Performance/PerformanceOverlay.cs | osu.Framework/Graphics/Performance/PerformanceOverlay.cs | // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Graphics.Containers;
using System.Linq;
namespace osu.Framework.Graphics.Performance
{
class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode>
{
private FrameStatisticsMode state;
public FrameStatisticsMode State
{
get
{
return state;
}
set
{
if (state == value) return;
state = value;
switch (state)
{
case FrameStatisticsMode.None:
FadeOut(100);
break;
case FrameStatisticsMode.Minimal:
case FrameStatisticsMode.Full:
FadeIn(100);
break;
}
foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>())
d.State = state;
}
}
public override void Load(BaseGame game)
{
base.Load(game);
Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor));
Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor));
Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor));
Direction = FlowDirection.VerticalOnly;
}
}
public enum FrameStatisticsMode
{
None,
Minimal,
Full
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Graphics.Containers;
using System.Linq;
namespace osu.Framework.Graphics.Performance
{
class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode>
{
private FrameStatisticsMode state;
public FrameStatisticsMode State
{
get
{
return state;
}
set
{
if (state == value) return;
state = value;
switch (state)
{
case FrameStatisticsMode.None:
FadeOut(100);
break;
case FrameStatisticsMode.Minimal:
case FrameStatisticsMode.Full:
FadeIn(100);
foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>())
d.State = state;
break;
}
}
}
public override void Load(BaseGame game)
{
base.Load(game);
Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor));
Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor));
Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor));
Direction = FlowDirection.VerticalOnly;
}
}
public enum FrameStatisticsMode
{
None,
Minimal,
Full
}
}
| mit | C# |
f4dd1a4820c4a9a8fd8a6c52d9db5706d370cab8 | Check for null | dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan | SnittListan/Controllers/AbstractController.cs | SnittListan/Controllers/AbstractController.cs | using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Elmah;
namespace SnittListan.Controllers
{
public class AbstractController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (HttpContext.Request.UserLanguages == null)
return;
// try to set culture
foreach (var lang in HttpContext.Request.UserLanguages)
{
try
{
var ci = new CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
break;
}
catch (Exception ex)
{
ErrorSignal
.FromCurrentContext()
.Raise(ex);
}
}
}
}
} | using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Elmah;
namespace SnittListan.Controllers
{
public class AbstractController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// try to set culture
foreach (var lang in HttpContext.Request.UserLanguages)
{
try
{
var ci = new CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
break;
}
catch (Exception ex)
{
ErrorSignal
.FromCurrentContext()
.Raise(ex);
}
}
}
}
} | mit | C# |
bfd4d1bc8884c9303604e73c8a0a1e8a39df64e4 | Correct installation of AutoMapper profiles | dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan | Snittlistan/Installers/AutoMapperInstaller.cs | Snittlistan/Installers/AutoMapperInstaller.cs | using AutoMapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace Snittlistan.Installers
{
public class AutoMapperInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(FindProfiles().LifestyleSingleton().WithServiceFromInterface(typeof(Profile)));
}
private static BasedOnDescriptor FindProfiles()
{
return AllTypes
.FromThisAssembly()
.BasedOn<Profile>();
}
}
} | using AutoMapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace Snittlistan.Installers
{
public class AutoMapperInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(FindProfiles().LifestyleSingleton());
}
private static BasedOnDescriptor FindProfiles()
{
return AllTypes
.FromThisAssembly()
.BasedOn<Profile>();
}
}
} | mit | C# |
d0b5e6c7e68f33f026eb3179a6a85663b9729aeb | Add console app demo | jadiaz/string-duplicates | StringDuplicates/SimpleLibraryDemo/Program.cs | StringDuplicates/SimpleLibraryDemo/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleLibrary;
namespace SimpleLibraryDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Simple Library Demonstration Application");
Console.WriteLine("Please enter a string:");
string input = Console.ReadLine();
try
{
StringUtilities stringUtils = new StringUtilities();
Console.WriteLine(stringUtils.GetDuplicates(input));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleLibrary;
namespace SimpleLibraryDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Simple Library Demonstration Application");
Console.WriteLine("Please enter a string:");
}
}
}
| mit | C# |
8ecd422ec362a64da54c3aa5b06e823c9445f92b | Add a newline | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/DynamicData/DynamicData/StateBagKey.cs | src/DynamicData/DynamicData/StateBagKey.cs | using System;
using System.Collections.Generic;
using System.Reflection;
namespace DotVVM.Framework.Controls.DynamicData
{
public struct StateBagKey : IEquatable<StateBagKey>
{
public object Provider { get; private set; }
public PropertyInfo Property { get; private set; }
public StateBagKey(object provider, PropertyInfo property) : this()
{
Provider = provider;
Property = property;
}
public override bool Equals(object obj)
{
return obj is StateBagKey key && Equals(key);
}
public bool Equals(StateBagKey other)
{
return EqualityComparer<object>.Default.Equals(Provider, other.Provider)
&& EqualityComparer<PropertyInfo>.Default.Equals(Property, other.Property);
}
public override int GetHashCode()
{
return HashCode.Combine(Provider, Property);
}
public static bool operator ==(StateBagKey left, StateBagKey right)
{
return left.Equals(right);
}
public static bool operator !=(StateBagKey left, StateBagKey right)
{
return !(left == right);
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
namespace DotVVM.Framework.Controls.DynamicData
{
public struct StateBagKey : IEquatable<StateBagKey>
{
public object Provider { get; private set; }
public PropertyInfo Property { get; private set; }
public StateBagKey(object provider, PropertyInfo property) : this()
{
Provider = provider;
Property = property;
}
public override bool Equals(object obj)
{
return obj is StateBagKey key && Equals(key);
}
public bool Equals(StateBagKey other)
{
return EqualityComparer<object>.Default.Equals(Provider, other.Provider) && EqualityComparer<PropertyInfo>.Default.Equals(Property, other.Property);
}
public override int GetHashCode()
{
return HashCode.Combine(Provider, Property);
}
public static bool operator ==(StateBagKey left, StateBagKey right)
{
return left.Equals(right);
}
public static bool operator !=(StateBagKey left, StateBagKey right)
{
return !(left == right);
}
}
}
| apache-2.0 | C# |
7bcca9c10690e7f235d06b6b5336d23d93ad083b | Rename parameter | appharbor/appharbor-cli | src/AppHarbor/Commands/LoginAuthCommand.cs | src/AppHarbor/Commands/LoginAuthCommand.cs | using System.IO;
using RestSharp;
using RestSharp.Contrib;
namespace AppHarbor.Commands
{
[CommandHelp("Login to AppHarbor", alias: "login")]
public class LoginAuthCommand : ICommand
{
private readonly IAccessTokenConfiguration _accessTokenConfiguration;
private readonly IMaskedInput _maskedInput;
private readonly TextReader _reader;
private readonly TextWriter _writer;
public LoginAuthCommand(IAccessTokenConfiguration accessTokenConfiguration, IMaskedInput maskedInput, TextReader reader, TextWriter writer)
{
_accessTokenConfiguration = accessTokenConfiguration;
_maskedInput = maskedInput;
_reader = reader;
_writer = writer;
}
public void Execute(string[] arguments)
{
if (_accessTokenConfiguration.GetAccessToken() != null)
{
throw new CommandException("You're already logged in");
}
_writer.Write("Username: ");
var username = _reader.ReadLine();
_writer.Write("Password: ");
var password = _maskedInput.Get();
var accessToken = GetAccessToken(username, password);
_accessTokenConfiguration.SetAccessToken(accessToken);
_writer.WriteLine("Successfully logged in as {0}", username);
}
public virtual string GetAccessToken(string username, string password)
{
//NOTE: Remove when merged into AppHarbor.NET library
var restClient = new RestClient("https://appharbor-token-client.apphb.com");
var request = new RestRequest("/token", Method.POST);
request.AddParameter("username", username);
request.AddParameter("password", password);
var response = restClient.Execute(request);
var accessToken = HttpUtility.ParseQueryString(response.Content)["access_token"];
if (accessToken == null)
{
throw new CommandException("Couldn't log in. Try again");
}
return accessToken;
}
}
}
| using System.IO;
using RestSharp;
using RestSharp.Contrib;
namespace AppHarbor.Commands
{
[CommandHelp("Login to AppHarbor", alias: "login")]
public class LoginAuthCommand : ICommand
{
private readonly IAccessTokenConfiguration _accessTokenConfiguration;
private readonly IMaskedInput _maskedInput;
private readonly TextReader _reader;
private readonly TextWriter _writer;
public LoginAuthCommand(IAccessTokenConfiguration accessTokenConfiguration, IMaskedInput maskedConsoleInput, TextReader reader, TextWriter writer)
{
_accessTokenConfiguration = accessTokenConfiguration;
_maskedInput = maskedConsoleInput;
_reader = reader;
_writer = writer;
}
public void Execute(string[] arguments)
{
if (_accessTokenConfiguration.GetAccessToken() != null)
{
throw new CommandException("You're already logged in");
}
_writer.Write("Username: ");
var username = _reader.ReadLine();
_writer.Write("Password: ");
var password = _maskedInput.Get();
var accessToken = GetAccessToken(username, password);
_accessTokenConfiguration.SetAccessToken(accessToken);
_writer.WriteLine("Successfully logged in as {0}", username);
}
public virtual string GetAccessToken(string username, string password)
{
//NOTE: Remove when merged into AppHarbor.NET library
var restClient = new RestClient("https://appharbor-token-client.apphb.com");
var request = new RestRequest("/token", Method.POST);
request.AddParameter("username", username);
request.AddParameter("password", password);
var response = restClient.Execute(request);
var accessToken = HttpUtility.ParseQueryString(response.Content)["access_token"];
if (accessToken == null)
{
throw new CommandException("Couldn't log in. Try again");
}
return accessToken;
}
}
}
| mit | C# |
07c8a97249449c55a1a263ad4947e919080e0267 | Fix Luc | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/LucFullenwarth.cs | src/Firehose.Web/Authors/LucFullenwarth.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class LucFullenwarth : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Luc";
public string LastName => "Fullenwarth";
public string ShortBioOrTagLine => "Luc is working as a Windows SysAdmin since 1999, and focuses mainly on Microsoft products (Windows, Azure, PowerShell, Active Directory, PKI, Security)";
public string StateOrRegion => "Strasbourg, France";
public string EmailAddress => "luke.blog@outlook.com";
public string GravatarHash => "ec967d9f1a0a2070951f22d87309d2d3";
public string GitHubHandle => "fullenw1";
public string TwitterHandle => "";
public GeoPosition Position => new GeoPosition(48.583636, 7.745839);
public Uri WebSite => new Uri("https://itluke.online/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://itluke.online/feed/"); } }
public bool Filter(SyndicationItem item)
{
// this filters out posts that do not have PowerShell in the title
return item.Title.Text.ToLowerInvariant().Contains("powershell");
}
public string FeedLanguageCode => "en";
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
public class LucFullenwarth : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Luc";
public string LastName => "Fullenwarth";
public string ShortBioOrTagLine => "Luc is working as a Windows SysAdmin since 1999, and focuses mainly on Microsoft products (Windows, Azure, PowerShell, Active Directory, PKI, Security)";
public string StateOrRegion => "Strasbourg, France";
public string EmailAddress => "luke.blog@outlook.com";
public string GravatarHash => "ec967d9f1a0a2070951f22d87309d2d3";
public string GitHubHandle => "fullenw1";
public string TwitterHandle => "";
public GeoPosition Position => new GeoPosition(48.583636, 7.745839);
public Uri WebSite => new Uri("https://itluke.online/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://itluke.online/feed/"); } }
public bool Filter(SyndicationItem item)
{
// this filters out posts that do not have PowerShell in the title
return item.Title.Text.ToLowerInvariant().Contains("powershell");
}
public string FeedLanguageCode => "en";
}
| mit | C# |
58628dff758d6bca939d9896111eba49129d6ebf | Make Exception property in FailedEventArgs readonly | ProgTrade/nUpdate,ProgTrade/nUpdate | nUpdate.WithoutTAP/UpdateEventArgs/FailedEventArgs.cs | nUpdate.WithoutTAP/UpdateEventArgs/FailedEventArgs.cs | // Copyright © Dominic Beger 2017
using System;
namespace nUpdate.UpdateEventArgs
{
/// <summary>
/// Provides data for any event that represents a failure of an operation.
/// </summary>
public class FailedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="FailedEventArgs" />-class.
/// </summary>
/// <param name="exception"></param>
internal FailedEventArgs(Exception exception)
{
Exception = exception;
}
/// <summary>
/// Gets or sets a value representing the exception that occured.
/// </summary>
public Exception Exception { get; }
}
} | // Copyright © Dominic Beger 2017
using System;
namespace nUpdate.UpdateEventArgs
{
/// <summary>
/// Provides data for any event that represents a failure of an operation.
/// </summary>
public class FailedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="FailedEventArgs" />-class.
/// </summary>
/// <param name="exception"></param>
internal FailedEventArgs(Exception exception)
{
Exception = exception;
}
/// <summary>
/// Gets or sets a value representing the exception that occured.
/// </summary>
public Exception Exception { get; set; }
}
} | mit | C# |
85a0c578984cf58b3a75f1490b1b7c379c884b6f | Update WindowDrag.cs | Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation | UnityProject/Assets/Scripts/UI/WindowDrag.cs | UnityProject/Assets/Scripts/UI/WindowDrag.cs | using UnityEngine;
public class WindowDrag : MonoBehaviour
{
public bool resetPositionOnDisable = false;
private float offsetX;
private float offsetY;
private Vector3 startPositon;
private RectTransform rectTransform;
void Start () {
// Save initial window start positon
startPositon = gameObject.transform.position;
rectTransform = GetComponent<RectTransform>();
}
void OnDisable () {
// Reset window to start position
if (resetPositionOnDisable)
{
gameObject.transform.position = startPositon;
}
}
/// <summary>
/// Sets the windowDrag fields offsetX and offsetY from the window position and the mouse position.
/// The fields offsetX and offsetY are the mouse position's offset from the window's top-left corner.
/// In onDrag(), these offsets are used to "hook" the window to the cursor as it is dragged.
/// </summary>
public void BeginDrag()
{
var windowTransformPosition = transform.position;
offsetX = windowTransformPosition.x - Input.mousePosition.x;
offsetY = windowTransformPosition.y - Input.mousePosition.y;
}
/// <summary>
/// Moves the window with the cursor within the screen bounds when called.
/// </summary>
public void OnDrag()
{
var windowSize = rectTransform.sizeDelta;
var windowScale = rectTransform.lossyScale;
var windowWidth = windowSize.x;
var windowHeight = windowSize.y;
var widthScale = windowScale.x;
var heightScale = windowScale.y;
transform.position = new Vector3(
Mathf.Clamp(offsetX + Input.mousePosition.x,
windowWidth * widthScale / 2f,
Screen.width - windowWidth * widthScale / 2f),
Mathf.Clamp(offsetY + Input.mousePosition.y,
windowHeight * heightScale / 2f,
Screen.height - windowHeight * heightScale / 2f));
}
}
| using UnityEngine;
public class WindowDrag : MonoBehaviour
{
public bool resetPositionOnDisable = false;
private float offsetX;
private float offsetY;
private Vector3 startPositon;
void Start () {
// Save initial window start positon
startPositon = gameObject.transform.position;
}
void OnDisable () {
// Reset window to start position
if (resetPositionOnDisable)
{
gameObject.transform.position = startPositon;
}
}
public void BeginDrag()
{
offsetX = transform.position.x - Input.mousePosition.x;
offsetY = transform.position.y - Input.mousePosition.y;
}
public void OnDrag()
{
transform.position = new Vector3(offsetX + Input.mousePosition.x, offsetY + Input.mousePosition.y);
}
}
| agpl-3.0 | C# |
10aceda1e46722d03a9b3f4d988c94690bf29a62 | Declare as static class | oliverzick/Delizious-Filtering | src/Library/HashCode.cs | src/Library/HashCode.cs | #region Copyright and license
// <copyright file="HashCode.cs" company="Oliver Zick">
// Copyright (c) 2016 Oliver Zick. All rights reserved.
// </copyright>
// <author>Oliver Zick</author>
// <license>
// 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.
// </license>
#endregion
namespace Delizious.Filtering
{
using System.Collections.Generic;
using System.Linq;
internal static class HashCode
{
public static int Calculate(IEnumerable<int> hashCodes)
{
return hashCodes.Aggregate(0, Aggregate);
}
private static int Aggregate(int aggregate, int value)
{
unchecked
{
return aggregate ^ (aggregate << 5) + (aggregate >> 2) + value;
}
}
}
}
| #region Copyright and license
// <copyright file="HashCode.cs" company="Oliver Zick">
// Copyright (c) 2016 Oliver Zick. All rights reserved.
// </copyright>
// <author>Oliver Zick</author>
// <license>
// 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.
// </license>
#endregion
namespace Delizious.Filtering
{
using System.Collections.Generic;
using System.Linq;
internal sealed class HashCode
{
public static int Calculate(IEnumerable<int> hashCodes)
{
return hashCodes.Aggregate(0, Aggregate);
}
private static int Aggregate(int aggregate, int value)
{
unchecked
{
return aggregate ^ (aggregate << 5) + (aggregate >> 2) + value;
}
}
}
}
| apache-2.0 | C# |
d6cfd7f0c5327b0ad4f73852a3239842ccd199f0 | Add annotation to DHtml enum | magicmonty/pickles,magicmonty/pickles,ludwigjossieaux/pickles,magicmonty/pickles,dirkrombauts/pickles,blorgbeard/pickles,picklesdoc/pickles,magicmonty/pickles,ludwigjossieaux/pickles,irfanah/pickles,ludwigjossieaux/pickles,irfanah/pickles,blorgbeard/pickles,irfanah/pickles,irfanah/pickles,picklesdoc/pickles,dirkrombauts/pickles,blorgbeard/pickles,dirkrombauts/pickles,dirkrombauts/pickles,blorgbeard/pickles,picklesdoc/pickles,picklesdoc/pickles | src/Pickles/Pickles/DocumentationFormat.cs | src/Pickles/Pickles/DocumentationFormat.cs | #region License
/*
Copyright [2011] [Jeffrey Cameron]
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
using System;
using System.ComponentModel;
namespace PicklesDoc.Pickles
{
public enum DocumentationFormat
{
[Description("HTML")]
Html,
[Description("Microsoft Word OpenXML (.docx)")]
Word,
[Description("Darwin Information Typing Architecture (DITA)")]
Dita,
[Description("Javascript Object Notation (JSON)")]
JSON,
[Description("Microsoft Excel OpenXML (.xlsx)")]
Excel,
[Description("HTML w/search")]
DHtml
}
} | #region License
/*
Copyright [2011] [Jeffrey Cameron]
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
using System;
using System.ComponentModel;
namespace PicklesDoc.Pickles
{
public enum DocumentationFormat
{
[Description("HTML")]
Html,
[Description("Microsoft Word OpenXML (.docx)")]
Word,
[Description("Darwin Information Typing Architecture (DITA)")]
Dita,
[Description("Javascript Object Notation (JSON)")]
JSON,
[Description("Microsoft Excel OpenXML (.xlsx)")]
Excel,
DHtml
}
} | apache-2.0 | C# |
894466f58b845b00b91accd105f7ce088593cbbb | Update NumberFormatting.cs | keith-hall/Extensions,keith-hall/Extensions | src/NumberFormatting.cs | src/NumberFormatting.cs | using System.Text.RegularExpressions;
namespace HallLibrary.Extensions
{
public static class NumberFormatting
{
private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture
private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture
private const char _defaultThousandsSeparator = ',';
private const string _defaultDecimalSeparatorForRegex = @"\.";
public static bool IsValidNumber (string value)
{
return _number.IsMatch(value);
}
public static string AddThousandsSeparators (string number, string thousandsSeparator = null)
{
if (!IsValidNumber(number))
throw new ArgumentException(nameof(number), "String does not contain a valid number");
return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); // TODO: replace comma with thousands separator from current culture
}
/*
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X"); // doesn't add 0x prefix
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix
*/
}
}
| using System.Text.RegularExpressions;
namespace HallLibrary.Extensions
{
public static class NumberFormatting
{
private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture
private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture
private const char _defaultThousandsSeparator = ',';
private const string _defaultDecimalSeparatorForRegex = @"\.";
public static string AddThousandsSeparators (string number, string thousandsSeparator = null) {
if (_number.IsMatch(number)) {
return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); // TODO: replace comma with thousands separator from current culture
} else {
return number;
}
}
/*
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X"); // doesn't add 0x prefix
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix
*/
}
}
| apache-2.0 | C# |
304c49821cab0cfa92de90c1e09026e96fa90406 | fix control catalog. | jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia | samples/ControlCatalog/ViewModels/CursorPageViewModel.cs | samples/ControlCatalog/ViewModels/CursorPageViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Input;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using MiniMvvm;
namespace ControlCatalog.ViewModels
{
public class CursorPageViewModel : ViewModelBase
{
public CursorPageViewModel()
{
StandardCursors = Enum.GetValues(typeof(StandardCursorType))
.Cast<StandardCursorType>()
.Select(x => new StandardCursorModel(x))
.ToList();
var loader = AvaloniaLocator.Current.GetService<IAssetLoader>();
var s = loader.Open(new Uri("avares://ControlCatalog/Assets/avalonia-32.png"));
var bitmap = new Bitmap(s);
CustomCursor = new Cursor(bitmap, new PixelPoint(16, 16));
}
public IEnumerable<StandardCursorModel> StandardCursors { get; }
public Cursor CustomCursor { get; }
public class StandardCursorModel
{
public StandardCursorModel(StandardCursorType type)
{
Type = type;
Cursor = new Cursor(type);
}
public StandardCursorType Type { get; }
public Cursor Cursor { get; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Input;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using ReactiveUI;
namespace ControlCatalog.ViewModels
{
public class CursorPageViewModel : ReactiveObject
{
public CursorPageViewModel()
{
StandardCursors = Enum.GetValues(typeof(StandardCursorType))
.Cast<StandardCursorType>()
.Select(x => new StandardCursorModel(x))
.ToList();
var loader = AvaloniaLocator.Current.GetService<IAssetLoader>();
var s = loader.Open(new Uri("avares://ControlCatalog/Assets/avalonia-32.png"));
var bitmap = new Bitmap(s);
CustomCursor = new Cursor(bitmap, new PixelPoint(16, 16));
}
public IEnumerable<StandardCursorModel> StandardCursors { get; }
public Cursor CustomCursor { get; }
public class StandardCursorModel
{
public StandardCursorModel(StandardCursorType type)
{
Type = type;
Cursor = new Cursor(type);
}
public StandardCursorType Type { get; }
public Cursor Cursor { get; }
}
}
}
| mit | C# |
da5d823ca46ee8ad33f8b510385840ffb856759f | Adjust incorrect namespace | zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype | src/Glimpse.Server.Web/Resources/HelloGlimpseResource.cs | src/Glimpse.Server.Web/Resources/HelloGlimpseResource.cs | using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;
namespace Glimpse.Server.Web.Resources
{
public class HelloGlimpseResource : IRequestHandler
{
public bool WillHandle(IContext context)
{
return context.Request.Path.StartsWith("/Glimpse");
}
public async Task Handle(IContext context)
{
var response = context.Response;
response.SetHeader("Content-Type", "text/plain");
var data = Encoding.UTF8.GetBytes("Hello world, Glimpse!");
await response.WriteAsync(data);
}
}
} | using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;
namespace Glimpse.Server.Resources
{
public class HelloGlimpseResource : IRequestHandler
{
public bool WillHandle(IContext context)
{
return context.Request.Path.StartsWith("/Glimpse");
}
public async Task Handle(IContext context)
{
var response = context.Response;
response.SetHeader("Content-Type", "text/plain");
var data = Encoding.UTF8.GetBytes("Hello world, Glimpse!");
await response.WriteAsync(data);
}
}
} | mit | C# |
9c74ed410e3a016be1153810bb7775bf8e4a1624 | Use cast instead of .AsQueryable() | tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server | src/Tgstation.Server.Host/Database/DatabaseCollection.cs | src/Tgstation.Server.Host/Database/DatabaseCollection.cs | using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Tgstation.Server.Host.Database
{
/// <inheritdoc />
sealed class DatabaseCollection<TModel> : IDatabaseCollection<TModel> where TModel : class
{
/// <summary>
/// The backing <see cref="DbSet{TEntity}"/>.
/// </summary>
readonly DbSet<TModel> dbSet;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseCollection{TModel}"/> <see langword="class"/>.
/// </summary>
/// <param name="dbSet">The value of <see cref="dbSet"/>.</param>
public DatabaseCollection(DbSet<TModel> dbSet)
{
this.dbSet = dbSet ?? throw new ArgumentNullException(nameof(dbSet));
}
/// <inheritdoc />
public IEnumerable<TModel> Local => dbSet.Local;
/// <inheritdoc />
public Type ElementType => ((IQueryable<TModel>)dbSet).ElementType;
/// <inheritdoc />
public Expression Expression => ((IQueryable<TModel>)dbSet).Expression;
/// <inheritdoc />
public IQueryProvider Provider => ((IQueryable<TModel>)dbSet).Provider;
/// <inheritdoc />
public void Add(TModel model) => dbSet.Add(model);
/// <inheritdoc />
public void AddRange(IEnumerable<TModel> models) => dbSet.AddRange(models);
/// <inheritdoc />
public void Attach(TModel model) => dbSet.Attach(model);
/// <inheritdoc />
public IEnumerator<TModel> GetEnumerator() => ((IQueryable<TModel>)dbSet).GetEnumerator();
/// <inheritdoc />
public void Remove(TModel model) => dbSet.Remove(model);
/// <inheritdoc />
public void RemoveRange(IEnumerable<TModel> models) => dbSet.RemoveRange(models);
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => ((IQueryable<TModel>)dbSet).GetEnumerator();
}
} | using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Tgstation.Server.Host.Database
{
/// <inheritdoc />
sealed class DatabaseCollection<TModel> : IDatabaseCollection<TModel> where TModel : class
{
/// <summary>
/// The backing <see cref="DbSet{TEntity}"/>.
/// </summary>
readonly DbSet<TModel> dbSet;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseCollection{TModel}"/> <see langword="class"/>.
/// </summary>
/// <param name="dbSet">The value of <see cref="dbSet"/>.</param>
public DatabaseCollection(DbSet<TModel> dbSet)
{
this.dbSet = dbSet ?? throw new ArgumentNullException(nameof(dbSet));
}
/// <inheritdoc />
public IEnumerable<TModel> Local => dbSet.Local;
/// <inheritdoc />
public Type ElementType => dbSet.AsQueryable().ElementType;
/// <inheritdoc />
public Expression Expression => dbSet.AsQueryable().Expression;
/// <inheritdoc />
public IQueryProvider Provider => dbSet.AsQueryable().Provider;
/// <inheritdoc />
public void Add(TModel model) => dbSet.Add(model);
/// <inheritdoc />
public void AddRange(IEnumerable<TModel> models) => dbSet.AddRange(models);
/// <inheritdoc />
public void Attach(TModel model) => dbSet.Attach(model);
/// <inheritdoc />
public IEnumerator<TModel> GetEnumerator() => dbSet.AsQueryable().GetEnumerator();
/// <inheritdoc />
public void Remove(TModel model) => dbSet.Remove(model);
/// <inheritdoc />
public void RemoveRange(IEnumerable<TModel> models) => dbSet.RemoveRange(models);
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => dbSet.AsQueryable().GetEnumerator();
}
} | agpl-3.0 | C# |
0ca5f6879139f2bc46bb0d1b872403adf22db72e | Add class ProgressRecord stubs | sillvan/Pash,mrward/Pash,ForNeVeR/Pash,Jaykul/Pash,WimObiwan/Pash,ForNeVeR/Pash,sburnicki/Pash,WimObiwan/Pash,mrward/Pash,mrward/Pash,sburnicki/Pash,mrward/Pash,sillvan/Pash,Jaykul/Pash,Jaykul/Pash,Jaykul/Pash,WimObiwan/Pash,sburnicki/Pash,ForNeVeR/Pash,sburnicki/Pash,sillvan/Pash,WimObiwan/Pash,sillvan/Pash,ForNeVeR/Pash | Source/System.Management/Automation/ProgressRecord.cs | Source/System.Management/Automation/ProgressRecord.cs | // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Management.Automation
{
public class ProgressRecord
{
public int ActivityId
{
get
{
throw new NotImplementedException ();
}
}
public int ParentActivityId
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public string Activity
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public string StatusDescription
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public string CurrentOperation
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public int PercentComplete
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public int SecondsRemaining
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public ProgressRecordType RecordType
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public ProgressRecord(int activityId, string activity, string statusDescription)
{
}
public override string ToString()
{
throw new NotImplementedException ();
}
}
}
| // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Management.Automation
{
public class ProgressRecord
{
//public ProgressRecord(int activityId, string activity, string statusDescription);
//public string Activity { get; set; }
//public int ActivityId { get; }
//public string CurrentOperation { get; set; }
//public int ParentActivityId { get; set; }
//public int PercentComplete { get; set; }
//public ProgressRecordType RecordType { get; set; }
//public int SecondsRemaining { get; set; }
//public string StatusDescription { get; set; }
//public override string ToString();
}
}
| bsd-3-clause | C# |
7ce7e83e153e6de3cf3deda2cee963449146933f | comment class | jtattermusch/google-api-dotnet-client,SimonAntony/google-api-dotnet-client,RavindraPatidar/google-api-dotnet-client,eshangin/google-api-dotnet-client,ephraimncory/google-api-dotnet-client,mjacobsen4DFM/google-api-dotnet-client,hoangduit/google-api-dotnet-client,amnsinghl/google-api-dotnet-client,MesutGULECYUZ/google-api-dotnet-client,aoisensi/google-api-dotnet-client,jskeet/google-api-dotnet-client,jskeet/google-api-dotnet-client,sqt-android/google-api-dotnet-client,joesoc/google-api-dotnet-client,hurcane/google-api-dotnet-client,pgallastegui/google-api-dotnet-client,inetdream/google-api-dotnet-client,asifshaon/google-api-dotnet-client,eshivakant/google-api-dotnet-client,hurcane/google-api-dotnet-client,googleapis/google-api-dotnet-client,initaldk/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,duckhamqng/google-api-dotnet-client,kekewong/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,MyOwnClone/google-api-dotnet-client,hivie7510/google-api-dotnet-client,liuqiaosz/google-api-dotnet-client,chenneo/google-api-dotnet-client,Senthilvera/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,line21c/google-api-dotnet-client,jskeet/google-api-dotnet-client,neil-119/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,kelvinRosa/google-api-dotnet-client,amitla/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,peleyal/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,peleyal/google-api-dotnet-client,eydjey/google-api-dotnet-client,bacm/google-api-dotnet-client,karishmal/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,arjunRanosys/google-api-dotnet-client,DJJam/google-api-dotnet-client,initaldk/google-api-dotnet-client,sawanmishra/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,rburgstaler/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,PiRSquared17/google-api-dotnet-client,ssett/google-api-dotnet-client,googleapis/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,aoisensi/google-api-dotnet-client,abujehad139/google-api-dotnet-client,milkmeat/google-api-dotnet-client,hurcane/google-api-dotnet-client,smarly-net/google-api-dotnet-client,amitla/google-api-dotnet-client,kapil-chauhan-ngi/google-api-dotnet-client,jesusog/google-api-dotnet-client,neil-119/google-api-dotnet-client,ErAmySharma/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,olofd/google-api-dotnet-client,lli-klick/google-api-dotnet-client,maha-khedr/google-api-dotnet-client,shumaojie/google-api-dotnet-client,ajmal744/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,cdanielm58/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,amit-learning/google-api-dotnet-client,hurcane/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,peleyal/google-api-dotnet-client,ajaypradeep/google-api-dotnet-client,luantn2/google-api-dotnet-client,mylemans/google-api-dotnet-client,nicolasdavel/google-api-dotnet-client,shumaojie/google-api-dotnet-client,initaldk/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,googleapis/google-api-dotnet-client | Src/GoogleApis.Tools.CodeGen/ServiceClassGenerator.cs | Src/GoogleApis.Tools.CodeGen/ServiceClassGenerator.cs | /*
Copyright 2010 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.CodeDom;
using System.Collections.Generic;
using Google.Apis.Authentication;
using Google.Apis.Discovery;
using Google.Apis.Testing;
using Google.Apis.Tools.CodeGen.Decorator.ServiceDecorator;
namespace Google.Apis.Tools.CodeGen
{
/// <summary>
/// Responsible for generating the Service class, this is handled primarly by calling
/// a secsesion of IServiceDecorator's
/// </summary>
/// <seealso cref="IServiceDecorator"/>
public class ServiceClassGenerator : BaseGenerator
{
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger (typeof(ServiceClassGenerator));
public const string GenericServiceName = "genericService";
public const string AuthenticatorName = "authenticator";
private readonly IEnumerable<IServiceDecorator> decorators;
private readonly IService service;
public ServiceClassGenerator (IService service, IEnumerable<IServiceDecorator> decorators)
{
this.decorators = decorators;
this.service = service;
}
public CodeTypeDeclaration CreateServiceClass ()
{
string serviceClassName = GeneratorUtils.UpperFirstLetter (service.Name) + "Service";
logger.DebugFormat ("Starting Generation of Class {0}", serviceClassName);
var serviceClass = new CodeTypeDeclaration (serviceClassName);
serviceClass.BaseTypes.Add (typeof(IRequestExecutor));
foreach (IServiceDecorator serviceDecorator in decorators) {
logger.DebugFormat("Decorating Class {0} with {1}", serviceClassName, serviceDecorator.ToString());
serviceDecorator.DecorateClass (service, serviceClass);
}
return serviceClass;
}
public static CodeFieldReferenceExpression GetFieldReference (Resource resource, int resourceNumber)
{
return new CodeFieldReferenceExpression (new CodeThisReferenceExpression (),
GeneratorUtils.GetFieldName (resource, resourceNumber));
}
}
} | /*
Copyright 2010 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.CodeDom;
using System.Collections.Generic;
using Google.Apis.Authentication;
using Google.Apis.Discovery;
using Google.Apis.Testing;
using Google.Apis.Tools.CodeGen.Decorator.ServiceDecorator;
namespace Google.Apis.Tools.CodeGen
{
public class ServiceClassGenerator : BaseGenerator
{
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger (typeof(ServiceClassGenerator));
public const string GenericServiceName = "genericService";
public const string AuthenticatorName = "authenticator";
private readonly IEnumerable<IServiceDecorator> decorators;
private readonly IService service;
public ServiceClassGenerator (IService service, IEnumerable<IServiceDecorator> decorators)
{
this.decorators = decorators;
this.service = service;
}
public CodeTypeDeclaration CreateServiceClass ()
{
string serviceClassName = GeneratorUtils.UpperFirstLetter (service.Name) + "Service";
logger.DebugFormat ("Starting Generation of Class {0}", serviceClassName);
var serviceClass = new CodeTypeDeclaration (serviceClassName);
serviceClass.BaseTypes.Add (typeof(IRequestExecutor));
foreach (IServiceDecorator serviceDecorator in decorators) {
logger.DebugFormat("Decorating Class {0} with {1}", serviceClassName, serviceDecorator.ToString());
serviceDecorator.DecorateClass (service, serviceClass);
}
return serviceClass;
}
public static CodeFieldReferenceExpression GetFieldReference (Resource resource, int resourceNumber)
{
return new CodeFieldReferenceExpression (new CodeThisReferenceExpression (),
GeneratorUtils.GetFieldName (resource, resourceNumber));
}
}
} | apache-2.0 | C# |
3799a055f3b277a10bc2009083f104c8f1ddc91c | Clean up warnings where preparing AntlrGeneratedFiles test project | DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn | test-assets/test-projects/AntlrGeneratedFiles/Program.cs | test-assets/test-projects/AntlrGeneratedFiles/Program.cs | using System;
[assembly: CLSCompliant(true)]
namespace Test
{
class Program
{
static void Main(string[] args)
{
new GrammarParser(null);
}
}
}
| using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
new GrammarParser(null);
}
}
}
| mit | C# |
ab617916d63abde507e3c54af10c85bcb54eeb39 | update Invoke to abstract | AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/Abstractions,AspectCore/AspectCore-Framework | src/AspectCore.Lite.Abstractions/Attributes/InterceptorAttribute.cs | src/AspectCore.Lite.Abstractions/Attributes/InterceptorAttribute.cs | using System;
using System.Threading.Tasks;
namespace AspectCore.Lite.Abstractions
{
[NonAspect]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public abstract class InterceptorAttribute : Attribute, IInterceptor
{
public virtual bool AllowMultiple { get; } = false;
public virtual int Order { get; set; } = 0;
public abstract Task Invoke(AspectContext context, AspectDelegate next);
}
}
| using System;
using System.Threading.Tasks;
namespace AspectCore.Lite.Abstractions
{
[NonAspect]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public abstract class InterceptorAttribute : Attribute, IInterceptor
{
public virtual bool AllowMultiple { get; } = false;
public virtual int Order { get; set; } = 0;
public virtual Task Invoke(AspectContext context, AspectDelegate next) => next(context);
}
}
| mit | C# |
6a5002495c1408ba9027f9daa003e47c31f20c55 | use already defined variable, instead of mapping the path twice | madsoulswe/Umbraco-CMS,kgiszewski/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tompipe/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,tompipe/Umbraco-CMS,aaronpowell/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,aaronpowell/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,base33/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,jchurchley/Umbraco-CMS,marcemarc/Umbraco-CMS,tompipe/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,jchurchley/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,kgiszewski/Umbraco-CMS,aadfPT/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,hfloyd/Umbraco-CMS,kgiszewski/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,jchurchley/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,base33/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,hfloyd/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,dawoe/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,aadfPT/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,lars-erik/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,aadfPT/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,aaronpowell/Umbraco-CMS,base33/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS | src/Umbraco.Web/UmbracoApplication.cs | src/Umbraco.Web/UmbracoApplication.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
using Umbraco.Web.Routing;
using umbraco.businesslogic;
namespace Umbraco.Web
{
/// <summary>
/// The Umbraco global.asax class
/// </summary>
public class UmbracoApplication : UmbracoApplicationBase
{
private ManifestWatcher _mw;
protected override void OnApplicationStarted(object sender, EventArgs e)
{
base.OnApplicationStarted(sender, e);
if (ApplicationContext.Current.IsConfigured && GlobalSettings.DebugMode)
{
var appPluginFolder = IOHelper.MapPath("~/App_Plugins/");
if (Directory.Exists(appPluginFolder))
{
_mw = new ManifestWatcher(LoggerResolver.Current.Logger);
_mw.Start(Directory.GetDirectories(appPluginFolder));
}
}
}
protected override void OnApplicationEnd(object sender, EventArgs e)
{
base.OnApplicationEnd(sender, e);
if (_mw != null)
{
_mw.Dispose();
}
}
protected override IBootManager GetBootManager()
{
return new WebBootManager(this);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
using Umbraco.Web.Routing;
using umbraco.businesslogic;
namespace Umbraco.Web
{
/// <summary>
/// The Umbraco global.asax class
/// </summary>
public class UmbracoApplication : UmbracoApplicationBase
{
private ManifestWatcher _mw;
protected override void OnApplicationStarted(object sender, EventArgs e)
{
base.OnApplicationStarted(sender, e);
if (ApplicationContext.Current.IsConfigured && GlobalSettings.DebugMode)
{
var appPluginFolder = IOHelper.MapPath("~/App_Plugins/");
if (Directory.Exists(appPluginFolder))
{
_mw = new ManifestWatcher(LoggerResolver.Current.Logger);
_mw.Start(Directory.GetDirectories(IOHelper.MapPath("~/App_Plugins/")));
}
}
}
protected override void OnApplicationEnd(object sender, EventArgs e)
{
base.OnApplicationEnd(sender, e);
if (_mw != null)
{
_mw.Dispose();
}
}
protected override IBootManager GetBootManager()
{
return new WebBootManager(this);
}
}
}
| mit | C# |
d7e206878bac7ccc558693d40d39726b17c020f4 | optimize GetRootDir | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Unity.Rider/Integration/UnityEditorIntegration/EditorPlugin/PluginPathsProvider.cs | resharper/resharper-unity/src/Unity.Rider/Integration/UnityEditorIntegration/EditorPlugin/PluginPathsProvider.cs | using System.IO;
using System.Reflection;
using JetBrains.Application.Environment;
using JetBrains.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.UnityEditorIntegration.EditorPlugin
{
[SolutionComponent]
public class PluginPathsProvider
{
private readonly ApplicationPackages myApplicationPackages;
private readonly IDeployedPackagesExpandLocationResolver myResolver;
private readonly FileSystemPath myRootDir;
public static readonly string BasicPluginDllFile = "JetBrains.Rider.Unity.Editor.Plugin.Repacked.dll";
public static readonly string Unity56PluginDllFile = "JetBrains.Rider.Unity.Editor.Plugin.Unity56.Repacked.dll";
public static readonly string FullPluginDllFile = "JetBrains.Rider.Unity.Editor.Plugin.Full.Repacked.dll";
public PluginPathsProvider(ApplicationPackages applicationPackages, IDeployedPackagesExpandLocationResolver resolver)
{
myApplicationPackages = applicationPackages;
myResolver = resolver;
myRootDir = GetRootDir();
}
public VirtualFileSystemPath GetEditorPluginPathDir()
{
var editorPluginPathDir = myRootDir.Combine(@"EditorPlugin");
return editorPluginPathDir.ToVirtualFileSystemPath();
}
public bool ShouldRunInstallation()
{
// Avoid EditorPlugin installation when we run from the dotnet-products repository.
// For the dotnet-products repository EditorPlugin may not be compiled, it is optional
return myRootDir.Combine("Product.Root").ExistsFile;
}
private FileSystemPath GetRootDir()
{
var assembly = Assembly.GetExecutingAssembly();
var package = myApplicationPackages.FindPackageWithAssembly(assembly, OnError.LogException);
var installDirectory = myResolver.GetDeployedPackageDirectory(package);
var root = installDirectory.Parent;
return root;
}
}
} | using System.IO;
using System.Reflection;
using JetBrains.Application.Environment;
using JetBrains.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.UnityEditorIntegration.EditorPlugin
{
[SolutionComponent]
public class PluginPathsProvider
{
private readonly ApplicationPackages myApplicationPackages;
private readonly IDeployedPackagesExpandLocationResolver myResolver;
public static readonly string BasicPluginDllFile = "JetBrains.Rider.Unity.Editor.Plugin.Repacked.dll";
public static readonly string Unity56PluginDllFile = "JetBrains.Rider.Unity.Editor.Plugin.Unity56.Repacked.dll";
public static readonly string FullPluginDllFile = "JetBrains.Rider.Unity.Editor.Plugin.Full.Repacked.dll";
public PluginPathsProvider(ApplicationPackages applicationPackages, IDeployedPackagesExpandLocationResolver resolver)
{
myApplicationPackages = applicationPackages;
myResolver = resolver;
}
public VirtualFileSystemPath GetEditorPluginPathDir()
{
var assembly = Assembly.GetExecutingAssembly();
var package = myApplicationPackages.FindPackageWithAssembly(assembly, OnError.LogException);
var installDirectory = myResolver.GetDeployedPackageDirectory(package);
var editorPluginPathDir = installDirectory.Parent.Combine(@"EditorPlugin");
return editorPluginPathDir.ToVirtualFileSystemPath();
}
public bool ShouldRunInstallation()
{
var assembly = Assembly.GetExecutingAssembly();
var package = myApplicationPackages.FindPackageWithAssembly(assembly, OnError.LogException);
var installDirectory = myResolver.GetDeployedPackageDirectory(package);
var root = installDirectory.Parent;
// Avoid EditorPlugin installation when we run from the dotnet-products repository.
// For the dotnet-products repository EditorPlugin may not be compiled, it is optional
return root.Combine("Product.Root").ExistsFile;
}
}
} | apache-2.0 | C# |
6d0e55f59ae7b918b5f3d0aaa25dc86b64cda18e | use integral calculation to prevent wrong fractional rounding | datastax/csharp-driver,maxwellb/csharp-driver,mintsoft/csharp-driver,maxwellb/csharp-driver,datastax/csharp-driver | src/Cassandra/Serialization/Primitive/DateTimeOffsetSerializer.cs | src/Cassandra/Serialization/Primitive/DateTimeOffsetSerializer.cs | //
// Copyright (C) 2012-2016 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Cassandra.Serialization.Primitive
{
internal class DateTimeOffsetSerializer : TypeSerializer<DateTimeOffset>
{
public override ColumnTypeCode CqlType
{
get { return ColumnTypeCode.Timestamp; }
}
internal static DateTimeOffset Deserialize(byte[] buffer, int offset)
{
var milliseconds = BeConverter.ToInt64(buffer, offset);
return UnixStart.AddTicks(TimeSpan.TicksPerMillisecond * milliseconds);
}
internal static byte[] Serialize(DateTimeOffset value)
{
var ticks = (value - UnixStart).Ticks;
return BeConverter.GetBytes(ticks / TimeSpan.TicksPerMillisecond);
}
public override DateTimeOffset Deserialize(ushort protocolVersion, byte[] buffer, int offset, int length, IColumnInfo typeInfo)
{
return Deserialize(buffer, offset);
}
public override byte[] Serialize(ushort protocolVersion, DateTimeOffset value)
{
return Serialize(value);
}
}
}
| //
// Copyright (C) 2012-2016 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Cassandra.Serialization.Primitive
{
internal class DateTimeOffsetSerializer : TypeSerializer<DateTimeOffset>
{
public override ColumnTypeCode CqlType
{
get { return ColumnTypeCode.Timestamp; }
}
internal static DateTimeOffset Deserialize(byte[] buffer, int offset)
{
return UnixStart.AddMilliseconds(BeConverter.ToInt64(buffer, offset));
}
internal static byte[] Serialize(DateTimeOffset value)
{
return BeConverter.GetBytes(Convert.ToInt64(Math.Floor((value - UnixStart).TotalMilliseconds)));
}
public override DateTimeOffset Deserialize(ushort protocolVersion, byte[] buffer, int offset, int length, IColumnInfo typeInfo)
{
return Deserialize(buffer, offset);
}
public override byte[] Serialize(ushort protocolVersion, DateTimeOffset value)
{
return Serialize(value);
}
}
}
| apache-2.0 | C# |
4e48c0cb822beec61758ddc3a31d957451d26eb0 | Change end. | eternnoir/NWorkflow | src/NWorkflow/Flow.cs | src/NWorkflow/Flow.cs | using NLogging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NWorkflow
{
public class Flow : IFlow
{
private ILogger logger;
public RecoveryMode RecoveryMode
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public ILogger Logger
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public Monitoring.IMonitor Monitor
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void RunAllJob()
{
throw new NotImplementedException();
}
public JobResult RunJon(string JobName)
{
throw new NotImplementedException();
}
}
}
| using NLogging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NWorkflow
{
public class Flow : IFlow
{
private ILogger logger;
public RecoveryMode RecoveryMode
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public ILogger Logger
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public Monitoring.IMonitor Monitor
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void RunAllJob()
{
throw new NotImplementedException();
}
public JobResult RunJon(string JobName)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
442b7b452cfd0af716c2d84bba0f5a9c67dc30fd | Add xml comments to IDocumentBuilder (#1540) | graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet | src/GraphQL/Execution/IDocumentBuilder.cs | src/GraphQL/Execution/IDocumentBuilder.cs | using GraphQL.Language.AST;
namespace GraphQL.Execution
{
/// <summary>
/// Creates a <see cref="Document">Document</see> representing a GraphQL AST from a plain GraphQL query string
/// </summary>
public interface IDocumentBuilder
{
/// <summary>
/// Parse a GraphQL request and return a <see cref="Document">Document</see> representing the GraphQL request AST
/// </summary>
Document Build(string body);
}
}
| using GraphQL.Language.AST;
namespace GraphQL.Execution
{
public interface IDocumentBuilder
{
Document Build(string body);
}
}
| mit | C# |
52ccec7f296fb41627a73b11a5b075d82eb09901 | edit xml summary | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/Dialog/IDialogViewModel.cs | WalletWasabi.Fluent/ViewModels/Dialog/IDialogViewModel.cs | namespace WalletWasabi.Fluent.ViewModels.Dialog
{
/// <summary>
/// Interface that abstracts <see cref="DialogViewModelBase{TResult}"/>.
/// </summary>
public interface IDialogViewModel
{
/// <summary>
/// Gets or sets if the dialog is opened/closed.
/// </summary>
bool IsDialogOpen { get; set; }
}
}
| namespace WalletWasabi.Fluent.ViewModels.Dialog
{
public interface IDialogViewModel
{
bool IsDialogOpen { get; set; }
}
}
| mit | C# |
19996be76027e1f4e01b951ef66bbf5417f67872 | Fix nullability in UserAvatar | leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | src/JoinRpg.DataModel/Users/UserAvatar.cs | src/JoinRpg.DataModel/Users/UserAvatar.cs | namespace JoinRpg.DataModel.Users
{
#nullable enable
/// <summary>
/// Avatar for user
/// </summary>
public class UserAvatar
{
/// <summary>
/// Primary key
/// </summary>
public int UserAvatarId { get; set; }
/// <summary>
/// <see cref="User"/>
/// </summary>
public int UserId { get; set; }
/// <summary>
/// <see cref="User"/>
/// </summary>
public virtual User User { get; set; } = null!;
/// <summary>
/// Defines source how avatar was obtained
/// </summary>
public enum Source
{
/// <summary>
/// https://gravatar.com/
/// </summary>
GrAvatar,
/// <summary>
/// Using social network provider
/// </summary>
SocialNetwork,
}
/// <summary>
/// How avatar was obtained
/// </summary>
public Source AvatarSource { get; set; }
/// <summary>
/// What provider is it? Google, VKontakte, etc
/// </summary>
public string? ProviderId { get; set; }
/// <summary>
/// Cached Uri in Azure storage
/// </summary>
public string? CachedUri { get; set; } = null!;
/// <summary>
/// Uri as specified by provider
/// </summary>
public string OriginalUri { get; set; } = null!;
/// <summary>
/// Is active or deleted
/// </summary>
public bool IsActive { get; set; }
}
}
| namespace JoinRpg.DataModel.Users
{
#nullable enable
/// <summary>
/// Avatar for user
/// </summary>
public class UserAvatar
{
/// <summary>
/// Primary key
/// </summary>
public int UserAvatarId { get; set; }
/// <summary>
/// <see cref="User"/>
/// </summary>
public int UserId { get; set; }
/// <summary>
/// <see cref="User"/>
/// </summary>
public virtual User User { get; set; }
/// <summary>
/// Defines source how avatar was obtained
/// </summary>
public enum Source
{
/// <summary>
/// https://gravatar.com/
/// </summary>
GrAvatar,
/// <summary>
/// Using social network provider
/// </summary>
SocialNetwork,
}
/// <summary>
/// How avatar was obtained
/// </summary>
public Source AvatarSource { get; set; }
/// <summary>
/// What provider is it? Google, VKontakte, etc
/// </summary>
public string? ProviderId { get; set; }
/// <summary>
/// Provider-specified key
/// </summary>
public string Uri { get; set; } = null!;
/// <summary>
/// Is active or deleted
/// </summary>
public bool IsActive { get; set; }
}
}
| mit | C# |
1b5e932172c7d27830419c46ef96ab20ab28a2f7 | bump version | jesseh77/UrlFilter | src/UrlFilter/Properties/AssemblyInfo.cs | src/UrlFilter/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("UrlFilter")]
[assembly: AssemblyDescription("Builds linq expressions from query string filters")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jesse H")]
[assembly: AssemblyProduct("UrlFilter")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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.1.*")]
[assembly: AssemblyInformationalVersion("1.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("UrlFilter")]
[assembly: AssemblyDescription("Builds linq expressions from query string filters")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jesse H")]
[assembly: AssemblyProduct("UrlFilter")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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.*")]
[assembly: AssemblyInformationalVersion("1.0.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
dfa5fec9045cdcabc802d99bc9d83854be185d75 | Rename ITerminationHandler methods and add method for when an Assume cannot be satisfied. | symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix | symbooglix/symbooglix/Core/ExecutorHandlers/TerminationHandler.cs | symbooglix/symbooglix/Core/ExecutorHandlers/TerminationHandler.cs | using System;
namespace symbooglix
{
public interface ITerminationHandler
{
void handleSuccess(ExecutionState s);
void handleFailingAssert(ExecutionState s);
void handleFailingEnsures(ExecutionState s);
void handleUnsatisfiableAssume(ExecutionState s);
}
}
| using System;
namespace symbooglix
{
public interface ITerminationHandler
{
void handleSuccess(ExecutionState s);
void handleAssertFail(ExecutionState s);
void handleEnsuresFail(ExecutionState s);
}
}
| bsd-2-clause | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.