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 |
|---|---|---|---|---|---|---|---|---|
99d10a342e047c0f40ff2b4c9236fe7d773a8241 | Remove a string length cap on Name in the Genre Class. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Models/DatabaseModels/Genre.cs | src/Open-School-Library/Models/DatabaseModels/Genre.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DatabaseModels
{
public class Genre
{
public int GenreId { get; set; }
public string Name { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DatabaseModels
{
public class Genre
{
public int GenreId { get; set; }
[StringLength(50)]
public string Name { get; set; }
}
}
| mit | C# |
7322e9865126a9e18933867d09d7a756f2b323dc | bump minor version | pragmatrix/NEventSocket,pragmatrix/NEventSocket,danbarua/NEventSocket,danbarua/NEventSocket | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NEventSocket")]
[assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")]
[assembly: AssemblyCompany("Dan Barua")]
[assembly: AssemblyProduct("NEventSocket")]
[assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")]
[assembly: AssemblyVersion("1.1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NEventSocket")]
[assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")]
[assembly: AssemblyCompany("Dan Barua")]
[assembly: AssemblyProduct("NEventSocket")]
[assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")]
[assembly: AssemblyVersion("1.0.3.0")]
| mpl-2.0 | C# |
e21659f5ecfd37e5e3840253cca186b075e4438d | Update WavChannel.cs | wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter | WavFile/WavChannel.cs | WavFile/WavChannel.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace WavFile
{
#region References
using System;
#endregion
#region WavChannel
/// <summary>
/// WAV channel information
/// </summary>
public struct WavChannel
{
private readonly string _longName;
private readonly string _shortName;
private readonly WavChannelMask _mask;
public WavChannel(string longName, string shortName, WavChannelMask mask)
{
_longName = longName;
_shortName = shortName;
_mask = mask;
}
public string LongName { get { return _longName; } }
public string ShortName { get { return _shortName; } }
public WavChannelMask Mask { get { return _mask; } }
}
#endregion
}
| /*
* WavFile
* Copyright © Wiesław Šoltés 2010-2012. All Rights Reserved
*/
namespace WavFile
{
#region References
using System;
#endregion
#region WavChannel
/// <summary>
/// WAV channel information
/// </summary>
public struct WavChannel
{
private readonly string _longName;
private readonly string _shortName;
private readonly WavChannelMask _mask;
public WavChannel(string longName, string shortName, WavChannelMask mask)
{
_longName = longName;
_shortName = shortName;
_mask = mask;
}
public string LongName { get { return _longName; } }
public string ShortName { get { return _shortName; } }
public WavChannelMask Mask { get { return _mask; } }
}
#endregion
}
| mit | C# |
bca3e22d4fae4be655c2f538f454393939134195 | Increment version # | TrinityWestern/Nvelope,badjer/Nvelope,TrinityWestern/Nvelope,badjer/Nvelope | src/Nvelope/Properties/AssemblyInfo.cs | src/Nvelope/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
// 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("Nvelope")]
[assembly: AssemblyDescription("Nvelope is a set of language extensions for C# - a Batman utility belt to make Microsoft's favorite language faster, friendlier, and just a little bit sexier.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Trinity Western University")]
[assembly: AssemblyProduct("Nvelope")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("163553ef-393a-4ba2-a6de-810c5b83f53b")]
// 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.16")]
[assembly: AssemblyFileVersion("1.0.1.16")]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
// 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("Nvelope")]
[assembly: AssemblyDescription("Nvelope is a set of language extensions for C# - a Batman utility belt to make Microsoft's favorite language faster, friendlier, and just a little bit sexier.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Trinity Western University")]
[assembly: AssemblyProduct("Nvelope")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("163553ef-393a-4ba2-a6de-810c5b83f53b")]
// 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.15")]
[assembly: AssemblyFileVersion("1.0.1.15")]
| mit | C# |
b9e8e6b69d5f7704fdcd78c1f05467ab1ae6e914 | exclude from code coverage | bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather | api/src/BellRichM.Api/Models/LinkModel.cs | api/src/BellRichM.Api/Models/LinkModel.cs | using BellRichM.Attribute.CodeCoverage;
namespace BellRichM.Api.Models
{
/// <summary>
/// The link model.
/// </summary>
[ExcludeFromCodeCoverage]
public class LinkModel
{
/// <summary>
/// Gets or sets the label.
/// </summary>
/// <value>
/// The href.
/// </value>
public string Label { get; set; }
/// <summary>
/// Gets or sets the href.
/// </summary>
/// <value>
/// The href.
/// </value>
public string Href { get; set; }
/// <summary>
/// Gets or sets the relative.
/// </summary>
/// <value>
/// The relative.
/// </value>
public string Rel { get; set; }
/// <summary>
/// Gets or sets the method.
/// </summary>
/// <value>
/// The method.
/// </value>
public string Method { get; set; }
}
} | namespace BellRichM.Api.Models
{
/// <summary>
/// The link model.
/// </summary>
public class LinkModel
{
/// <summary>
/// Gets or sets the label.
/// </summary>
/// <value>
/// The href.
/// </value>
public string Label { get; set; }
/// <summary>
/// Gets or sets the href.
/// </summary>
/// <value>
/// The href.
/// </value>
public string Href { get; set; }
/// <summary>
/// Gets or sets the relative.
/// </summary>
/// <value>
/// The relative.
/// </value>
public string Rel { get; set; }
/// <summary>
/// Gets or sets the method.
/// </summary>
/// <value>
/// The method.
/// </value>
public string Method { get; set; }
}
} | mit | C# |
2a77e8b83940a792857cc1383aa603590b85e55b | change background coordinates from NDC to pixels | Dergash/le | src/Game.cs | src/Game.cs |
using System;
using System.IO;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace LE {
public class Game : GameWindow {
int? backgroundTextureId;
public Game() {
base.Title = "Princess colour";
}
protected override void OnResize(EventArgs e)
{
GL.Viewport(0, 0, this.Width, this.Height);
renderEmptyBackground();
if(this.backgroundTextureId.HasValue) {
renderBackground();
}
this.SwapBuffers();
}
protected override void OnLoad(EventArgs e) {
GL.MatrixMode(MatrixMode.Projection);
GL.Ortho(0, Width, 0, Height, 0, 1);
GL.Enable(EnableCap.Texture2D);
var texture = new Texture("assets/forest.png");
if(texture.Id != -1) {
this.backgroundTextureId = texture.Id;
}
}
protected override void OnRenderFrame(FrameEventArgs e) {
renderEmptyBackground();
if(this.backgroundTextureId.HasValue) {
renderBackground();
}
this.SwapBuffers();
}
void renderEmptyBackground() {
Color color = new Color(32, 50, 108, 0);
GL.ClearColor(color);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
}
void renderBackground() {
GL.BindTexture(TextureTarget.Texture2D, this.backgroundTextureId.Value);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(0, 0); GL.Vertex2(0, 600);
GL.TexCoord2(1, 0); GL.Vertex2(800, 600);
GL.TexCoord2(1, 1); GL.Vertex2(800, 0);
GL.TexCoord2(0, 1); GL.Vertex2(0,0);
GL.End();
}
}
} |
using System;
using System.IO;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace LE {
public class Game : GameWindow {
int? backgroundTextureId;
public Game() {
base.Title = "Princess colour";
}
protected override void OnResize(EventArgs e)
{
GL.Viewport(0, 0, this.Width, this.Height);
renderEmptyBackground();
if(this.backgroundTextureId.HasValue) {
renderBackground();
}
this.SwapBuffers();
}
protected override void OnLoad(EventArgs e) {
GL.Enable(EnableCap.Texture2D);
var texture = new Texture("assets/forest.png");
if(texture.Id != -1) {
this.backgroundTextureId = texture.Id;
}
}
protected override void OnRenderFrame(FrameEventArgs e) {
renderEmptyBackground();
if(this.backgroundTextureId.HasValue) {
renderBackground();
}
this.SwapBuffers();
}
void renderEmptyBackground() {
Color color = new Color(32, 50, 108, 0);
GL.ClearColor(color);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
}
void renderBackground() {
GL.BindTexture(TextureTarget.Texture2D, this.backgroundTextureId.Value);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(0, 0); GL.Vertex2(-1, 1);
GL.TexCoord2(1, 0); GL.Vertex2(1, 1);
GL.TexCoord2(1, 1); GL.Vertex2(1, -1);
GL.TexCoord2(0, 1); GL.Vertex2(-1, -1);
GL.End();
}
}
} | mit | C# |
3a36260ca0934b8566ae77c7e211d49ed4eecbac | Remove ConvertResxToJObject | chunye/azure-functions-ux,projectkudu/WebJobsPortal,agruning/azure-functions-ux,chunye/azure-functions-ux,chunye/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/AzureFunctions,agruning/azure-functions-ux,projectkudu/AzureFunctions,chunye/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal,agruning/azure-functions-ux,agruning/azure-functions-ux,projectkudu/WebJobsPortal,chunye/azure-functions-ux,agruning/azure-functions-ux,projectkudu/AzureFunctions | AzureFunctions.ResxConverter/ResxConvertor.cs | AzureFunctions.ResxConverter/ResxConvertor.cs | using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Resources;
using System.Text;
namespace AzureFunctions.ResxConvertor
{
public class ResxConvertor
{
public void SaveResxAsTypeScriptFile(string resxFilePath, string outputTSFilePAth)
{
var sb = new StringBuilder();
sb.AppendLine("// This file is auto generated");
sb.AppendLine("");
sb.AppendLine("export class PortalResources");
sb.AppendLine("{");
ResXResourceReader rsxr = new ResXResourceReader(resxFilePath);
foreach (DictionaryEntry d in rsxr)
{
sb.AppendLine(string.Format(" public static {0}: string = \"{0}\";", d.Key.ToString()));
}
sb.AppendLine("}");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth))
{
file.WriteLine(sb.ToString());
}
//Close the reader.
rsxr.Close();
}
}
}
| using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Resources;
using System.Text;
namespace AzureFunctions.ResxConvertor
{
public class ResxConvertor
{
public JObject ConvertResxToJObject(string resxFilePath)
{
// Create a ResXResourceReader for the file items.resx.
ResXResourceReader rsxr = new ResXResourceReader(resxFilePath);
var jo = new JObject();
// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
jo[d.Key.ToString()] = d.Value.ToString();
}
//Close the reader.
rsxr.Close();
return jo;
}
public void SaveResxAsTypeScriptFile(string resxFilePath, string outputTSFilePAth)
{
var sb = new StringBuilder();
sb.AppendLine("// This file is auto generated");
sb.AppendLine("");
sb.AppendLine("export class PortalResources");
sb.AppendLine("{");
ResXResourceReader rsxr = new ResXResourceReader(resxFilePath);
foreach (DictionaryEntry d in rsxr)
{
sb.AppendLine(string.Format(" public static {0}: string = \"{0}\";", d.Key.ToString()));
}
sb.AppendLine("}");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth))
{
file.WriteLine(sb.ToString());
}
}
}
}
| apache-2.0 | C# |
30bc9ce093ec2db8d1ac921974eb40468ee8d49d | Update SavingFiles.cs | asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_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,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Files/Handling/SavingFiles.cs | Examples/CSharp/Files/Handling/SavingFiles.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Files.Handling
{
public class SavingFiles
{
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 Workbook object
Workbook workbook = new Workbook();
//Your Code goes here for any workbook related operations
//Save in Excel 97 – 2003 format
workbook.Save(dataDir + "book1.out.xls");
//OR
workbook.Save(dataDir + "book1.out.xls", new XlsSaveOptions(SaveFormat.Excel97To2003));
//Save in Excel2007 xlsx format
workbook.Save(dataDir + "book1.out.xlsx", SaveFormat.Xlsx);
//Save in Excel2007 xlsb format
workbook.Save(dataDir + "book1.out.xlsb", SaveFormat.Xlsb);
//Save in ODS format
workbook.Save(dataDir + "book1.out.ods", SaveFormat.ODS);
//Save in Pdf format
workbook.Save(dataDir + "book1.out.pdf", SaveFormat.Pdf);
//Save in Html format
workbook.Save(dataDir + "book1.out.html", SaveFormat.Html);
//Save in SpreadsheetML format
workbook.Save(dataDir + "book1.out.xml", SaveFormat.SpreadsheetML);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Files.Handling
{
public class SavingFiles
{
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 Workbook object
Workbook workbook = new Workbook();
//Your Code goes here for any workbook related operations
//Save in Excel 97 – 2003 format
workbook.Save(dataDir + "book1.out.xls");
//OR
workbook.Save(dataDir + "book1.out.xls", new XlsSaveOptions(SaveFormat.Excel97To2003));
//Save in Excel2007 xlsx format
workbook.Save(dataDir + "book1.out.xlsx", SaveFormat.Xlsx);
//Save in Excel2007 xlsb format
workbook.Save(dataDir + "book1.out.xlsb", SaveFormat.Xlsb);
//Save in ODS format
workbook.Save(dataDir + "book1.out.ods", SaveFormat.ODS);
//Save in Pdf format
workbook.Save(dataDir + "book1.out.pdf", SaveFormat.Pdf);
//Save in Html format
workbook.Save(dataDir + "book1.out.html", SaveFormat.Html);
//Save in SpreadsheetML format
workbook.Save(dataDir + "book1.out.xml", SaveFormat.SpreadsheetML);
}
}
} | mit | C# |
7ffbfd8a2a1ad4d57289e0065f73a6e66e70b100 | Fix mono build | foens/OpenCVR,foens/OpenCVR,foens/OpenCVR | OpenCVR/Persistence/PersistenceTransaction.cs | OpenCVR/Persistence/PersistenceTransaction.cs | #if (__MonoCS__)
using SQLiteTransaction = Mono.Data.Sqlite.SqliteTransaction;
#else
using System.Data.SQLite;
#endif
namespace OpenCVR.Persistence
{
internal class PersistenceTransaction : IPersistenceTransaction
{
private readonly SQLiteTransaction transaction;
public PersistenceTransaction(SQLiteTransaction transaction)
{
this.transaction = transaction;
}
public void Dispose()
{
transaction.Dispose();
}
public void Commit()
{
transaction.Commit();
}
}
} | using System;
using System.Data.SQLite;
namespace OpenCVR.Persistence
{
internal class PersistenceTransaction : IPersistenceTransaction
{
private readonly SQLiteTransaction transaction;
public PersistenceTransaction(SQLiteTransaction transaction)
{
this.transaction = transaction;
}
public void Dispose()
{
transaction.Dispose();
}
public void Commit()
{
transaction.Commit();
}
}
} | unlicense | C# |
4e2224ca4d4c91079868bb4f5d98b1ef45691334 | Fix for assuming any legacy call is 32-bit | nycdotnet/RedGate.AppHost,red-gate/RedGate.AppHost | RedGate.AppHost.Server/ChildProcessFactory.cs | RedGate.AppHost.Server/ChildProcessFactory.cs | namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, is64Bit, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
| namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, false, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
| apache-2.0 | C# |
9827e3b766c3a3015a1d8cd567272a0ea2f08bf9 | Add String.Left() and String.Right() functions | eleven41/Eleven41.Extensions | Eleven41.Extensions/StringExtensions.cs | Eleven41.Extensions/StringExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eleven41.Extensions
{
public static class StringExtensions
{
// Null-safe version of .Trim()
public static string SafeTrim(this string s)
{
if (s == null)
return s;
return s.Trim();
}
// Ensures the string is non-null.
public static string EnsureNotNull(this string self)
{
if (self == null)
return "";
return self;
}
public static string Upto(this string self, char c)
{
int index = self.IndexOf(c);
if (index < 0)
return "";
return self.Substring(0, index);
}
public static string UptoAndIncluding(this string self, char c)
{
int index = self.IndexOf(c);
if (index < 0)
return "";
return self.Substring(0, index + 1);
}
public static string After(this string self, char c)
{
int index = self.IndexOf(c);
if (index < 0)
return "";
return self.Substring(index + 1);
}
// Returns the left characters from the string.
public static string Left(this string self, int count)
{
if (self == null)
return null;
if (self.Length <= count)
return self;
return self.Substring(0, count);
}
// Returns the right characters from the string.
public static string Right(this string self, int count)
{
if (self == null)
return null;
if (self.Length <= count)
return self;
return self.Substring(self.Length - count, count);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eleven41.Extensions
{
public static class StringExtensions
{
// Null-safe version of .Trim()
public static string SafeTrim(this string s)
{
if (s == null)
return s;
return s.Trim();
}
// Ensures the string is non-null.
public static string EnsureNotNull(this string self)
{
if (self == null)
return "";
return self;
}
public static string Upto(this string self, char c)
{
int index = self.IndexOf(c);
if (index < 0)
return "";
return self.Substring(0, index);
}
public static string UptoAndIncluding(this string self, char c)
{
int index = self.IndexOf(c);
if (index < 0)
return "";
return self.Substring(0, index + 1);
}
public static string After(this string self, char c)
{
int index = self.IndexOf(c);
if (index < 0)
return "";
return self.Substring(index + 1);
}
}
}
| mit | C# |
a070c79a64016adb228c553af1058758488dcb54 | Update SilentUserConfirmation.cs | tiksn/TIKSN-Framework | TIKSN.Core/Progress/SilentUserConfirmation.cs | TIKSN.Core/Progress/SilentUserConfirmation.cs | namespace TIKSN.Progress
{
public class SilentUserConfirmation : IUserConfirmation
{
public bool ShouldContinue(string query, string caption) => true;
public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll)
{
if (yesToAll)
{
return true;
}
if (noToAll)
{
return false;
}
return true;
}
public bool ShouldProcess(string target) => true;
public bool ShouldProcess(string target, string action) => true;
public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) => true;
}
}
| namespace TIKSN.Progress
{
public class SilentUserConfirmation : IUserConfirmation
{
public bool ShouldContinue(string query, string caption)
{
return true;
}
public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll)
{
if (yesToAll) return true;
if (noToAll) return false;
return true;
}
public bool ShouldProcess(string target)
{
return true;
}
public bool ShouldProcess(string target, string action)
{
return true;
}
public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption)
{
return true;
}
}
} | mit | C# |
3cceb354455dbccf1dc096450d42d741163649aa | Fix Stack item status not updating correctly. | space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14 | Content.Client/GameObjects/Components/StackComponent.cs | Content.Client/GameObjects/Components/StackComponent.cs | using Content.Client.UserInterface;
using Content.Client.Utility;
using Content.Shared.GameObjects.Components;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Client.GameObjects.Components
{
[RegisterComponent]
public class StackComponent : SharedStackComponent, IItemStatus
{
[ViewVariables] public int Count { get; private set; }
[ViewVariables] public int MaxCount { get; private set; }
[ViewVariables(VVAccess.ReadWrite)] private bool _uiUpdateNeeded;
public Control MakeControl() => new StatusControl(this);
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
var cast = (StackComponentState) curState;
Count = cast.Count;
MaxCount = cast.MaxCount;
_uiUpdateNeeded = true;
}
private sealed class StatusControl : Control
{
private readonly StackComponent _parent;
private readonly RichTextLabel _label;
public StatusControl(StackComponent parent)
{
_parent = parent;
_label = new RichTextLabel {StyleClasses = {NanoStyle.StyleClassItemStatus}};
AddChild(_label);
parent._uiUpdateNeeded = true;
}
protected override void Update(FrameEventArgs args)
{
base.Update(args);
if (!_parent._uiUpdateNeeded)
{
return;
}
_parent._uiUpdateNeeded = false;
_label.SetMarkup(Loc.GetString("Count: [color=white]{0}[/color]", _parent.Count));
}
}
}
}
| using Content.Client.UserInterface;
using Content.Client.Utility;
using Content.Shared.GameObjects.Components;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Client.GameObjects.Components
{
[RegisterComponent]
public class StackComponent : SharedStackComponent, IItemStatus
{
[ViewVariables] public int Count { get; private set; }
[ViewVariables] public int MaxCount { get; private set; }
[ViewVariables(VVAccess.ReadWrite)] private bool _uiUpdateNeeded;
public Control MakeControl() => new StatusControl(this);
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
var cast = (StackComponentState) curState;
Count = cast.Count;
MaxCount = cast.MaxCount;
}
private sealed class StatusControl : Control
{
private readonly StackComponent _parent;
private readonly RichTextLabel _label;
public StatusControl(StackComponent parent)
{
_parent = parent;
_label = new RichTextLabel {StyleClasses = {NanoStyle.StyleClassItemStatus}};
AddChild(_label);
parent._uiUpdateNeeded = true;
}
protected override void Update(FrameEventArgs args)
{
base.Update(args);
if (!_parent._uiUpdateNeeded)
{
return;
}
_parent._uiUpdateNeeded = false;
_label.SetMarkup(Loc.GetString("Count: [color=white]{0}[/color]", _parent.Count));
}
}
}
}
| mit | C# |
27905becc6075439a04deacc0f967267c08ed0d9 | Fix release-mode crash | pingzing/k-christmas-2016 | KChristmas.Core/NetworkService.cs | KChristmas.Core/NetworkService.cs | using KChristmas.Models;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace KChristmas.Core
{
public class NetworkService
{
private HttpClient _httpClient;
#if DEBUG
private readonly string _baseUrl;
#else
private readonly string _baseUrl = "https://kc2016.azurewebsites.net/";
#endif
private readonly string GetGiftHintsUrl = "api/GetGiftHints?code=Z8RSw1TEMQtGP36KqEIax5bj/XRSvJQBAalBmteLYhWwrk9ldqSFhA==";
private readonly string GetPinkieEventsUrl = "api/GetPinkieEvents?code=nUU8YEaQ6Dw4BgoqFAPFjM1NfTFd1hImXbd/EezinkbL9jbsq0ZBdQ==";
public NetworkService()
{
// Android emulators sit behind a virutal router, so they need to use a differnet IP to hit
// the dev machine's localhost.
#if DEBUG
_baseUrl = DeviceInfo.Platform == DevicePlatform.Android
? "http://10.0.2.2:7071/"
: "http://localhost:7071/";
#endif
_httpClient = new HttpClient();
}
public async Task<string?> GetGiftHints()
{
var response = await _httpClient.GetAsync($"{_baseUrl}{GetGiftHintsUrl}");
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStringAsync();
}
public async Task<PinkieEvent[]> GetPinkieEvents()
{
var response = await _httpClient.GetAsync($"{_baseUrl}{GetPinkieEventsUrl}");
if (!response.IsSuccessStatusCode)
{
return new PinkieEvent[0];
}
return JsonConvert.DeserializeObject<PinkieEvent[]>(await response.Content.ReadAsStringAsync());
}
}
}
| using KChristmas.Models;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace KChristmas.Core
{
public class NetworkService
{
private HttpClient _httpClient;
#if DEBUG
private readonly string _baseUrl;
#else
private readonly string _baseUrl = "https://kc2016.azurewebsites.net/";
#endif
private readonly string GetGiftHintsUrl = "api/GetGiftHints?code=Z8RSw1TEMQtGP36KqEIax5bj/XRSvJQBAalBmteLYhWwrk9ldqSFhA==";
private readonly string GetPinkieEventsUrl = "api/GetPinkieEvents?code=nUU8YEaQ6Dw4BgoqFAPFjM1NfTFd1hImXbd/EezinkbL9jbsq0ZBdQ==";
public NetworkService()
{
// Android emulators sit behind a virutal router, so they need to use a differnet IP to hit
// the dev machine's localhost.
_baseUrl = DeviceInfo.Platform == DevicePlatform.Android
? "http://10.0.2.2:7071/"
: "http://localhost:7071/";
_httpClient = new HttpClient();
}
public async Task<string?> GetGiftHints()
{
var response = await _httpClient.GetAsync($"{_baseUrl}{GetGiftHintsUrl}");
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStringAsync();
}
public async Task<PinkieEvent[]> GetPinkieEvents()
{
var response = await _httpClient.GetAsync($"{_baseUrl}{GetPinkieEventsUrl}");
if (!response.IsSuccessStatusCode)
{
return new PinkieEvent[0];
}
return JsonConvert.DeserializeObject<PinkieEvent[]>(await response.Content.ReadAsStringAsync());
}
}
}
| mit | C# |
d51aa6d4ee9e8971b34ec9d86b534093f3f8aacf | Add EmptyFiles to testCoverageFilter (#68) | bbtsoftware/TfsUrlParser | recipe.cake | recipe.cake | #load nuget:?package=Cake.Recipe&version=1.0.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "TfsUrlParser",
repositoryOwner: "bbtsoftware",
repositoryName: "TfsUrlParser",
appVeyorAccountName: "BBTSoftwareAG",
shouldPublishMyGet: false,
shouldRunCodecov: true,
shouldDeployGraphDocumentation: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(
context: Context,
dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]* -[DiffEngine]* -[EmptyFiles]*",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| #load nuget:?package=Cake.Recipe&version=1.0.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "TfsUrlParser",
repositoryOwner: "bbtsoftware",
repositoryName: "TfsUrlParser",
appVeyorAccountName: "BBTSoftwareAG",
shouldPublishMyGet: false,
shouldRunCodecov: true,
shouldDeployGraphDocumentation: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(
context: Context,
dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]* -[DiffEngine]*",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| mit | C# |
1d5bd11e3b53e08209205ad0f4076574f3a95623 | Add support for sending ASCII characters in FileMapManager | Piotrekol/StreamCompanion,Piotrekol/StreamCompanion | osu!StreamCompanion/Code/Modules/MapDataGetters/FileMap/FileMapManager.cs | osu!StreamCompanion/Code/Modules/MapDataGetters/FileMap/FileMapManager.cs | using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
namespace osu_StreamCompanion.Code.Modules.MapDataGetters.FileMap
{
public class FileMapManager
{
Dictionary<string, MapContainer> _files = new Dictionary<string, MapContainer>();
private readonly object _lockingObject = new object();
private class MapContainer
{
public MemoryMappedFile File { get; set; }
public bool ASCIIonly = false;
private readonly object _lockingObject = new object();
public void Write(string data)
{
lock (_lockingObject)
{
byte[] bytes;
if (ASCIIonly)
bytes = Encoding.ASCII.GetBytes(data.Replace("\\n","\n"));
else
bytes = Encoding.Unicode.GetBytes(data);
using (var a = File.CreateViewStream())
{
a.Write(bytes, 0, bytes.Length);
a.WriteByte(0);
}
}
}
}
private MapContainer GetFile(string pipeName)
{
lock (_lockingObject)
{
if (_files.ContainsKey(pipeName))
return _files[pipeName];
MapContainer f = new MapContainer() { File = MemoryMappedFile.CreateOrOpen(pipeName, 16 * 1024) };
_files.Add(pipeName, f);
return f;
}
}
public void Write(string name, string value)
{
var file = GetFile(name);
file.Write(value);
}
}
} | using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
namespace osu_StreamCompanion.Code.Modules.MapDataGetters.FileMap
{
public class FileMapManager
{
Dictionary<string, MapContainer> _files = new Dictionary<string, MapContainer>();
private readonly object _lockingObject = new object();
private class MapContainer
{
public MemoryMappedFile File { get; set; }
private readonly object _lockingObject = new object();
public void Write(string data)
{
lock (_lockingObject)
{
var bytes = Encoding.Unicode.GetBytes(data);
using (var a = File.CreateViewStream())
{
a.Write(bytes, 0, bytes.Length);
a.WriteByte(0);
}
}
}
}
private MapContainer GetFile(string pipeName)
{
lock (_lockingObject)
{
if (_files.ContainsKey(pipeName))
return _files[pipeName];
MapContainer f = new MapContainer() { File = MemoryMappedFile.CreateOrOpen(pipeName, 16 * 1024) };
_files.Add(pipeName, f);
return f;
}
}
public void Write(string name, string value)
{
var file = GetFile(name);
file.Write(value);
}
}
} | mit | C# |
8be0dec2c4fab0deca694537470cf7252ba16df6 | Use of metadata proxies to generate table. | xaviermonin/EntityCore | Core/EntityCore/DynamicEntity/DatabaseStructure/EntityDatabaseStructure.cs | Core/EntityCore/DynamicEntity/DatabaseStructure/EntityDatabaseStructure.cs | using EntityCore.Proxy.Metadata;
using System.Text;
namespace EntityCore.DynamicEntity
{
internal class EntityDatabaseStructure
{
public static string GenerateCreateTableSqlQuery(IEntity entity)
{
var createTable = new StringBuilder();
createTable.AppendFormat("CREATE TABLE [{0}] (Id int IDENTITY(1,1) NOT NULL, ", entity.Name);
foreach (var attribute in entity.Attributes)
{
createTable.AppendFormat("{0} {1}{2} {3} {4}, ", attribute.Name,
attribute.Type.SqlServerName,
attribute.Length == null ? string.Empty : "(" + attribute.Length.ToString() + ")",
(attribute.IsNullable ?? true) ? "NULL" : string.Empty,
attribute.DefaultValue != null ? "DEFAULT(" + attribute.DefaultValue + ")" : string.Empty);
}
createTable.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name);
createTable.AppendFormat("(Id ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF," +
"ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
return createTable.ToString();
}
}
}
| using System.Text;
using Models = EntityCore.Initialization.Metadata.Models;
namespace EntityCore.DynamicEntity
{
internal class EntityDatabaseStructure
{
public static string GenerateCreateTableSqlQuery(Models.Entity entity)
{
var createTable = new StringBuilder();
createTable.AppendFormat("CREATE TABLE [{0}] (Id int IDENTITY(1,1) NOT NULL, ", entity.Name);
foreach (var attribute in entity.Attributes)
{
createTable.AppendFormat("{0} {1}{2} {3} {4}, ", attribute.Name,
attribute.Type.SqlServerName,
attribute.Length == null ? string.Empty : "(" + attribute.Length.ToString() + ")",
attribute.IsNullable ? "NULL" : string.Empty,
attribute.DefaultValue != null ? "DEFAULT(" + attribute.DefaultValue + ")" : string.Empty);
}
createTable.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name);
createTable.AppendFormat("(Id ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF," +
"ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
return createTable.ToString();
}
}
}
| mit | C# |
3ef120d631393d9149acac5fcfa81770e0255df9 | Add new property to session type | neo4j/neo4j-dotnet-driver,neo4j/neo4j-dotnet-driver | Neo4j.Driver/Neo4j.Driver.Tests.TestBackend/Protocol/Session/NewSession.cs | Neo4j.Driver/Neo4j.Driver.Tests.TestBackend/Protocol/Session/NewSession.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Neo4j.Driver.Tests.TestBackend
{
internal class NewSession : IProtocolObject
{
public enum SessionState
{
RetryAbleNothing,
RetryAblePositive,
RetryAbleNegative
}
[JsonIgnore]
public SessionState RetryState { get; private set; } = SessionState.RetryAbleNothing;
[JsonIgnore]
public string RetryableErrorId { get; private set; }
public NewSessionType data { get; set; } = new NewSessionType();
[JsonIgnore]
public IAsyncSession Session { get; set; }
public class NewSessionType
{
public string driverId { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public string accessMode { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public List<string> bookmarks { get; set; } = new List<string>();
[JsonProperty(Required = Required.AllowNull)]
public string database { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public long fetchSize { get; set; } = 1000;
[JsonProperty(Required = Required.AllowNull)]
public string impersonatedUser { get; set; }
}
[JsonIgnore]
public AccessMode GetAccessMode
{
get
{
if (data.accessMode == "r")
return AccessMode.Read;
else
return AccessMode.Write;
}
}
[JsonIgnore]
public List<string> SessionTransactions { get; } = new List<string>();
void SessionConfig(SessionConfigBuilder configBuilder)
{
if(!string.IsNullOrEmpty(data.database)) configBuilder.WithDatabase(data.database);
if(!string.IsNullOrEmpty(data.accessMode)) configBuilder.WithDefaultAccessMode(GetAccessMode);
if(data.bookmarks.Count > 0) configBuilder.WithBookmarks(Bookmark.From(data.bookmarks.ToArray()));
configBuilder.WithFetchSize(data.fetchSize);
}
public override async Task Process()
{
IDriver driver = ((NewDriver)ObjManager.GetObject(data.driverId)).Driver;
Session = driver.AsyncSession(SessionConfig);
await Task.CompletedTask;
}
public override string Respond()
{
return new ProtocolResponse("Session", uniqueId).Encode();
}
public void SetupRetryAbleState(SessionState state, string retryableErrorId = "")
{
RetryState = state;
RetryableErrorId = retryableErrorId;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Neo4j.Driver.Tests.TestBackend
{
internal class NewSession : IProtocolObject
{
public enum SessionState
{
RetryAbleNothing,
RetryAblePositive,
RetryAbleNegative
}
[JsonIgnore]
public SessionState RetryState { get; private set; } = SessionState.RetryAbleNothing;
[JsonIgnore]
public string RetryableErrorId { get; private set; }
public NewSessionType data { get; set; } = new NewSessionType();
[JsonIgnore]
public IAsyncSession Session { get; set; }
public class NewSessionType
{
public string driverId { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public string accessMode { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public List<string> bookmarks { get; set; } = new List<string>();
[JsonProperty(Required = Required.AllowNull)]
public string database { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public long fetchSize { get; set; } = 1000;
}
[JsonIgnore]
public AccessMode GetAccessMode
{
get
{
if (data.accessMode == "r")
return AccessMode.Read;
else
return AccessMode.Write;
}
}
[JsonIgnore]
public List<string> SessionTransactions { get; } = new List<string>();
void SessionConfig(SessionConfigBuilder configBuilder)
{
if(!string.IsNullOrEmpty(data.database)) configBuilder.WithDatabase(data.database);
if(!string.IsNullOrEmpty(data.accessMode)) configBuilder.WithDefaultAccessMode(GetAccessMode);
if(data.bookmarks.Count > 0) configBuilder.WithBookmarks(Bookmark.From(data.bookmarks.ToArray()));
configBuilder.WithFetchSize(data.fetchSize);
}
public override async Task Process()
{
IDriver driver = ((NewDriver)ObjManager.GetObject(data.driverId)).Driver;
Session = driver.AsyncSession(SessionConfig);
await Task.CompletedTask;
}
public override string Respond()
{
return new ProtocolResponse("Session", uniqueId).Encode();
}
public void SetupRetryAbleState(SessionState state, string retryableErrorId = "")
{
RetryState = state;
RetryableErrorId = retryableErrorId;
}
}
}
| apache-2.0 | C# |
9f2c730b918a1a22251c422e9e98a41b5ffd7e03 | build 7.1.11 | agileharbor/channelAdvisorAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.11.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.10.0" ) ] | bsd-3-clause | C# |
ae357d6ff87f23a0df99bdcbb7796acaf2670a5e | Create Program.cs | chemadvisor/chemapi_csharp_example | ConsoleClient/Program.cs | ConsoleClient/Program.cs | /*
* Copyright (c) 2017 ChemADVISOR, Inc. All rights reserved.
* Licensed under The MIT License (MIT)
* https://opensource.org/licenses/MIT
*/
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ConsoleClient
{
internal class Program
{
public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();
private static async Task MainAsync()
{
// set base address
var baseAddress = "https://sandbox.chemadvisor.io/chem/rest/v2/";
// set user_key header
var userKey = "your_user_key";
// set accept header: "application/xml", "application/json"
var acceptHeader = "application/json";
// set api
var resource = "lists";
// set query parameters: q, limit, offset
var q = Uri.EscapeUriString("{\"tags.tag.name\":\"Government Inventory Lists\"}");
var limit = 10;
var offset = 0;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
client.DefaultRequestHeaders.Add("user_key", userKey);
var response = await client.GetAsync(string.Format("{0}?q={1}&limit={2}&offset={3}", resource, q, limit, offset));
if (response.IsSuccessStatusCode)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
else
{
Console.WriteLine(response.StatusCode);
}
Console.ReadLine();
}
}
}
| /*
* Copyright (c) 2017 ChemADVISOR, Inc. All rights reserved.
* Licensed under The MIT License (MIT)
* https://opensource.org/licenses/MIT
*/
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ConsoleClient
{
internal class Program
{
public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();
private static async Task MainAsync()
{
// set base address
var baseAddress = "https://sandbox.chemadvisor.io/chem/rest/v2/";
// set user_key header
var userKey = "YOURUSERKEY";
// set accept header: "application/xml", "application/json"
var acceptHeader = "application/json";
// set api
var api = "lists";
// set query parameters: q, limit, offset
var q = Uri.EscapeUriString("{\"tags.tag.name\":\"Government Inventory Lists\"}");
var limit = 10;
var offset = 0;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
client.DefaultRequestHeaders.Add("user_key", userKey);
var response = await client.GetAsync(string.Format("{0}?q={1}&limit={2}&offset={3}", api, q, limit, offset));
if (response.IsSuccessStatusCode)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
else
{
Console.WriteLine(response.StatusCode);
}
Console.ReadLine();
}
}
} | mit | C# |
65ee5d00352f583afe72aa79cc34b7fa7497194a | Update version number. Nice. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.69.*")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.68.*")]
| mit | C# |
189491de6ecf6f8f2a4b465853ed01a3ff262544 | Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | jango2015/Autofac.Configuration,autofac/Autofac.Configuration | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Configuration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Configuration, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
| using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Configuration")]
[assembly: AssemblyDescription("Autofac XML Configuration Support")]
[assembly: InternalsVisibleTo("Autofac.Tests.Configuration, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
| mit | C# |
5a2998cc63d39ca21c493d182e5a027803f64a82 | Clean up Table | doom-desire/GBA | GBAHL/Text/Table.cs | GBAHL/Text/Table.cs | using System;
namespace GBAHL.Text
{
/// <summary>
/// Represents a table of characters.
/// </summary>
public class Table
{
/// <summary>
/// Initializes a new instance of the <see cref="Table"/> class.
/// </summary>
/// <param name="characters">The character table.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="characters"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="characters"/> does not have a length of 256.
/// </exception>
public Table(string[] characters)
{
if (characters == null)
throw new ArgumentNullException(nameof(characters));
if (characters.Length != 256)
throw new ArgumentException("Table must contain 256 characters.", nameof(characters));
Characters = characters ?? throw new ArgumentNullException("characters");
}
/// <summary>
/// Decodes the specified value.
/// </summary>
/// <param name="value">The value to be decoded.</param>
/// <returns>A string representing the decoded character.</returns>
public string GetCharacter(byte value) => Characters[value] ?? string.Empty;
/// <summary>
/// Encodes the specified character.
/// </summary>
/// <param name="character">The character to be encoded.</param>
/// <returns>The value of the character if found in the table; otherwise, -1.</returns>
public int GetByte(string character)
{
for (int i = 0; i < Characters.Length; i++)
{
if (Characters[i] == character)
{
return i;
}
}
return -1;
}
/// <summary>
/// Gets the character table.
/// </summary>
public string[] Characters { get; }
}
}
| using System;
namespace GBAHL.Text
{
/// <summary>
/// Represents a table of characters.
/// </summary>
public class Table
{
public Table(string[] characters)
{
if (characters == null)
throw new ArgumentNullException(nameof(characters));
if (characters.Length != 256)
throw new ArgumentException("Table must contain 256 characters.", nameof(characters));
Characters = characters ?? throw new ArgumentNullException("characters");
}
#region Methods
public string GetCharacter(byte value) => Characters[value] ?? string.Empty;
public int GetByte(string character)
{
for (int i = 0; i < Characters.Length; i++)
{
if (Characters[i] == character)
{
return i;
}
}
return -1;
}
#endregion
// TODO: Investigate the best way to represent multiple-byte constants.
// Maybe as an integer? Note that constants are never more than 4 bytes.
public string[] Characters { get; }
}
}
| mit | C# |
8c9d39700d66af8c12ff2a82a46f39a8ea241b19 | Update deprecated code in iOS main entry | smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu | osu.iOS/Application.cs | osu.iOS/Application.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.iOS;
using UIKit;
namespace osu.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
| // 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 UIKit;
namespace osu.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, "GameUIApplication", "AppDelegate");
}
}
}
| mit | C# |
c16dbbf563d4abad8e8de5ee4adad600bba2c2d4 | Update ServerCapabilities type | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/ServerCapabilities.cs | src/PowerShellEditorServices.Protocol/LanguageServer/ServerCapabilities.cs | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class ServerCapabilities
{
public TextDocumentSyncKind? TextDocumentSync { get; set; }
public bool? HoverProvider { get; set; }
public CompletionOptions CompletionProvider { get; set; }
public SignatureHelpOptions SignatureHelpProvider { get; set; }
public bool? DefinitionProvider { get; set; }
public bool? ReferencesProvider { get; set; }
public bool? DocumentHighlightProvider { get; set; }
public bool? DocumentSymbolProvider { get; set; }
public bool? WorkspaceSymbolProvider { get; set; }
public bool? CodeActionProvider { get; set; }
public bool? CodeLensProvider { get; set; }
public bool? DocumentFormattingProvider { get; set; }
public bool? DocumentRangeFormattingProvider { get; set; }
public DocumentOnTypeFormattingOptions DocumentOnTypeFormattingProvider { get; set; }
public bool? RenameProvider { get; set; }
public DocumentLinkOptions DocumentLinkProvider { get; set; }
public ExecuteCommandOptions ExecuteCommandProvider { get; set; }
public object Experimental { get; set; }
}
/// <summary>
/// Execute command options.
/// </summary>
public class ExecuteCommandOptions
{
/// <summary>
/// The commands to be executed on the server.
/// </summary>
public string[] Commands { get; set; }
}
/// <summary>
/// Document link options.
/// </summary>
public class DocumentLinkOptions
{
/// <summary>
/// Document links have a resolve provider.
/// </summary>
public bool? ResolveProvider { get; set; }
}
/// <summary>
/// Options that the server provides for OnTypeFormatting request.
/// </summary>
public class DocumentOnTypeFormattingOptions
{
/// <summary>
/// A character on which formatting should be triggered.
/// </summary>
public string FirstTriggerCharacter { get; set; }
/// <summary>
/// More trigger characters.
/// </summary>
public string[] MoreTriggerCharacters { get; set; }
}
/// <summary>
/// Defines the document synchronization strategies that a server may support.
/// </summary>
public enum TextDocumentSyncKind
{
/// <summary>
/// Indicates that documents should not be synced at all.
/// </summary>
None = 0,
/// <summary>
/// Indicates that document changes are always sent with the full content.
/// </summary>
Full,
/// <summary>
/// Indicates that document changes are sent as incremental changes after
/// the initial document content has been sent.
/// </summary>
Incremental
}
public class CompletionOptions
{
public bool? ResolveProvider { get; set; }
public string[] TriggerCharacters { get; set; }
}
public class SignatureHelpOptions
{
public string[] TriggerCharacters { get; set; }
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class ServerCapabilities
{
public TextDocumentSyncKind? TextDocumentSync { get; set; }
public bool? HoverProvider { get; set; }
public CompletionOptions CompletionProvider { get; set; }
public SignatureHelpOptions SignatureHelpProvider { get; set; }
public bool? DefinitionProvider { get; set; }
public bool? ReferencesProvider { get; set; }
public bool? DocumentHighlightProvider { get; set; }
public bool? DocumentSymbolProvider { get; set; }
public bool? WorkspaceSymbolProvider { get; set; }
public bool? CodeActionProvider { get; set; }
}
/// <summary>
/// Defines the document synchronization strategies that a server may support.
/// </summary>
public enum TextDocumentSyncKind
{
/// <summary>
/// Indicates that documents should not be synced at all.
/// </summary>
None = 0,
/// <summary>
/// Indicates that document changes are always sent with the full content.
/// </summary>
Full,
/// <summary>
/// Indicates that document changes are sent as incremental changes after
/// the initial document content has been sent.
/// </summary>
Incremental
}
public class CompletionOptions
{
public bool? ResolveProvider { get; set; }
public string[] TriggerCharacters { get; set; }
}
public class SignatureHelpOptions
{
public string[] TriggerCharacters { get; set; }
}
}
| mit | C# |
69422ab87558265dfa8bc7e268079e6d1fa27f98 | set copyright to 2017 | wcm-io-devops/aem-manager | AEMManager/Properties/AssemblyInfo.cs | AEMManager/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("AEM Manager")]
[assembly: AssemblyDescription("Taskbar application for managing AEM instances")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("wcm.io")]
[assembly: AssemblyProduct("wcm.io AEM Manager")]
[assembly: AssemblyCopyright("©2010-2017 pro!vision GmbH, wcm.io")]
[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("7eb3bb90-a3f2-4a71-aee0-fbc04cabfb32")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.3.5.0")]
[assembly: AssemblyFileVersion("2.3.5.0")]
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfiguratorAttribute(Watch = true)]
| 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("AEM Manager")]
[assembly: AssemblyDescription("Taskbar application for managing AEM instances")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("wcm.io")]
[assembly: AssemblyProduct("wcm.io AEM Manager")]
[assembly: AssemblyCopyright("©2010-2016 pro!vision GmbH, wcm.io")]
[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("7eb3bb90-a3f2-4a71-aee0-fbc04cabfb32")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.3.5.0")]
[assembly: AssemblyFileVersion("2.3.5.0")]
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfiguratorAttribute(Watch = true)]
| apache-2.0 | C# |
2550e616ca37208a803f5870c57bff86ff549559 | bump version | alecgorge/adzerk-dot-net | Adzerk.Api/Properties/AssemblyInfo.cs | Adzerk.Api/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.11")]
[assembly: AssemblyFileVersion("0.0.0.11")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.10")]
[assembly: AssemblyFileVersion("0.0.0.10")]
| mit | C# |
8780eac1c72873338b6647cb699d7d0163ed986e | Test de Cliente Completo | pablovargan/winforms-ooh4ria | LimpiezasPalmeralTest/ClienteTest.cs | LimpiezasPalmeralTest/ClienteTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PalmeralGenNHibernate.CEN.Default_;
using PalmeralGenNHibernate.EN.Default_;
namespace LimpiezasPalmeralTest
{
[TestClass]
public class ClienteTest
{
private ClienteCEN clienteTest;
[TestInitialize]
public void TestMethod1()
{
clienteTest = new ClienteCEN();
}
[TestMethod]
public void Cli_Registrar()
{
string expected = clienteTest.Crear("99999999Z", "Cliente", "Descripcion", "email@email.com", "Alicante", "Alicante", "España", "Calle", "03339", "665855458");
clienteTest.Eliminar("99999999Z");
Assert.AreEqual("99999999Z", expected);
}
[TestMethod]
public void Cli_RegistarError()
{
try
{
clienteTest.Crear("99999999Z", "Cliente", "Descripcion", "email@email.com", "Alicante", "Alicante", "España", "Calle", "03339", "665855458");
string expected = clienteTest.Crear("99999999Z", "Cliente", "Descripcion", "email@email.com", "Alicante", "Alicante", "España", "Calle", "03339", "665855458");
clienteTest.Eliminar("99999999Z");
Assert.Fail("Excepcion no lanzada");
}
catch (PalmeralGenNHibernate.Exceptions.DataLayerException ex)
{
string expected = "Error in ClienteCAD.";
Assert.AreEqual(ex.Message, expected);
}
}
[TestMethod]
public void Cli_Consultar()
{
ClienteEN expected = clienteTest.ObtenerCliente("99999999Z");
string actual = "Cliente";
Assert.AreEqual(actual, expected.Nombre);
}
[TestMethod]
public void Cli_ConsultarError()
{
try
{
ClienteEN expected = clienteTest.ObtenerCliente(null);
Assert.Fail("Excepcion no lanzada");
}
catch (PalmeralGenNHibernate.Exceptions.DataLayerException ex)
{
string expected = "Error in ClienteCAD.";
Assert.AreEqual(ex.Message, expected);
}
}
[TestCleanup]
public void Disconnect()
{
clienteTest = null;
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LimpiezasPalmeralTest
{
[TestClass]
public class ClienteTest
{
[TestMethod]
public void TestMethod1()
{
}
}
}
| apache-2.0 | C# |
7cc66a2f336d1da21c95a142894a7e09cad9c300 | Update assembly info for development of the next version | nanathan/AltFunding | AltFunding/Properties/AssemblyInfo.cs | AltFunding/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("AltFunding")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AltFunding")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[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("2c84adb4-a8b2-453a-941a-dca4e9383182")]
// 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.2")]
[assembly: AssemblyFileVersion("0.2.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("AltFunding")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AltFunding")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[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("2c84adb4-a8b2-453a-941a-dca4e9383182")]
// 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")]
[assembly: AssemblyFileVersion("0.1.0")]
| mit | C# |
6861b7f9d994ddc3c1a7e9ef046f64447fff32ce | Add credentials class for user authorization | tenevdev/idiot-netmf-sdk | Idiot/Net/Credentials.cs | Idiot/Net/Credentials.cs | using System;
using Microsoft.SPOT;
using System.Text;
using GHIElectronics.NETMF.Net;
namespace Idiot.Net
{
public class Credentials
{
private string username;
private string password;
public Credentials(string username, string password)
{
this.username = username;
this.password = password;
this.AuthorizationHeader = this.toAuthorizationHeader();
}
/// <summary>
/// Basic authorization header value to be used for server authentication
/// </summary>
public string AuthorizationHeader { get; private set; }
private string toAuthorizationHeader()
{
return "Basic " + ConvertBase64.ToBase64String(Encoding.UTF8.GetBytes(this.username + ":" + this.password));
}
}
}
| using System;
using Microsoft.SPOT;
namespace Idiot.Net
{
class Credentials
{
}
}
| mit | C# |
80a1a124071bebe82441e20c8189d19b283e18be | add mahapps xmlns prefix | tipunch74/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,DingpingZhang/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit | MaterialDesignThemes.MahApps/Properties/AssemblyInfo.cs | MaterialDesignThemes.MahApps/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
// 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("MaterialDesignThemes.MahApps")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MaterialDesignThemes.MahApps")]
[assembly: AssemblyCopyright("Copyright © 2015-2016 James Willock, Mulholland Software & Contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.7")]
[assembly: AssemblyFileVersion("0.0.7")]
[assembly: XmlnsPrefix("http://materialdesigninxaml.net/winfx/xaml/themes", "materialDesignMahApps")]
[assembly: XmlnsDefinition("http://materialdesigninxaml.net/winfx/xaml/themes", "MaterialDesignThemes.MahApps")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
// 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("MaterialDesignThemes.MahApps")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MaterialDesignThemes.MahApps")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.6")]
[assembly: AssemblyFileVersion("0.0.6")]
[assembly: XmlnsDefinition("http://materialdesigninxaml.net/winfx/xaml/themes", "MaterialDesignThemes.MahApps")]
| mit | C# |
c3582bed367dfbb602e7abe5f3ca5bf5c7b10ba7 | Fix a bug about Use Grouping working randomnly | Seddryck/NBi,Seddryck/NBi | NBi.UI.Genbi/View/TestSuiteGenerator/TestListControl.cs | NBi.UI.Genbi/View/TestSuiteGenerator/TestListControl.cs | using System;
using System.Linq;
using System.Windows.Forms;
using NBi.UI.Genbi.Presenter;
namespace NBi.UI.Genbi.View.TestSuiteGenerator
{
public partial class TestListControl : UserControl
{
private BindingSource testsSource;
public TestListControl()
{
InitializeComponent();
}
internal void DataBind(TestListPresenter presenter)
{
if (presenter != null)
{
testsSource = new BindingSource(presenter, "Tests");
testsList.DataSource = testsSource;
testsList.DisplayMember = "Title";
testsList.DataBindings.Add("SelectedItem", presenter, "SelectedTest", true, DataSourceUpdateMode.OnPropertyChanged);
testsList.SelectedIndexChanged += (s, args) => testsList.DataBindings["SelectedItem"].WriteValue();
useGrouping.DataBindings.Add("Checked", presenter, "UseGrouping", false, DataSourceUpdateMode.OnPropertyChanged);
progressBarTest.DataBindings.Add("Value", presenter, "Progress", false, DataSourceUpdateMode.OnPropertyChanged);
presenter.GenerationStarted += (sender, e) => testsSource.SuspendBinding();
presenter.GenerationEnded += (sender, e) => testsSource.ResumeBinding();
}
}
private void TestsList_MouseDown(object sender, MouseEventArgs e)
{
//select the item under the mouse pointer
testsList.SelectedIndex = testsList.IndexFromPoint(e.Location);
//If it's a right click (and something is selected) display the pop-up menu
if (e.Button == MouseButtons.Right && testsList.SelectedIndex != -1)
testsListMenu.Show(testsList, e.Location);
}
public ToolStripMenuItem DisplayCommand
{
get { return editTestToolStripMenuItem; }
}
public ToolStripMenuItem DeleteCommand
{
get { return deleteTestToolStripMenuItem; }
}
}
}
| using System;
using System.Linq;
using System.Windows.Forms;
using NBi.UI.Genbi.Presenter;
namespace NBi.UI.Genbi.View.TestSuiteGenerator
{
public partial class TestListControl : UserControl
{
private BindingSource testsSource;
public TestListControl()
{
InitializeComponent();
}
internal void DataBind(TestListPresenter presenter)
{
if (presenter != null)
{
testsSource = new BindingSource(presenter, "Tests");
testsList.DataSource = testsSource;
testsList.DisplayMember = "Title";
testsList.DataBindings.Add("SelectedItem", presenter, "SelectedTest", true, DataSourceUpdateMode.OnPropertyChanged);
testsList.SelectedIndexChanged += (s, args) => testsList.DataBindings["SelectedItem"].WriteValue();
useGrouping.DataBindings.Add("Checked", presenter, "UseGrouping", false, DataSourceUpdateMode.OnValidation);
progressBarTest.DataBindings.Add("Value", presenter, "Progress", false, DataSourceUpdateMode.OnPropertyChanged);
presenter.GenerationStarted += (sender, e) => testsSource.SuspendBinding();
presenter.GenerationEnded += (sender, e) => testsSource.ResumeBinding();
}
}
private void TestsList_MouseDown(object sender, MouseEventArgs e)
{
//select the item under the mouse pointer
testsList.SelectedIndex = testsList.IndexFromPoint(e.Location);
//If it's a right click (and something is selected) display the pop-up menu
if (e.Button == MouseButtons.Right && testsList.SelectedIndex != -1)
testsListMenu.Show(testsList, e.Location);
}
public ToolStripMenuItem DisplayCommand
{
get { return editTestToolStripMenuItem; }
}
public ToolStripMenuItem DeleteCommand
{
get { return deleteTestToolStripMenuItem; }
}
}
}
| apache-2.0 | C# |
c847e51d1d14d02bbe05d925a936a9b5aef0675b | Update RDFOntologyFact.cs | mdesalvo/RDFSharp | RDFSharp/Semantics/OWL/Ontology/Data/RDFOntologyFact.cs | RDFSharp/Semantics/OWL/Ontology/Data/RDFOntologyFact.cs | /*
Copyright 2015-2020 Marco De Salvo
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 RDFSharp.Model;
namespace RDFSharp.Semantics.OWL
{
/// <summary>
/// RDFOntologyFact represents an instance of an ontology class within an ontology data.
/// </summary>
public class RDFOntologyFact : RDFOntologyResource
{
#region Ctors
/// <summary>
/// Default-ctor to build an ontology fact with the given name.
/// </summary>
public RDFOntologyFact(RDFResource factName)
{
if (factName != null)
{
this.Value = factName;
this.PatternMemberID = factName.PatternMemberID;
}
else
{
throw new RDFSemanticsException("Cannot create RDFOntologyFact because given \"factName\" parameter is null.");
}
}
#endregion
}
}
| /*
Copyright 2015-2020 Marco De Salvo
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 RDFSharp.Model;
namespace RDFSharp.Semantics.OWL
{
/// <summary>
/// RDFOntologyFact represents an instance of an ontology class within an ontology data.
/// </summary>
public class RDFOntologyFact : RDFOntologyResource
{
#region Ctors
/// <summary>
/// Default-ctor to build an ontology fact with the given name: in case of a not-blank resource name,<br />
/// the fact will be tagged as instance of built-in class owl:NamedIndividual when added to an ontology.
/// </summary>
public RDFOntologyFact(RDFResource factName)
{
if (factName != null)
{
this.Value = factName;
this.PatternMemberID = factName.PatternMemberID;
}
else
{
throw new RDFSemanticsException("Cannot create RDFOntologyFact because given \"factName\" parameter is null.");
}
}
#endregion
}
} | apache-2.0 | C# |
8dce323b1a7253bc10484ddc6ded59c487089f4d | check for existing record | faithword/IdentityServer3.EntityFramework,IdentityServer/IdentityServer3.EntityFramework,henkmeulekamp/IdentityServer3.EntityFramework,chwilliamson/IdentityServer3.EntityFramework,buybackoff/IdentityServer3.EntityFramework | Source/Core.EntityFramework/Stores/RefreshTokenStore.cs | Source/Core.EntityFramework/Stores/RefreshTokenStore.cs | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* 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.Threading.Tasks;
using Thinktecture.IdentityServer.EntityFramework.Entities;
using Thinktecture.IdentityServer.Core.Models;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.EntityFramework
{
public class RefreshTokenStore : BaseTokenStore<RefreshToken>, IRefreshTokenStore
{
public RefreshTokenStore(OperationalDbContext context, IScopeStore scopeStore, IClientStore clientStore)
: base(context, TokenType.RefreshToken, scopeStore, clientStore)
{
}
public override async Task StoreAsync(string key, RefreshToken value)
{
var token = await context.Tokens.FindAsync(key, tokenType);
if (token == null)
{
token = new Entities.Token
{
Key = key,
SubjectId = value.SubjectId,
ClientId = value.ClientId,
JsonCode = ConvertToJson(value),
TokenType = tokenType
};
context.Tokens.Add(token);
}
token.Expiry = DateTimeOffset.UtcNow.AddSeconds(value.LifeTime);
await context.SaveChangesAsync();
}
}
}
| /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* 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.Threading.Tasks;
using Thinktecture.IdentityServer.EntityFramework.Entities;
using Thinktecture.IdentityServer.Core.Models;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.EntityFramework
{
public class RefreshTokenStore : BaseTokenStore<RefreshToken>, IRefreshTokenStore
{
public RefreshTokenStore(OperationalDbContext context, IScopeStore scopeStore, IClientStore clientStore)
: base(context, TokenType.RefreshToken, scopeStore, clientStore)
{
}
public override async Task StoreAsync(string key, RefreshToken value)
{
var efToken = new Entities.Token
{
Key = key,
SubjectId = value.SubjectId,
ClientId = value.ClientId,
JsonCode = ConvertToJson(value),
Expiry = DateTimeOffset.UtcNow.AddSeconds(value.LifeTime),
TokenType = tokenType
};
context.Tokens.Add(efToken);
await context.SaveChangesAsync();
}
}
}
| apache-2.0 | C# |
344e7dc62aa4a191a2bf7f6851a9df73ea45b417 | Update version numbers and copyright dates in AssemblyInfo.cs files. | eylvisaker/AgateLib | Drivers/OldCode/AgateSDL/Properties/AssemblyInfo.cs | Drivers/OldCode/AgateSDL/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("AgateSDL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AgateSDL")]
[assembly: AssemblyCopyright("Copyright © 2006-9")]
[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("dfd15a81-4bbf-4128-bf33-48df0957439b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DisplayImpl_SDL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DisplayImpl_SDL")]
[assembly: AssemblyCopyright("Copyright © 2006")]
[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("dfd15a81-4bbf-4128-bf33-48df0957439b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
482b1bfa5a1ff003b518f3c9d5c26863bc64d494 | Update IRestAuthenticationTokenProvider.cs | tiksn/TIKSN-Framework | TIKSN.Core/Web/Rest/IRestAuthenticationTokenProvider.cs | TIKSN.Core/Web/Rest/IRestAuthenticationTokenProvider.cs | using System;
using System.Threading.Tasks;
namespace TIKSN.Web.Rest
{
public interface IRestAuthenticationTokenProvider
{
Task<string> GetAuthenticationToken(Guid apiKey);
}
}
| using System;
using System.Threading.Tasks;
namespace TIKSN.Web.Rest
{
public interface IRestAuthenticationTokenProvider
{
Task<string> GetAuthenticationToken(Guid apiKey);
}
} | mit | C# |
b0a8a7fceaf0d926506a3d4c700d5dda43a0932c | check the current count of the semaphore in "AsyncLock" to verify it should be released | bbqchickenrobot/Akavache,akavache/Akavache | src/Akavache.Sqlite3/AsyncLock.cs | src/Akavache.Sqlite3/AsyncLock.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Akavache.Sqlite3.Internal
{
// Straight-up thieved from http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx
public sealed class AsyncLock
{
const int semaphoreMaxCount = 1;
readonly SemaphoreSlim m_semaphore = new SemaphoreSlim(1, semaphoreMaxCount);
readonly Task<IDisposable> m_releaser;
public AsyncLock()
{
m_releaser = Task.FromResult((IDisposable)new Releaser(this));
}
public Task<IDisposable> LockAsync(CancellationToken ct = default(CancellationToken))
{
var wait = m_semaphore.WaitAsync(ct);
// Happy path. We synchronously acquired the lock.
if (wait.IsCompleted && !wait.IsFaulted)
return m_releaser;
return wait
.ContinueWith((_, state) => (IDisposable)state,
m_releaser.Result, ct,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
sealed class Releaser : IDisposable
{
readonly AsyncLock m_toRelease;
internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; }
public void Dispose()
{
if(m_toRelease.m_semaphore.CurrentCount != semaphoreMaxCount)
m_toRelease.m_semaphore.Release();
}
}
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Akavache.Sqlite3.Internal
{
// Straight-up thieved from http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx
public sealed class AsyncLock
{
readonly SemaphoreSlim m_semaphore = new SemaphoreSlim(1, 1);
readonly Task<IDisposable> m_releaser;
public AsyncLock()
{
m_releaser = Task.FromResult((IDisposable)new Releaser(this));
}
public Task<IDisposable> LockAsync(CancellationToken ct = default(CancellationToken))
{
var wait = m_semaphore.WaitAsync(ct);
// Happy path. We synchronously acquired the lock.
if (wait.IsCompleted && !wait.IsFaulted)
return m_releaser;
return wait
.ContinueWith((_, state) => (IDisposable)state,
m_releaser.Result, ct,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
sealed class Releaser : IDisposable
{
readonly AsyncLock m_toRelease;
internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; }
public void Dispose() { m_toRelease.m_semaphore.Release(); }
}
}
} | mit | C# |
e09bc11d08959f9a2ebe512a605322ea9703053d | Fix typo | SaladbowlCreative/LumberjackClient | samples/NLog/Program.cs | samples/NLog/Program.cs | using NLog.Config;
using NLog.Targets.Logstash;
using System;
using System.Threading;
namespace NLog
{
class Program
{
static void Main(string[] args)
{
Setup();
TestLog();
Thread.Sleep(1000);
}
static void Setup()
{
var logstashTarget = new LogstashTarget();
logstashTarget.Host = "localhost";
logstashTarget.Port = 5000;
logstashTarget.Header = "Header";
logstashTarget.Layout = @"${message} ${exception}";
logstashTarget.Footer = "Footer";
var config = new LoggingConfiguration();
config.AddTarget("logstash", logstashTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logstashTarget));
LogManager.Configuration = config;
}
static void TestLog()
{
var logger = LogManager.GetLogger("Test");
logger.Debug("Test Debug Log");
logger.Info("Test Info Log");
logger.Warn("Test Warn Log");
logger.Error(new Exception("Exception Message"), "Test Error Log");
}
}
}
| using NLog.Config;
using NLog.Targets.Logstash;
using System.Threading;
namespace NLog
{
class Program
{
static void Main(string[] args)
{
Setup();
TestLog();
Thread.Sleep(1000);
}
static void Setup()
{
var logstashTarget = new LogstashTarget();
logstashTarget.Host = "localhost";
logstashTarget.Port = 5000;
logstashTarget.Header = "Header";
logstashTarget.Layout = @"${message} ${exception}";
logstashTarget.Footer = "Footer";
var config = new LoggingConfiguration();
config.AddTarget("logstash", logstashTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logstashTarget));
LogManager.Configuration = config;
}
static void TestLog()
{
var logger = LogManager.GetLogger("Test");
logger.Debug("Test Debug Log");
logger.Info("Test Info Log");
logger.Warn("Test Warn Log");
logger.Error("Test Warn Log");
}
}
}
| mit | C# |
f4a1b293db9d18ca0816b6067bbfedf5b1cb0a27 | Change missed exception message to resource. | PCFDev/SNPPlib | SNPPlib/SNPPlib/PagerCollection.cs | SNPPlib/SNPPlib/PagerCollection.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace SNPPlib
{
public class PagerCollection : Collection<string>
{
public PagerCollection()
{
Pagers = new List<string>();
}
internal IList<string> Pagers { get; set; }
public new void Add(string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers.Add(pager);
}
public void AddRange(IEnumerable<string> pagers)
{
foreach (var pager in pagers)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers.Add(pager);
}
}
public override string ToString()
{
return String.Join(", ", Pagers);
}
protected override void InsertItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers.Insert(index, pager);
}
protected override void SetItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers[index] = pager;
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace SNPPlib
{
public class PagerCollection : Collection<string>
{
public PagerCollection()
{
Pagers = new List<string>();
}
internal IList<string> Pagers { get; set; }
public new void Add(string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers.Add(pager);
}
public void AddRange(IEnumerable<string> pagers)
{
foreach (var pager in pagers)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers.Add(pager);
}
}
public override string ToString()
{
return String.Join(", ", Pagers);
}
protected override void InsertItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers.Insert(index, pager);
}
protected override void SetItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers[index] = pager;
}
}
} | mit | C# |
a369ad960eff4ac885c2e3f1029499fc8fa31826 | add options of failed call-back. | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | src/DotNetCore.CAP/CAP.Options.cs | src/DotNetCore.CAP/CAP.Options.cs | using System;
using System.Collections.Generic;
namespace DotNetCore.CAP
{
/// <summary>
/// Represents all the options you can use to configure the system.
/// </summary>
public class CapOptions
{
internal IList<ICapOptionsExtension> Extensions { get; private set; }
/// <summary>
/// Default value for polling delay timeout, in seconds.
/// </summary>
public const int DefaultPollingDelay = 15;
/// <summary>
/// Default processor count to process messages of cap.queue.
/// </summary>
public const int DefaultQueueProcessorCount = 2;
public CapOptions()
{
PollingDelay = DefaultPollingDelay;
QueueProcessorCount = DefaultQueueProcessorCount;
Extensions = new List<ICapOptionsExtension>();
}
/// <summary>
/// Productor job polling delay time. Default is 15 sec.
/// </summary>
public int PollingDelay { get; set; }
/// <summary>
/// Gets or sets the messages queue (Cap.Queue table) processor count.
/// </summary>
public int QueueProcessorCount { get; set; }
/// <summary>
/// Failed messages polling delay time. Default is 3 min.
/// </summary>
public TimeSpan FailedMessageWaitingInterval = TimeSpan.FromMinutes(3);
/// <summary>
/// We’ll invoke this call-back with message type,name,content when requeue failed message.
/// </summary>
public Action<Models.MessageType, string, string> FailedCallback { get; set; }
/// <summary>
/// Registers an extension that will be executed when building services.
/// </summary>
/// <param name="extension"></param>
public void RegisterExtension(ICapOptionsExtension extension)
{
if (extension == null)
throw new ArgumentNullException(nameof(extension));
Extensions.Add(extension);
}
}
} | using System;
using System.Collections.Generic;
namespace DotNetCore.CAP
{
/// <summary>
/// Represents all the options you can use to configure the system.
/// </summary>
public class CapOptions
{
internal IList<ICapOptionsExtension> Extensions { get; private set; }
/// <summary>
/// Default value for polling delay timeout, in seconds.
/// </summary>
public const int DefaultPollingDelay = 8;
public CapOptions()
{
PollingDelay = DefaultPollingDelay;
Extensions = new List<ICapOptionsExtension>();
}
/// <summary>
/// Productor job polling delay time. Default is 5 sec.
/// </summary>
public int PollingDelay { get; set; } = 5;
/// <summary>
/// Failed messages polling delay time. Default is 2 min.
/// </summary>
public TimeSpan FailedMessageWaitingInterval = TimeSpan.FromMinutes(2);
/// <summary>
/// We’ll send a POST request to the URL below with details of any subscribed events.
/// </summary>
public WebHook WebHook => throw new NotSupportedException();
/// <summary>
/// Registers an extension that will be executed when building services.
/// </summary>
/// <param name="extension"></param>
public void RegisterExtension(ICapOptionsExtension extension)
{
if (extension == null)
throw new ArgumentNullException(nameof(extension));
Extensions.Add(extension);
}
}
public class WebHook
{
public string PayloadUrl { get; set; }
public string Secret { get; set; }
}
} | mit | C# |
361c0c14088c573a65199e19c5ec74a8acccb2de | Update ReactionCallback.cs | foxbot/Discord.Addons.InteractiveCommands,foxbot/Discord.Addons.InteractiveCommands | src/Discord.Addons.InteractiveCommands/ReactionCallback.cs | src/Discord.Addons.InteractiveCommands/ReactionCallback.cs | using System;
using System.Threading.Tasks;
namespace Discord.Addons.InteractiveCommands
{
public class ReactionCallback
{
public bool ResumeAfterExecution { get; set; }
public Func<IUser, Task> Function { get; set; }
}
}
| using System;
using System.Threading.Tasks;
namespace Discord.Addons.InteractiveCommands
{
public class ReactionCallback
{
public bool ResumeAfterExecution { get; set; }
public Func<IUser, Task> Callback { get; set; }
}
}
| isc | C# |
7fdbc76618b351d249a6e3079c0d90f79c816c3b | Update IStartupTask.cs (#4465) | dotnet/orleans,Liversage/orleans,dotnet/orleans,ReubenBond/orleans,galvesribeiro/orleans,yevhen/orleans,veikkoeeva/orleans,amccool/orleans,sergeybykov/orleans,ElanHasson/orleans,Liversage/orleans,hoopsomuah/orleans,Liversage/orleans,waynemunro/orleans,ibondy/orleans,brhinescot/orleans,waynemunro/orleans,pherbel/orleans,brhinescot/orleans,SoftWar1923/orleans,benjaminpetit/orleans,amccool/orleans,ElanHasson/orleans,hoopsomuah/orleans,brhinescot/orleans,yevhen/orleans,ibondy/orleans,jthelin/orleans,pherbel/orleans,galvesribeiro/orleans,amccool/orleans,jason-bragg/orleans,SoftWar1923/orleans,sergeybykov/orleans | src/Orleans.Runtime.Abstractions/Lifecycle/IStartupTask.cs | src/Orleans.Runtime.Abstractions/Lifecycle/IStartupTask.cs | using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime
{
/// <summary>
/// Defines an action to be taken after silo startup.
/// </summary>
public interface IStartupTask
{
/// <summary>
/// Called after the silo has started.
/// </summary>
/// <param name="cancellationToken">The cancellation token which is canceled when the method must abort.</param>
/// <returns>A <see cref="Task"/> representing the work performed.</returns>
Task Execute(CancellationToken cancellationToken);
}
}
| using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime
{
/// <summary>
/// Defines an action to be taken during silo startup.
/// </summary>
public interface IStartupTask
{
/// <summary>
/// Called after the silo has started.
/// </summary>
/// <param name="cancellationToken">The cancellation token which is canceled when the method must abort.</param>
/// <returns>A <see cref="Task"/> representing the work performed.</returns>
Task Execute(CancellationToken cancellationToken);
}
}
| mit | C# |
6a2341741c436bd9e626ca5ed1449f4a7806319f | Use CodeBase instead of Location | reportunit/reportunit,ekirmayer/reportunit,ekirmayer/reportunit,ekirmayer/reportunit,reportunit/reportunit,reportunit/reportunit | ReportUnitTest/JUnitTests.cs | ReportUnitTest/JUnitTests.cs | using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
namespace ReportUnitTest
{
[TestFixture]
public class JUnitTests
{
public static string ExecutableDir;
public static string ResourcesDir;
[OneTimeSetUp]
public static void Setup()
{
var assemblyDir = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)).LocalPath;
if (assemblyDir == null)
{
throw new Exception("Failed to get assembly path");
}
TestContext.Progress.WriteLine("Assembly: " + assemblyDir);
ResourcesDir = Path.Combine(assemblyDir, "..", "..", "Resources");
if (!Directory.Exists(ResourcesDir))
{
throw new Exception("Can't find Resources folder");
}
TestContext.Progress.WriteLine("Resources: " + ResourcesDir);
ExecutableDir = Path.Combine(assemblyDir, "..", "..", "..", "ReportUnit", "bin");
if (!Directory.Exists(ExecutableDir))
{
throw new Exception("Can't find ReportUnit folder");
}
TestContext.Progress.WriteLine("Executable: " + ExecutableDir);
}
[Test]
public void Test()
{
var filename = Path.Combine(ExecutableDir, "ReportUnit.exe");
var proc = System.Diagnostics.Process.Start(filename, "test_junit_01.xml");
if (proc == null)
{
throw new Exception("Failed to start");
}
if (!proc.WaitForExit(5000))
{
throw new Exception("Timeout");
}
if (proc.ExitCode != 0)
{
throw new Exception("Exit code " + proc.ExitCode);
}
}
}
}
| using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
namespace ReportUnitTest
{
[TestFixture]
public class JUnitTests
{
public static string ExecutableDir;
public static string ResourcesDir;
[OneTimeSetUp]
public static void Setup()
{
//
// NOTE
// ================================================================
// Those who are failing to run these tests with ReSharper Unit
// Test Runner, please disable the "shadow copy" of the assembly
// in the ReSharper menu.
//
// More details:
// http://stackoverflow.com/questions/16231084/resharper-runs-unittest-from-different-location
//
var assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (assemblyDir == null)
{
throw new Exception("Failed to get assembly path");
}
TestContext.Progress.WriteLine("Assembly: " + assemblyDir);
ResourcesDir = Path.Combine(assemblyDir, "..", "..", "Resources");
if (!Directory.Exists(ResourcesDir))
{
throw new Exception("Can't find Resources folder");
}
TestContext.Progress.WriteLine("Resources: " + ResourcesDir);
ExecutableDir = Path.Combine(assemblyDir, "..", "..", "..", "ReportUnit", "bin");
if (!Directory.Exists(ExecutableDir))
{
throw new Exception("Can't find ReportUnit folder");
}
TestContext.Progress.WriteLine("Executable: " + ExecutableDir);
}
[Test]
public void Test()
{
var filename = Path.Combine(ExecutableDir, "ReportUnit.exe");
var proc = System.Diagnostics.Process.Start(filename, "test_junit_01.xml");
if (proc == null)
{
throw new Exception("Failed to start");
}
if (!proc.WaitForExit(5000))
{
throw new Exception("Timeout");
}
if (proc.ExitCode != 0)
{
throw new Exception("Exit code " + proc.ExitCode);
}
}
}
}
| mit | C# |
25569c0bfbd85afc702130ff1fd6ad4979efc001 | Remove Record Requests proxy | mattherman/MbDotNet,mattherman/MbDotNet | MbDotNet/Models/Imposters/Imposter.cs | MbDotNet/Models/Imposters/Imposter.cs | using MbDotNet.Enums;
using MbDotNet.Exceptions;
using Newtonsoft.Json;
namespace MbDotNet.Models.Imposters
{
public abstract class Imposter
{
/// <summary>
/// The port the imposter is set up to accept requests on.
/// </summary>
[JsonProperty(PropertyName = "port", DefaultValueHandling = DefaultValueHandling.Ignore)]
public int Port { get; private set; }
/// <summary>
/// The protocol the imposter is set up to accept requests through.
/// </summary>
[JsonProperty("protocol")]
public string Protocol { get; private set; }
/// <summary>
/// Optional name for the imposter, used in the logs.
/// </summary>
[JsonProperty("name")]
public string Name { get; private set; }
internal void SetDynamicPort(int port)
{
if (Port != default(int))
{
throw new MountebankException("Cannot change imposter port once it has been set.");
}
Port = port;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Set as virtual for testing purposes")]
public Imposter(int? port, Protocol protocol, string name)
{
if (port.HasValue)
{
Port = port.Value;
}
Protocol = protocol.ToString().ToLower();
Name = name;
}
}
}
| using MbDotNet.Enums;
using MbDotNet.Exceptions;
using Newtonsoft.Json;
namespace MbDotNet.Models.Imposters
{
public abstract class Imposter
{
/// <summary>
/// The port the imposter is set up to accept requests on.
/// </summary>
[JsonProperty(PropertyName = "port", DefaultValueHandling = DefaultValueHandling.Ignore)]
public int Port { get; private set; }
/// <summary>
/// The protocol the imposter is set up to accept requests through.
/// </summary>
[JsonProperty("protocol")]
public string Protocol { get; private set; }
/// <summary>
/// Optional name for the imposter, used in the logs.
/// </summary>
[JsonProperty("name")]
public string Name { get; private set; }
/// <summary>
/// Adds mock verification support by remembering the requests made to this imposter. Note that this represents a memory leak for any long running mb process, as requests are never forgotten.
/// </summary>
[JsonProperty("recordRequests")]
public bool RecordRequests { get; set; }
internal void SetDynamicPort(int port)
{
if (Port != default(int))
{
throw new MountebankException("Cannot change imposter port once it has been set.");
}
Port = port;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Set as virtual for testing purposes")]
public Imposter(int? port, Protocol protocol, string name)
{
if (port.HasValue)
{
Port = port.Value;
}
Protocol = protocol.ToString().ToLower();
Name = name;
}
}
}
| mit | C# |
cc10760510f0a0262c42039573160be6f6e3bb29 | Fix warning message | pflugs30/nunit,danielmarbach/nunit,ChrisMaddock/nunit,Suremaker/nunit,JustinRChou/nunit,Therzok/nunit,agray/nunit,JohanO/nunit,akoeplinger/nunit,appel1/nunit,cPetru/nunit-params,zmaruo/nunit,pcalin/nunit,jeremymeng/nunit,dicko2/nunit,acco32/nunit,elbaloo/nunit,modulexcite/nunit,jnm2/nunit,agray/nunit,acco32/nunit,NikolayPianikov/nunit,pcalin/nunit,Green-Bug/nunit,ArsenShnurkov/nunit,ggeurts/nunit,Green-Bug/nunit,passaro/nunit,JustinRChou/nunit,akoeplinger/nunit,mjedrzejek/nunit,michal-franc/nunit,ChrisMaddock/nunit,michal-franc/nunit,JohanO/nunit,jhamm/nunit,Suremaker/nunit,Green-Bug/nunit,ArsenShnurkov/nunit,mikkelbu/nunit,zmaruo/nunit,mikkelbu/nunit,jadarnel27/nunit,danielmarbach/nunit,ArsenShnurkov/nunit,danielmarbach/nunit,OmicronPersei/nunit,zmaruo/nunit,pflugs30/nunit,NarohLoyahl/nunit,jeremymeng/nunit,agray/nunit,pcalin/nunit,dicko2/nunit,OmicronPersei/nunit,elbaloo/nunit,mjedrzejek/nunit,passaro/nunit,michal-franc/nunit,appel1/nunit,NarohLoyahl/nunit,jadarnel27/nunit,JohanO/nunit,nivanov1984/nunit,jeremymeng/nunit,acco32/nunit,modulexcite/nunit,jnm2/nunit,Therzok/nunit,nunit/nunit,passaro/nunit,NikolayPianikov/nunit,ggeurts/nunit,Therzok/nunit,nunit/nunit,jhamm/nunit,nivanov1984/nunit,NarohLoyahl/nunit,elbaloo/nunit,akoeplinger/nunit,jhamm/nunit,dicko2/nunit,modulexcite/nunit,cPetru/nunit-params | src/NUnitFramework/testdata/TimeoutFixture.cs | src/NUnitFramework/testdata/TimeoutFixture.cs | // ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// 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.
// ***********************************************************************
#if !PORTABLE
using System;
using NUnit.Framework;
namespace NUnit.TestData
{
[TestFixture]
public class TimeoutFixture
{
public bool TearDownWasRun;
[SetUp]
public void SetUp()
{
TearDownWasRun = false;
}
[TearDown]
public void TearDown()
{
TearDownWasRun = true;
}
[Test, Timeout(50)]
public void InfiniteLoopWith50msTimeout()
{
while (true) { }
}
}
public class TimeoutFixtureWithTimeoutInSetUp : TimeoutFixture
{
[SetUp]
public bool SetUp2()
{
while (true) { }
}
[Test, Timeout(50)]
public void Test1() { }
}
public class TimeoutFixtureWithTimeoutInTearDown : TimeoutFixture
{
[TearDown]
public void TearDown2()
{
while (true) { }
}
[Test, Timeout(50)]
public void Test1() { }
}
[TestFixture, Timeout(50)]
public class TimeoutFixtureWithTimeoutOnFixture
{
[Test]
public void Test1() { }
[Test]
public void Test2WithInfiniteLoop()
{
while (true) { }
}
[Test]
public void Test3() { }
}
}
#endif
| // ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// 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.
// ***********************************************************************
#if !PORTABLE
using System;
using NUnit.Framework;
namespace NUnit.TestData
{
[TestFixture]
public class TimeoutFixture
{
public bool TearDownWasRun;
[SetUp]
public void SetUp()
{
TearDownWasRun = false;
}
[TearDown]
public void TearDown()
{
TearDownWasRun = true;
}
[Test, Timeout(50)]
public void InfiniteLoopWith50msTimeout()
{
while (true) { }
}
}
public class TimeoutFixtureWithTimeoutInSetUp : TimeoutFixture
{
[SetUp]
public bool SetUp()
{
while (true) { }
}
[Test, Timeout(50)]
public void Test1() { }
}
public class TimeoutFixtureWithTimeoutInTearDown : TimeoutFixture
{
[TearDown]
public void TearDown()
{
while (true) { }
}
[Test, Timeout(50)]
public void Test1() { }
}
[TestFixture, Timeout(50)]
public class TimeoutFixtureWithTimeoutOnFixture
{
[Test]
public void Test1() { }
[Test]
public void Test2WithInfiniteLoop()
{
while (true) { }
}
[Test]
public void Test3() { }
}
}
#endif
| mit | C# |
ea5159aa1bae4ac42fdc8a1c4644c6414fb90d1e | Remove F# leftovers | OrleansContrib/Orleankka,mhertis/Orleankka,yevhen/Orleankka,yevhen/Orleankka,mhertis/Orleankka,OrleansContrib/Orleankka | Source/Orleankka/IActorGrain.cs | Source/Orleankka/IActorGrain.cs | using System.Threading.Tasks;
using Orleans;
namespace Orleankka
{
public interface IActor
{
Task Autorun();
Task<object> Receive(object message);
Task ReceiveVoid(object message);
Task Notify(object message);
}
public interface IActorGrain : IActor, IGrainWithStringKey, IRemindable
{}
}
| using System.Threading.Tasks;
using Orleans;
namespace Orleankka
{
public interface IActor
{
Task Autorun();
Task<object> Receive(object message);
Task ReceiveVoid(object message);
Task Notify(object message);
}
public interface IActorGrain : IActor, IGrainWithStringKey, IRemindable
{}
/// <summary>
/// This for F# api
/// </summary>
/// <typeparam name="TMessage">Type of DU</typeparam>
public interface IActorGrain<TMessage> : IActorGrain
{}
}
| apache-2.0 | C# |
23bfaa5e315c0e4f1276d8f9701005d303903037 | Add tag to 3.0.2 | dazerdude/SharpDX,dazerdude/SharpDX,mrvux/SharpDX,sharpdx/SharpDX,sharpdx/SharpDX,mrvux/SharpDX,andrewst/SharpDX,mrvux/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,dazerdude/SharpDX,andrewst/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,andrewst/SharpDX,sharpdx/SharpDX,dazerdude/SharpDX | Source/SharedAssemblyInfo.cs | Source/SharedAssemblyInfo.cs | // Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("3.0.2")]
[assembly:AssemblyFileVersion("3.0.2")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
#if STORE_APP
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)]
[assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
#endif | // Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("3.0.1")]
[assembly:AssemblyFileVersion("3.0.1")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
#if STORE_APP
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)]
[assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
#endif | mit | C# |
3880008478d7e7f14f88d3d758d1d5bf9fe11718 | Update Program.cs | WeihanLi/SparkTodo,WeihanLi/SparkTodo,WeihanLi/SparkTodo,WeihanLi/SparkTodo | SparkTodo.API/Program.cs | SparkTodo.API/Program.cs | using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Prometheus.DotNetRuntime;
using SparkTodo.API;
using SparkTodo.Models;
DotNetRuntimeStatsBuilder.Customize()
.WithContentionStats()
.WithGcStats()
.WithThreadPoolStats()
.StartCollecting();
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder.UseStartup<Startup>();
})
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.AddJsonConsole();
})
.Build();
using (var serviceScope = host.Services.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetRequiredService<SparkTodoDbContext>();
await dbContext.Database.EnsureCreatedAsync();
//init Database,you can add your init data here
var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<UserAccount>>();
var email = "weihanli@outlook.com";
if (await userManager.FindByEmailAsync(email) == null)
{
await userManager.CreateAsync(new UserAccount
{
UserName = email,
Email = email
}, "Test1234");
}
}
await host.RunAsync();
| using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Prometheus.DotNetRuntime;
using SparkTodo.Models;
namespace SparkTodo.API
{
public class Program
{
/// <summary>
/// program entry
/// </summary>
/// <param name="args">arguments</param>
public static async Task Main(string[] args)
{
DotNetRuntimeStatsBuilder.Customize()
.WithContentionStats()
.WithGcStats()
.WithThreadPoolStats()
.StartCollecting();
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder.UseStartup<Startup>();
})
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.AddJsonConsole();
})
.Build();
using (var serviceScope = host.Services.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetRequiredService<SparkTodoDbContext>();
await dbContext.Database.EnsureCreatedAsync();
//init Database,you can add your init data here
var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<UserAccount>>();
var email = "weihanli@outlook.com";
if (await userManager.FindByEmailAsync(email) == null)
{
await userManager.CreateAsync(new UserAccount
{
UserName = email,
Email = email
}, "Test1234");
}
}
await host.RunAsync();
}
}
}
| mit | C# |
e6ab5f266f0587c2daa6b21bbc32d78f3512d067 | fix NRE in JsonWebKeySet | IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel2,IdentityModel/IdentityModel | src/Jwk/JsonWebKeySet.cs | src/Jwk/JsonWebKeySet.cs | //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the 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 System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace IdentityModel.Jwk
{
/// <summary>
/// Contains a collection of <see cref="JsonWebKey"/> that can be populated from a json string.
/// </summary>
public class JsonWebKeySet
{
/// <summary>
/// Initializes an new instance of <see cref="JsonWebKeySet"/>.
/// </summary>
public JsonWebKeySet()
{ }
/// <summary>
/// Initializes an new instance of <see cref="JsonWebKeySet"/> from a json string.
/// </summary>
/// <param name="json">a json string containing values.</param>
/// <exception cref="ArgumentNullException">if 'json' is null or whitespace.</exception>
public JsonWebKeySet(string json)
{
if (string.IsNullOrWhiteSpace(json)) throw new ArgumentNullException(nameof(json));
var jwebKeys = JsonSerializer.Deserialize<JsonWebKeySet>(json);
Keys = jwebKeys.Keys;
}
/// <summary>
/// A list of JSON web keys
/// </summary>
[JsonPropertyName("keys")]
public List<JsonWebKey> Keys { get; set; } = new();
}
} | //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the 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 System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace IdentityModel.Jwk
{
/// <summary>
/// Contains a collection of <see cref="JsonWebKey"/> that can be populated from a json string.
/// </summary>
public class JsonWebKeySet
{
private List<JsonWebKey> _keys = new List<JsonWebKey>();
/// <summary>
/// Initializes an new instance of <see cref="JsonWebKeySet"/>.
/// </summary>
public JsonWebKeySet()
{ }
/// <summary>
/// Initializes an new instance of <see cref="JsonWebKeySet"/> from a json string.
/// </summary>
/// <param name="json">a json string containing values.</param>
/// <exception cref="ArgumentNullException">if 'json' is null or whitespace.</exception>
public JsonWebKeySet(string json)
{
if (string.IsNullOrWhiteSpace(json)) throw new ArgumentNullException(nameof(json));
var jwebKeys = JsonSerializer.Deserialize<JsonWebKeySet>(json);
Keys = jwebKeys.Keys;
}
/// <summary>
/// A list of JSON web keys
/// </summary>
[JsonPropertyName("keys")]
public List<JsonWebKey> Keys { get; set; }
}
} | apache-2.0 | C# |
3a25fec81fd1dd829b664bb7ba2616dbb3ed34e9 | Replace usage of Photo to IBrowseableItem in ThumbnailCommand.cs | mono/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,Sanva/f-spot,dkoeb/f-spot,Sanva/f-spot,mono/f-spot,dkoeb/f-spot,Yetangitu/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,dkoeb/f-spot,GNOME/f-spot,NguyenMatthieu/f-spot,mono/f-spot,mans0954/f-spot,dkoeb/f-spot,GNOME/f-spot,nathansamson/F-Spot-Album-Exporter,GNOME/f-spot,Sanva/f-spot,Yetangitu/f-spot,mans0954/f-spot,GNOME/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,mans0954/f-spot,Sanva/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mono/f-spot,mono/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,GNOME/f-spot,dkoeb/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,mono/f-spot,Yetangitu/f-spot,NguyenMatthieu/f-spot | src/ThumbnailCommand.cs | src/ThumbnailCommand.cs | using System;
using Gtk;
using FSpot;
using FSpot.Utils;
using FSpot.UI.Dialog;
public class ThumbnailCommand {
private Gtk.Window parent_window;
public ThumbnailCommand (Gtk.Window parent_window)
{
this.parent_window = parent_window;
}
public bool Execute (IBrowsableItem [] photos)
{
ProgressDialog progress_dialog = null;
var loader = ThumbnailLoader.Default;
if (photos.Length > 1) {
progress_dialog = new ProgressDialog (Mono.Unix.Catalog.GetString ("Updating Thumbnails"),
ProgressDialog.CancelButtonType.Stop,
photos.Length, parent_window);
}
int count = 0;
foreach (IBrowsableItem photo in photos) {
if (progress_dialog != null
&& progress_dialog.Update (String.Format (Mono.Unix.Catalog.GetString ("Updating picture \"{0}\""), photo.Name)))
break;
foreach (IBrowsableItemVersion version in photo.Versions) {
loader.Request (version.Uri, ThumbnailSize.Large, 10);
}
count++;
}
if (progress_dialog != null)
progress_dialog.Destroy ();
return true;
}
}
| using System;
using Gtk;
using FSpot;
using FSpot.Utils;
using FSpot.UI.Dialog;
public class ThumbnailCommand {
private Gtk.Window parent_window;
public ThumbnailCommand (Gtk.Window parent_window)
{
this.parent_window = parent_window;
}
public bool Execute (Photo [] photos)
{
ProgressDialog progress_dialog = null;
var loader = ThumbnailLoader.Default;
if (photos.Length > 1) {
progress_dialog = new ProgressDialog (Mono.Unix.Catalog.GetString ("Updating Thumbnails"),
ProgressDialog.CancelButtonType.Stop,
photos.Length, parent_window);
}
int count = 0;
foreach (Photo p in photos) {
if (progress_dialog != null
&& progress_dialog.Update (String.Format (Mono.Unix.Catalog.GetString ("Updating picture \"{0}\""), p.Name)))
break;
foreach (uint version_id in p.VersionIds) {
loader.Request (p.VersionUri (version_id), ThumbnailSize.Large, 10);
}
count++;
}
if (progress_dialog != null)
progress_dialog.Destroy ();
return true;
}
}
| mit | C# |
15e67e171ae5b33f6406a285225b0498328b2e99 | Remove use of obsolete function | dgnorth/DriftUe4Plugin,dgnorth/DriftUe4Plugin,dgnorth/DriftUe4Plugin,dgnorth/DriftUe4Plugin | Source/DriftUe4PluginServer.Target.cs | Source/DriftUe4PluginServer.Target.cs | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DriftUe4PluginServerTarget : TargetRules
{
public DriftUe4PluginServerTarget(TargetInfo Target)
{
Type = TargetType.Server;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
OutExtraModuleNames.Add("DriftUe4Plugin");
}
}
| // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DriftUe4PluginServerTarget : TargetRules
{
public DriftUe4PluginServerTarget(TargetInfo Target)
{
Type = TargetType.Server;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
OutExtraModuleNames.Add("DriftUe4Plugin");
}
public override bool GetSupportedPlatforms(ref List<UnrealTargetPlatform> OutPlatforms)
{
// It is valid for only server platforms
return UnrealBuildTool.UnrealBuildTool.GetAllServerPlatforms(ref OutPlatforms, false);
}
}
| mit | C# |
bd570c8d0853e48bb4c6107ae4586ba28ab1b94a | Enable RuntimeError() to have variable length arguments. | AIWolfSharp/AIWolfCore,AIWolfSharp/AIWolf_NET | AIWolfLib/Error.cs | AIWolfLib/Error.cs | //
// Error.cs
//
// Copyright (c) 2016 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Diagnostics;
namespace AIWolf.Lib
{
/// <summary>
/// Error handling class.
/// </summary>
public static class Error
{
/// <summary>
/// Writes an error message, then throws exception on debug.
/// </summary>
/// <param name="message">Error message.</param>
public static void RuntimeError(params string[] messages)
{
string message = "";
if (messages.Length > 0)
{
message = messages[0];
}
ThrowException(message);
foreach (var m in messages)
{
Console.Error.WriteLine(m);
}
}
[Conditional("DEBUG")]
static void ThrowException(string message)
{
throw new AIWolfRuntimeException(message);
}
}
}
| //
// Error.cs
//
// Copyright (c) 2016 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Diagnostics;
namespace AIWolf.Lib
{
/// <summary>
/// Error handling class.
/// </summary>
public static class Error
{
/// <summary>
/// Writes an error message, then throws exception on debug.
/// </summary>
/// <param name="message">Error message.</param>
public static void RuntimeError(string message)
{
Console.Error.WriteLine(message);
ThrowException(message);
}
[Conditional("DEBUG")]
static void ThrowException(string message)
{
throw new AIWolfRuntimeException(message);
}
}
}
| mit | C# |
e641c7fb20d5ea3e91703e07b6d49963e3e02d5c | Update C# mops to use 32bit values like the rest of the tests. | tkob/parrot,tewk/parrot-select,tkob/parrot,youprofit/parrot,gagern/parrot,tkob/parrot,FROGGS/parrot,FROGGS/parrot,parrot/parrot,tewk/parrot-select,tkob/parrot,gagern/parrot,gitster/parrot,gitster/parrot,youprofit/parrot,parrot/parrot,gitster/parrot,tewk/parrot-select,FROGGS/parrot,gagern/parrot,gagern/parrot,youprofit/parrot,FROGGS/parrot,gagern/parrot,fernandobrito/parrot,parrot/parrot,youprofit/parrot,FROGGS/parrot,tkob/parrot,parrot/parrot,FROGGS/parrot,fernandobrito/parrot,tewk/parrot-select,tewk/parrot-select,parrot/parrot,tkob/parrot,FROGGS/parrot,fernandobrito/parrot,fernandobrito/parrot,gagern/parrot,gitster/parrot,gitster/parrot,fernandobrito/parrot,gitster/parrot,gagern/parrot,youprofit/parrot,youprofit/parrot,fernandobrito/parrot,tewk/parrot-select,tkob/parrot,youprofit/parrot,FROGGS/parrot,tkob/parrot,fernandobrito/parrot,gitster/parrot,tewk/parrot-select,youprofit/parrot | examples/mops/mops.cs | examples/mops/mops.cs | // created on 03/03/2002 at 15:12
using System;
class App {
public static int Main(String[] args) {
int i1, i5;
// int i2 = 0;
int i3 = 1;
int i4 = 100000000;
DateTime start, end;
double n1, n2;
Console.WriteLine("Iterations: {0}", i4);
// IL_0038: ldloc.3
// IL_0039: ldloc.2
// IL_003a: sub
// IL_003b: stloc.3
// IL_003c: ldloc.3
// IL_003d: ldc.i4.0
// IL_003e: conv.i8
// IL_003f: bgt.s IL_0038
//
// Insane, isn't it?
i1 = 8;
i5 = i4 * i1;
Console.WriteLine("Estimated ops: {0}", i5);
start = DateTime.Now;
REDO:
i4 = i4 - i3;
if (i4 > 0)
goto REDO;
end = DateTime.Now;
n2 = (end-start).TotalMilliseconds;
n2 /= 1000; // Milliseconds to seconds
Console.WriteLine("Elapsed Time: {0}", n2);
n1 = i5;
n1 /= n2;
n2 = 1000000.0;
n1 /= n2;
Console.WriteLine("M op/s: {0}", n1);
return 0;
}
}
| // created on 03/03/2002 at 15:12
using System;
class App {
public static int Main(String[] args) {
long i1, i5;
// int i2 = 0;
long i3 = 1;
long i4 = 100000000;
DateTime start, end;
double n1, n2;
Console.WriteLine("Iterations: {0}", i4);
// IL_0038: ldloc.3
// IL_0039: ldloc.2
// IL_003a: sub
// IL_003b: stloc.3
// IL_003c: ldloc.3
// IL_003d: ldc.i4.0
// IL_003e: conv.i8
// IL_003f: bgt.s IL_0038
//
// Insane, isn't it?
i1 = 8;
i5 = i4 * i1;
Console.WriteLine("Estimated ops: {0}", i5);
start = DateTime.Now;
REDO:
i4 = i4 - i3;
if (i4 > 0)
goto REDO;
end = DateTime.Now;
n2 = (end-start).TotalMilliseconds;
n2 /= 1000; // Milliseconds to seconds
Console.WriteLine("Elapsed Time: {0}", n2);
n1 = i5;
n1 /= n2;
n2 = 1000000.0;
n1 /= n2;
Console.WriteLine("M op/s: {0}", n1);
return 0;
}
}
| artistic-2.0 | C# |
e4626186cce28e7bc90fefc37fde06c236952717 | Switch to 1.1.5 | rbouallou/Zebus,AtwooTM/Zebus,Abc-Arbitrage/Zebus,biarne-a/Zebus | src/SharedVersionInfo.cs | src/SharedVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.1.5")]
[assembly: AssemblyFileVersion("1.1.5")]
[assembly: AssemblyInformationalVersion("1.1.5")] | using System.Reflection;
[assembly: AssemblyVersion("1.1.4")]
[assembly: AssemblyFileVersion("1.1.4")]
[assembly: AssemblyInformationalVersion("1.1.4")] | mit | C# |
392a527f982dd1fdb43071a1df622b214f434104 | Switch to version 1.3.4 | Abc-Arbitrage/Zebus,rbouallou/Zebus,AtwooTM/Zebus,biarne-a/Zebus | src/SharedVersionInfo.cs | src/SharedVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.3.4")]
[assembly: AssemblyFileVersion("1.3.4")]
[assembly: AssemblyInformationalVersion("1.3.4")]
| using System.Reflection;
[assembly: AssemblyVersion("1.3.3")]
[assembly: AssemblyFileVersion("1.3.3")]
[assembly: AssemblyInformationalVersion("1.3.3")]
| mit | C# |
c301fee2aa2a09c3fc016c9524fe5623efd4b411 | Add OcclusionInfo.ToString method | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Viewer/src/occlusion/OcclusionInfo.cs | Viewer/src/occlusion/OcclusionInfo.cs | using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct OcclusionInfo {
public static readonly int SizeInBytes = 2 * sizeof(float);
public static readonly int PackedSizeInBytes = sizeof(uint);
public float Front { get; }
public float Back { get; }
public OcclusionInfo(float front, float back) {
Front = front;
Back = back;
}
public static OcclusionInfo Zero {
get {
return new OcclusionInfo(0, 0);
}
}
public static OcclusionInfo operator *(float f, OcclusionInfo info) {
return new OcclusionInfo(f * info.Front, f * info.Back);
}
public static OcclusionInfo operator +(OcclusionInfo info1, OcclusionInfo info2) {
return new OcclusionInfo(info1.Front + info2.Front, info1.Back + info2.Back);
}
public static uint Pack(OcclusionInfo occlusionInfo) {
return IntegerUtils.Pack(
IntegerUtils.ToUShort(occlusionInfo.Front),
IntegerUtils.ToUShort(occlusionInfo.Back));
}
public static OcclusionInfo Unpack(uint packedOcclusionInfo) {
IntegerUtils.Unpack(packedOcclusionInfo, out ushort front, out ushort back);
return new OcclusionInfo(IntegerUtils.FromUShort(front), IntegerUtils.FromUShort(back));
}
public static OcclusionInfo[] UnpackArray(uint[] packedArray) {
if (packedArray == null) {
return null;
}
int length = packedArray.Length;
OcclusionInfo[] array = new OcclusionInfo[length];
for (int i = 0; i < length; ++i) {
array[i] = Unpack(packedArray[i]);
}
return array;
}
public static uint[] PackArray(OcclusionInfo[] array) {
if (array == null) {
return null;
}
int length = array.Length;
uint[] packedArray = new uint[length];
for (int i = 0; i < length; ++i) {
packedArray[i] = Pack(array[i]);
}
return packedArray;
}
override public string ToString() {
return String.Format("OcclusionInfo[front = {0}, back = {1}]", Front, Back);
}
}
| using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct OcclusionInfo {
public static readonly int SizeInBytes = 2 * sizeof(float);
public static readonly int PackedSizeInBytes = sizeof(uint);
public float Front { get; }
public float Back { get; }
public OcclusionInfo(float front, float back) {
Front = front;
Back = back;
}
public static OcclusionInfo Zero {
get {
return new OcclusionInfo(0, 0);
}
}
public static OcclusionInfo operator *(float f, OcclusionInfo info) {
return new OcclusionInfo(f * info.Front, f * info.Back);
}
public static OcclusionInfo operator +(OcclusionInfo info1, OcclusionInfo info2) {
return new OcclusionInfo(info1.Front + info2.Front, info1.Back + info2.Back);
}
public static uint Pack(OcclusionInfo occlusionInfo) {
return IntegerUtils.Pack(
IntegerUtils.ToUShort(occlusionInfo.Front),
IntegerUtils.ToUShort(occlusionInfo.Back));
}
public static OcclusionInfo Unpack(uint packedOcclusionInfo) {
IntegerUtils.Unpack(packedOcclusionInfo, out ushort front, out ushort back);
return new OcclusionInfo(IntegerUtils.FromUShort(front), IntegerUtils.FromUShort(back));
}
public static OcclusionInfo[] UnpackArray(uint[] packedArray) {
if (packedArray == null) {
return null;
}
int length = packedArray.Length;
OcclusionInfo[] array = new OcclusionInfo[length];
for (int i = 0; i < length; ++i) {
array[i] = Unpack(packedArray[i]);
}
return array;
}
public static uint[] PackArray(OcclusionInfo[] array) {
if (array == null) {
return null;
}
int length = array.Length;
uint[] packedArray = new uint[length];
for (int i = 0; i < length; ++i) {
packedArray[i] = Pack(array[i]);
}
return packedArray;
}
}
| mit | C# |
89a165eaec3ffa40ce65c32b1763574adad28f35 | Add ForContext<T>(ILog, T) overload | vostok/core | Vostok.Core/Logging/ILogExtensions.cs | Vostok.Core/Logging/ILogExtensions.cs | using System;
using System.Collections.Generic;
namespace Vostok.Logging
{
public static class ILogExtensions
{
public static ILog ForContext<T>(this ILog log)
{
return log.ForContext(typeof(T));
}
public static ILog ForContext<T>(this ILog log, T _)
{
return log.ForContext(typeof(T));
}
public static ILog ForContext(this ILog log, Type source)
{
return log.ForContext("SourceContext", source.FullName);
}
public static ILog ForContext(this ILog log, string name, object value)
{
return new LogWithProperties(log, new Dictionary<string, object> {{name, value}});
}
public static ILog ForContext(this ILog log, IReadOnlyDictionary<string, object> properties)
{
return new LogWithProperties(log, properties);
}
private class LogWithProperties : ILog
{
private readonly ILog log;
private readonly IReadOnlyDictionary<string, object> properties;
public LogWithProperties(ILog log, IReadOnlyDictionary<string, object> properties)
{
this.log = log;
this.properties = properties;
}
public void Log(LogEvent logEvent)
{
foreach (var kvp in properties)
{
logEvent.AddPropertyIfAbsent(kvp.Key, kvp.Value);
}
log.Log(logEvent);
}
public bool IsEnabledFor(LogLevel level)
{
return log.IsEnabledFor(level);
}
}
}
} | using System;
using System.Collections.Generic;
namespace Vostok.Logging
{
public static class ILogExtensions
{
public static ILog ForContext<T>(this ILog log)
{
return log.ForContext(typeof(T));
}
public static ILog ForContext(this ILog log, Type source)
{
return log.ForContext("SourceContext", source.FullName);
}
public static ILog ForContext(this ILog log, string name, object value)
{
return new LogWithProperties(log, new Dictionary<string, object> {{name, value}});
}
public static ILog ForContext(this ILog log, IReadOnlyDictionary<string, object> properties)
{
return new LogWithProperties(log, properties);
}
private class LogWithProperties : ILog
{
private readonly ILog log;
private readonly IReadOnlyDictionary<string, object> properties;
public LogWithProperties(ILog log, IReadOnlyDictionary<string, object> properties)
{
this.log = log;
this.properties = properties;
}
public void Log(LogEvent logEvent)
{
foreach (var kvp in properties)
{
logEvent.AddPropertyIfAbsent(kvp.Key, kvp.Value);
}
log.Log(logEvent);
}
public bool IsEnabledFor(LogLevel level)
{
return log.IsEnabledFor(level);
}
}
}
} | mit | C# |
66b8219acdbc7f89353b7625d33b700f843a6500 | Update version to 2.0.0 | synel/syndll2 | Syndll2/Properties/AssemblyInfo.cs | Syndll2/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Syndll2")]
[assembly: AssemblyDescription("Synel Communications Protocol Client Library")]
[assembly: AssemblyCompany("Synel Industries Ltd.")]
[assembly: AssemblyProduct("Syndll2")]
[assembly: AssemblyCopyright("Copyright © 2014, Synel Industries Ltd.")]
[assembly: ComVisible(false)]
[assembly: Guid("a7fe65a7-0b61-4ea1-81c0-adc5a037ea17")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: InternalsVisibleTo("Syndll2.Tests, PublicKey=" +
"00240000048000009400000006020000002400005253413100040000010001000f0f0c410cd366" +
"72c6264d60b03c1099ab0c910081744c6199219f003d9ae1baca1f0e4b6cb637901a10a9eabbad" +
"a806bfa1645acdddd52b1749d8135b96987bfae82d25d746a25e02a83dec271c5bba92ba243dab" +
"180786452edc1045cd2004744804247b2d1dd9f724a6224f29adfe9bc10155136f6be404457629" +
"4722ffaa")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Syndll2")]
[assembly: AssemblyDescription("Synel Communications Protocol Client Library")]
[assembly: AssemblyCompany("Synel Industries Ltd.")]
[assembly: AssemblyProduct("Syndll2")]
[assembly: AssemblyCopyright("Copyright © 2014, Synel Industries Ltd.")]
[assembly: ComVisible(false)]
[assembly: Guid("a7fe65a7-0b61-4ea1-81c0-adc5a037ea17")]
[assembly: AssemblyVersion("1.0.0.*")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: InternalsVisibleTo("Syndll2.Tests, PublicKey=" +
"00240000048000009400000006020000002400005253413100040000010001000f0f0c410cd366" +
"72c6264d60b03c1099ab0c910081744c6199219f003d9ae1baca1f0e4b6cb637901a10a9eabbad" +
"a806bfa1645acdddd52b1749d8135b96987bfae82d25d746a25e02a83dec271c5bba92ba243dab" +
"180786452edc1045cd2004744804247b2d1dd9f724a6224f29adfe9bc10155136f6be404457629" +
"4722ffaa")]
| mit | C# |
794d5413426660f4a974b7ef16fb5e604ca2d11e | Update AssumeRole.cs | awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples | dotnetv3/STS/AssumeRole/AssumeRoleExample/AssumeRole.cs | dotnetv3/STS/AssumeRole/AssumeRoleExample/AssumeRole.cs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using System;
using System.Threading.Tasks;
namespace AssumeRoleExample
{
class AssumeRole
{
/// <summary>
/// This example shows how to use the AWS Security Token
/// Service (AWS STS) to assume an IAM role.
///
/// NOTE: It is important that the role that will be assumed has a
/// trust relationship with the account that will assume the role.
///
/// Before you run the example, you need to create the role you want to
/// assume and have it trust the IAM account that will assume that role.
///
/// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
/// for help in working with roles.
/// </summary>
private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2;
static async Task Main()
{
// Create the SecurityToken client and then display the identity of the
// default user.
var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";
var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);
// Get and display the information about the identity of the default user.
var callerIdRequest = new GetCallerIdentityRequest();
var caller = await client.GetCallerIdentityAsync(callerIdRequest);
Console.WriteLine($"Original Caller: {caller.Arn}");
// Create the request to use with the AssumeRoleAsync call.
var assumeRoleReq = new AssumeRoleRequest() {
DurationSeconds = 1600,
RoleSessionName = "Session1",
RoleArn = roleArnToAssume
};
var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);
// Now create a new client based on the credentials of the caller assuming the role.
var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials);
// Get and display information about the caller that has assumed the defined role.
var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest);
Console.WriteLine($"AssumedRole Caller: {caller2.Arn}");
}
}
}
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using System;
using System.Threading.Tasks;
namespace AssumeRoleExample
{
class AssumeRole
{
/// <summary>
/// This example shows how to use the AWS Security Token
/// Service (AWS STS) to assume an IAM role.
///
/// NOTE: It is important that the role that will be assumed has a
/// trust relationship with the account that will assume the role.
///
/// Before you run the example, you need to create the role you want to
/// assume and have it trust the IAM account that will assume that role.
///
/// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
/// for help in working with roles.
/// </summary>
private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2;
static async Task Main()
{
// Create the SecurityToken client and then display the identity of the
// default user.
var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";
var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);
// Get and display the information about the identity of the default user.
var callerIdRequest = new GetCallerIdentityRequest();
var caller = await client.GetCallerIdentityAsync(callerIdRequest);
Console.WriteLine($"Original Caller: {caller.Arn}");
// Create the request to use with the AssumeRoleAsync call.
var assumeRoleReq = new AssumeRoleRequest() {
DurationSeconds = 1600,
RoleSessionName = "Session1",
RoleArn = roleArnToAssume
};
var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);
// Now create a new client based on the credentials of the caller assuming the role.
var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials);
// Get and display information about the caller that has assumed the defined role.
var caller2 = await client.GetCallerIdentityAsync(callerIdRequest);
Console.WriteLine($"AssumedRole Caller: {caller2.Arn}");
}
}
}
| apache-2.0 | C# |
3c9a0e8143230c5b4639bf3906d3e02eb898e674 | Add beginnings of a method to parse TMD files | Figglewatts/LBD2OBJ | LBD2OBJ/Program.cs | LBD2OBJ/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using LBD2OBJ.Types;
namespace LBD2OBJ
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("LBD2OBJ - Made by Figglewatts 2015");
foreach (string arg in args)
{
if (Path.GetExtension(arg).ToLower().Equals("tmd"))
{
// convert from tmd
}
else if (Path.GetExtension(arg).ToLower().Equals("lbd"))
{
// convert from lbd
}
else
{
Console.WriteLine("Invalid input file. Extension: {0} not recognized.", Path.GetExtension(arg));
}
}
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
public static void ConvertTMD(string path)
{
Console.WriteLine("Converting TMD...");
TMD tmd;
bool fixP; // if true, pointers are fixed i.e. non-relative
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
tmd.header = readHeader(b);
fixP = (tmd.header.flags & 1) == 1 ? true : false;
tmd.objTable = new OBJECT[tmd.header.numObjects];
for (int i = 0; i < tmd.header.numObjects; i++)
{
tmd.objTable[i] = readObject(b);
}
}
}
private static TMDHEADER readHeader(BinaryReader b)
{
TMDHEADER tmdHeader;
tmdHeader.ID = b.ReadUInt32();
tmdHeader.flags = b.ReadUInt32();
tmdHeader.numObjects = b.ReadUInt32();
return tmdHeader;
}
private static OBJECT readObject(BinaryReader b)
{
OBJECT obj;
obj.vertTop = b.ReadUInt32();
obj.numVerts = b.ReadUInt32();
obj.normTop = b.ReadUInt32();
obj.numNorms = b.ReadUInt32();
obj.primTop = b.ReadUInt32();
obj.numPrims = b.ReadUInt32();
obj.scale = b.ReadInt32();
return obj;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJ
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
1912ec9d98a341c5827c71b1e6c278bd32055372 | Remove unused namespace. | EVAST9919/osu-framework,default0/osu-framework,naoey/osu-framework,ppy/osu-framework,NeoAdonis/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,Nabile-Rahmani/osu-framework,RedNesto/osu-framework,ppy/osu-framework,peppy/osu-framework,NeoAdonis/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,naoey/osu-framework,RedNesto/osu-framework,default0/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,paparony03/osu-framework | SampleGame/SampleGame.cs | SampleGame/SampleGame.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 OpenTK;
using OpenTK.Graphics;
using osu.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Drawables;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace osu.Desktop
{
class SampleGame : Game
{
public override void Load()
{
base.Load();
Box box;
Add(box = new Box()
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(150, 150),
Colour = Color4.Tomato
});
box.RotateTo(360 * 10, 60000);
}
}
}
| //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 OpenTK;
using OpenTK.Graphics;
using osu.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Drawables;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
namespace osu.Desktop
{
class SampleGame : Game
{
public override void Load()
{
base.Load();
Box box;
Add(box = new Box()
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(150, 150),
Colour = Color4.Tomato
});
box.RotateTo(360 * 10, 60000);
}
}
}
| mit | C# |
5d585fe85fd58a74381e7eea9c7d630a9f612dfd | Remove VisibleCharacters from ICharacterRepository | ethanmoffat/EndlessClient | EOLib/Domain/Character/ICharacterRepository.cs | EOLib/Domain/Character/ICharacterRepository.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
namespace EOLib.Domain.Character
{
public interface ICharacterRepository
{
ICharacter ActiveCharacter { get; set; }
}
public interface ICharacterProvider
{
ICharacter ActiveCharacter { get; }
}
public class CharacterRepository : ICharacterRepository, ICharacterProvider
{
public ICharacter ActiveCharacter { get; set; }
public List<ICharacter> VisibleCharacters { get; set; }
public CharacterRepository()
{
VisibleCharacters = new List<ICharacter>(64);
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
namespace EOLib.Domain.Character
{
public interface ICharacterRepository
{
ICharacter ActiveCharacter { get; set; }
List<ICharacter> VisibleCharacters { get; set; }
}
public interface ICharacterProvider
{
ICharacter ActiveCharacter { get; }
IReadOnlyList<ICharacter> VisibleCharacters { get; }
}
public class CharacterRepository : ICharacterRepository, ICharacterProvider
{
public ICharacter ActiveCharacter { get; set; }
public List<ICharacter> VisibleCharacters { get; set; }
IReadOnlyList<ICharacter> ICharacterProvider.VisibleCharacters { get { return VisibleCharacters; } }
public CharacterRepository()
{
VisibleCharacters = new List<ICharacter>(64);
}
}
}
| mit | C# |
1caadc0950a06e789c6d63ff93f7823e138b8467 | Add UpsertDocument validations, close #13 | kotorihq/kotori-core | KotoriCore/Commands/Document/UpsertDocument.cs | KotoriCore/Commands/Document/UpsertDocument.cs | using System.Collections.Generic;
using KotoriCore.Helpers;
namespace KotoriCore.Commands
{
/// <summary>
/// Upsert document.
/// </summary>
public class UpsertDocument : Command
{
/// <summary>
/// Gets the instance.
/// </summary>
/// <value>The instance.</value>
public string Instance { get; }
/// <summary>
/// Gets the project identifier.
/// </summary>
/// <value>The project identifier.</value>
public string ProjectId { get; }
/// <summary>
/// Gets the identifier.
/// </summary>
/// <value>The identifier.</value>
public string Identifier { get; }
/// <summary>
/// Gets the content.
/// </summary>
/// <value>The content.</value>
public string Content { get; }
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Commands.UpsertDocument"/> class.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="projectId">Project identifier.</param>
/// <param name="identifier">Identifier.</param>
/// <param name="content">Content.</param>
public UpsertDocument(string instance, string projectId, string identifier, string content)
{
Instance = instance;
ProjectId = projectId;
Identifier = identifier;
Content = content;
}
/// <summary>
/// Validates the command.
/// </summary>
/// <returns>The validation results.</returns>
public override IEnumerable<ValidationResult> Validate()
{
if (string.IsNullOrEmpty(Instance))
yield return new ValidationResult("Instance must be set.");
if (string.IsNullOrEmpty(ProjectId))
yield return new ValidationResult("Project Id must be set.");
if (string.IsNullOrEmpty(Identifier))
yield return new ValidationResult("Identifier must be set.");
if (string.IsNullOrEmpty(Content))
yield return new ValidationResult("Content must be set.");
}
}
}
| using System.Collections.Generic;
using KotoriCore.Helpers;
namespace KotoriCore.Commands
{
/// <summary>
/// Upsert document.
/// </summary>
public class UpsertDocument : Command
{
/// <summary>
/// Gets the instance.
/// </summary>
/// <value>The instance.</value>
public string Instance { get; }
/// <summary>
/// Gets the project identifier.
/// </summary>
/// <value>The project identifier.</value>
public string ProjectId { get; }
/// <summary>
/// Gets the identifier.
/// </summary>
/// <value>The identifier.</value>
public string Identifier { get; }
/// <summary>
/// Gets the content.
/// </summary>
/// <value>The content.</value>
public string Content { get; }
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Commands.UpsertDocument"/> class.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="projectId">Project identifier.</param>
/// <param name="identifier">Identifier.</param>
/// <param name="content">Content.</param>
public UpsertDocument(string instance, string projectId, string identifier, string content)
{
Instance = instance;
ProjectId = projectId;
Identifier = identifier;
Content = content;
}
/// <summary>
/// Validates the command.
/// </summary>
/// <returns>The validation results.</returns>
public override IEnumerable<ValidationResult> Validate()
{
// TODO
return null;
}
}
}
| mit | C# |
98bc99b630bac82d7c52dba84bf41e94618764a3 | Update types to align with Lib. | BibleBot/BibleBot,BibleBot/BibleBot,BibleBot/BibleBot | src/BibleBot.AutomaticServices/Utils.cs | src/BibleBot.AutomaticServices/Utils.cs | /*
* Copyright (C) 2016-2021 Kerygma Digital Co.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at https://mozilla.org/MPL/2.0/.
*/
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using BibleBot.AutomaticServices.Models;
using BibleBot.Lib;
namespace BibleBot.AutomaticServices
{
public class Utils
{
public enum Colors
{
NORMAL_COLOR = 6709986,
ERROR_COLOR = 16723502
}
public static string Version = "9.2-beta";
public InternalEmbed Embedify(string title, string description, bool isError)
{
return Embedify(null, title, description, isError, null);
}
public InternalEmbed Embedify(string author, string title, string description, bool isError, string copyright)
{
string footerText = $"BibleBot v{Utils.Version} by Kerygma Digital";
var embed = new InternalEmbed();
embed.Title = title;
embed.Color = isError ? (uint)Colors.ERROR_COLOR : (uint)Colors.NORMAL_COLOR;
embed.Footer = new Footer();
embed.Footer.Text = copyright != null ? $"{copyright}\n{footerText}" : footerText;
embed.Footer.IconURL = "https://i.imgur.com/hr4RXpy.png";
if (description != null)
{
embed.Description = description;
}
if (author != null)
{
embed.Author = new Author
{
Name = author
};
}
return embed;
}
}
}
| /*
* Copyright (C) 2016-2021 Kerygma Digital Co.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at https://mozilla.org/MPL/2.0/.
*/
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using BibleBot.AutomaticServices.Models;
using BibleBot.Lib;
namespace BibleBot.AutomaticServices
{
public class Utils
{
public enum Colors
{
NORMAL_COLOR = 6709986,
ERROR_COLOR = 16723502
}
public static string Version = "9.2-beta";
public InternalEmbed Embedify(string title, string description, bool isError)
{
return Embedify(null, title, description, isError, null);
}
public InternalEmbed Embedify(string author, string title, string description, bool isError, string copyright)
{
string footerText = $"BibleBot v{Utils.Version} by Kerygma Digital";
var embed = new InternalEmbed();
embed.Title = title;
embed.Color = isError ? (int)Colors.ERROR_COLOR : (int)Colors.NORMAL_COLOR;
embed.Footer = new Footer();
embed.Footer.Text = copyright != null ? $"{copyright}\n{footerText}" : footerText;
embed.Footer.IconURL = "https://i.imgur.com/hr4RXpy.png";
if (description != null)
{
embed.Description = description;
}
if (author != null)
{
embed.Author = new Author
{
Name = author
};
}
return embed;
}
}
}
| mpl-2.0 | C# |
1cf3f61d2b2c6ad51a006bc4204c1dd0761b3a7e | Allow publish without outputting a .md file | bendetat/GitReleaseNotes,JakeGinnivan/GitReleaseNotes,bendetat/GitReleaseNotes,GitTools/GitReleaseNotes,JakeGinnivan/GitReleaseNotes,theleancoder/GitReleaseNotes,JakeGinnivan/GitReleaseNotes,MacDennis76/GitReleaseNotes,GitTools/GitReleaseNotes,theleancoder/GitReleaseNotes,MacDennis76/GitReleaseNotes | src/GitReleaseNotes/ArgumentVerifier.cs | src/GitReleaseNotes/ArgumentVerifier.cs | using System;
namespace GitReleaseNotes
{
public class ArgumentVerifier
{
public static bool VerifyArguments(GitReleaseNotesArguments arguments)
{
if (arguments.IssueTracker == null)
{
Console.WriteLine("The IssueTracker argument must be provided, see help (/?) for possible options");
{
return false;
}
}
if ((string.IsNullOrEmpty(arguments.OutputFile) || !arguments.OutputFile.EndsWith(".md")) && !arguments.Publish)
{
Console.WriteLine("Specify an output file (*.md) [/OutputFile ...]");
{
return false;
}
}
return true;
}
}
} | using System;
namespace GitReleaseNotes
{
public class ArgumentVerifier
{
public static bool VerifyArguments(GitReleaseNotesArguments arguments)
{
if (arguments.IssueTracker == null)
{
Console.WriteLine("The IssueTracker argument must be provided, see help (/?) for possible options");
{
return false;
}
}
if (string.IsNullOrEmpty(arguments.OutputFile) || !arguments.OutputFile.EndsWith(".md"))
{
Console.WriteLine("Specify an output file (*.md) [/OutputFile ...]");
{
return false;
}
}
return true;
}
}
} | mit | C# |
52a47349d440ecc0df950fe5d30916c45df99e3f | Move logic to constructor | blorgbeard/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,picklesdoc/pickles,dirkrombauts/pickles,blorgbeard/pickles,blorgbeard/pickles,magicmonty/pickles,dirkrombauts/pickles,blorgbeard/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,magicmonty/pickles,magicmonty/pickles,picklesdoc/pickles,dirkrombauts/pickles,magicmonty/pickles,ludwigjossieaux/pickles | src/Pickles/Pickles/LanguageServices.cs | src/Pickles/Pickles/LanguageServices.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.Linq;
using Gherkin3;
namespace PicklesDoc.Pickles
{
public class LanguageServices
{
private readonly string language;
private readonly GherkinDialectProvider dialectProvider;
public LanguageServices(Configuration configuration)
: this(configuration.Language)
{
}
public LanguageServices(string language = "en")
{
this.language = string.IsNullOrWhiteSpace(language) ? "en" : language;
this.dialectProvider = new GherkinDialectProvider();
this.whenStepKeywordsLazy = new Lazy<string[]>(() => this.GetLanguage().WhenStepKeywords.Select(s => s.Trim()).ToArray());
}
private readonly Lazy<string[]> whenStepKeywordsLazy;
public string[] WhenStepKeywords
{
get
{
return this.whenStepKeywordsLazy.Value;
}
}
public string[] GivenStepKeywords { get { return this.GetLanguage().GivenStepKeywords; } }
public string[] ThenStepKeywords { get { return this.GetLanguage().ThenStepKeywords; } }
public string[] AndStepKeywords { get { return this.GetLanguage().AndStepKeywords; } }
public string[] ButStepKeywords { get { return this.GetLanguage().ButStepKeywords; } }
private string[] GetBackgroundKeywords()
{
return this.GetLanguage().BackgroundKeywords;
}
public string GetKeyword(string key)
{
var keywords = this.GetBackgroundKeywords();
return keywords.FirstOrDefault();
}
private GherkinDialect GetLanguage()
{
string l = this.language;
return this.dialectProvider.GetDialect(l, null);
}
}
} | #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.Linq;
using Gherkin3;
namespace PicklesDoc.Pickles
{
public class LanguageServices
{
private readonly string language;
private readonly GherkinDialectProvider dialectProvider;
public LanguageServices(Configuration configuration)
: this(configuration.Language)
{
}
public LanguageServices(string language = "en")
{
this.language = language;
this.dialectProvider = new GherkinDialectProvider();
this.whenStepKeywordsLazy = new Lazy<string[]>(() => this.GetLanguage().WhenStepKeywords.Select(s => s.Trim()).ToArray());
}
private readonly Lazy<string[]> whenStepKeywordsLazy;
public string[] WhenStepKeywords
{
get
{
return this.whenStepKeywordsLazy.Value;
}
}
public string[] GivenStepKeywords { get { return this.GetLanguage().GivenStepKeywords; } }
public string[] ThenStepKeywords { get { return this.GetLanguage().ThenStepKeywords; } }
public string[] AndStepKeywords { get { return this.GetLanguage().AndStepKeywords; } }
public string[] ButStepKeywords { get { return this.GetLanguage().ButStepKeywords; } }
private string[] GetBackgroundKeywords()
{
return this.GetLanguage().BackgroundKeywords;
}
public string GetKeyword(string key)
{
var keywords = this.GetBackgroundKeywords();
return keywords.FirstOrDefault();
}
private GherkinDialect GetLanguage()
{
string l = string.IsNullOrWhiteSpace(this.language) ? "en" : this.language;
return this.dialectProvider.GetDialect(l, null);
}
}
} | apache-2.0 | C# |
10287c9ca1600384b781295a9261cbb730b48e3e | Add missing values in `FilePurpose` | stripe/stripe-dotnet | src/Stripe.net/Constants/FilePurpose.cs | src/Stripe.net/Constants/FilePurpose.cs | namespace Stripe
{
public static class FilePurpose
{
public const string AdditionalVerification = "additional_verification";
public const string BusinessIcon = "business_icon";
public const string BusinessLogo = "business_logo";
public const string CustomerSignature = "customer_signature";
public const string DisputeEvidence = "dispute_evidence";
public const string DocumentProviderIdentityDocument = "document_provider_identity_document";
public const string FinanceReportRun = "finance_report_run";
public const string IdentityDocument = "identity_document";
public const string IncorporationArticle = "incorporation_article";
public const string IncorporationDocument = "incorporation_document";
public const string PaymentProviderTransfer = "payment_provider_transfer";
public const string PciDocument = "pci_document";
public const string ProductFeed = "product_feed";
public const string SigmaScheduledQuery = "sigma_scheduled_query";
public const string TaxDocumentUserUpload = "tax_document_user_upload";
}
}
| namespace Stripe
{
public static class FilePurpose
{
public const string AdditionalVerification = "additional_verification";
public const string BusinessLogo = "business_logo";
public const string DisputeEvidence = "dispute_evidence";
public const string IdentityDocument = "identity_document";
public const string IncorporationArticle = "incorporation_article";
public const string IncorporationDocument = "incorporation_document";
public const string PaymentProviderTransfer = "payment_provider_transfer";
public const string ProductFeed = "product_feed";
}
}
| apache-2.0 | C# |
0746a03023e06bb66abd87aa6cd52124173c4c1a | set default database name | LeedsSharp/Twitter-Quiz,LeedsSharp/Twitter-Quiz | src/TwitterQuiz/RavenSessionProvider.cs | src/TwitterQuiz/RavenSessionProvider.cs | using System.Configuration;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Database.Server;
namespace TwitterQuiz
{
public class RavenSessionProvider
{
private static DocumentStore _documentStore;
public bool Embeddable { get; set; }
public bool SessionInitialized { get; set; }
public static DocumentStore DocumentStore
{
get { return (_documentStore ?? (_documentStore = CreateDocumentStore())); }
}
private static DocumentStore CreateDocumentStore()
{
var store = new DocumentStore
{
Url = ConfigurationManager.AppSettings["RAVEN_URI"],
DefaultDatabase = ConfigurationManager.AppSettings["RAVEN_Database"],
ApiKey = ConfigurationManager.AppSettings["RAVEN_APIKEY"]
};
store.Initialize();
return store;
}
public static DocumentStore EmbeddableDocumentStore
{
get { return (_documentStore ?? (_documentStore = CreateEmbeddableDocumentStore())); }
}
private static DocumentStore CreateEmbeddableDocumentStore()
{
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8082);
var store = new EmbeddableDocumentStore
{
DataDirectory = "App_Data",
UseEmbeddedHttpServer = true,
Configuration = { Port = 8082 },
DefaultDatabase = "PubQuiziminator"
};
store.Initialize();
return store;
}
}
} | using System.Configuration;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Database.Server;
namespace TwitterQuiz
{
public class RavenSessionProvider
{
private static DocumentStore _documentStore;
public bool Embeddable { get; set; }
public bool SessionInitialized { get; set; }
public static DocumentStore DocumentStore
{
get { return (_documentStore ?? (_documentStore = CreateDocumentStore())); }
}
private static DocumentStore CreateDocumentStore()
{
var store = new DocumentStore
{
Url = ConfigurationManager.AppSettings["RAVEN_URI"],
DefaultDatabase = ConfigurationManager.AppSettings["RAVEN_Database"],
ApiKey = ConfigurationManager.AppSettings["RAVEN_APIKEY"]
};
store.Initialize();
return store;
}
public static DocumentStore EmbeddableDocumentStore
{
get { return (_documentStore ?? (_documentStore = CreateEmbeddableDocumentStore())); }
}
private static DocumentStore CreateEmbeddableDocumentStore()
{
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8082);
var store = new EmbeddableDocumentStore
{
DataDirectory = "App_Data",
UseEmbeddedHttpServer = true,
Configuration = { Port = 8082 }
};
store.Initialize();
return store;
}
}
} | unlicense | C# |
2e240620033b9b4783f69ca4f16ffdb1547a833f | add feature to browser | wangkanai/Detection | src/Wangkanai.Browser/Models/Browser.cs | src/Wangkanai.Browser/Models/Browser.cs | namespace Wangkanai.Browser
{
public class Browser
{
public string Name { get; set; }
public string Maker { get; set; }
public BrowserType Type { get; set; }
public byte Bits { get; set; }
public string Version { get; set; }
public Feature Feature { get; set; }
}
} | namespace Wangkanai.Browser
{
public class Browser
{
public string Name { get; set; }
public string Maker { get; set; }
public BrowserType Type { get; set; }
public byte Bits { get; set; }
public string Version { get; set; }
}
} | apache-2.0 | C# |
083e4335a903053c0b1a23041bd5f5a6cbf6bfc6 | Add Ids to footer links | martincostello/website,martincostello/website,martincostello/website,martincostello/website | src/Website/Views/Shared/_Footer.cshtml | src/Website/Views/Shared/_Footer.cshtml | @model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git-commit" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a id="link-git-branch" href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
| @model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
| apache-2.0 | C# |
39a0199bd7df5b332f2fa54b885372e912f9a4cb | add Post function | kheiakiyama/speech-eng-functions | Questions/run.csx | Questions/run.csx | #r "System.Configuration"
#load "../QuestionEntity.csx"
using System.Net;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("ResultCount function processed a request.");
if (req.Method == HttpMethod.Get)
return await Get(req, log);
else if (req.Method == HttpMethod.Post)
return await Post(req, log);
else
return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation");
}
private static async Task<HttpResponseMessage> Get(HttpRequestMessage req, TraceWriter log)
{
string id = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
.Value;
dynamic data = await req.Content.ReadAsAsync<object>();
id = id ?? data?.id;
if (id == null)
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a id on the query string or in the request body");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["speechengfunction_STORAGE"]);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("sentences");
TableOperation retrieveOperation = TableOperation.Retrieve<QuestionEntity>("speech-eng", id);
TableResult retrievedResult = table.Execute(retrieveOperation);
if (retrievedResult.Result == null)
return req.CreateResponse(HttpStatusCode.InternalServerError, "This is a bug, maybe..");
var question = ((QuestionEntity)retrievedResult.Result);
log.Info(question.RowKey);
return req.CreateResponse(HttpStatusCode.OK, new {
sentence = question.Sentence,
total = question.ResultCount,
correct = question.CorrectCount
});
}
private static async Task<HttpResponseMessage> Post(HttpRequestMessage req, TraceWriter log)
{
string id = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
.Value;
string sentence = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "sentence", true) == 0)
.Value;
dynamic data = await req.Content.ReadAsAsync<object>();
id = id ?? data?.id;
sentence = sentence ?? data?.sentence;
if (id == null || sentence == null)
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a id and sentence on the query string or in the request body");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["speechengfunction_STORAGE"]);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("sentences");
TableOperation retrieveOperation = TableOperation.Retrieve<QuestionEntity>("speech-eng", id);
TableResult retrievedResult = table.Execute(retrieveOperation);
if (retrievedResult.Result == null)
return req.CreateResponse(HttpStatusCode.InternalServerError, "This is a bug, maybe..");
var question = ((QuestionEntity)retrievedResult.Result);
log.Info(question.RowKey);
question.ResultCount = question.ResultCount + 1;
if (question.Sentence == sentence)
question.CorrectCount = question.CorrectCount + 1;
TableOperation updateOperation = TableOperation.Replace(question);
table.Execute(updateOperation);
return req.CreateResponse(HttpStatusCode.OK, new {
});
} | #r "System.Configuration"
#load "../QuestionEntity.csx"
using System.Net;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("ResultCount function processed a request.");
if (req.Method == HttpMethod.Get)
return await Get(req, log);
else
return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation");
}
private static async Task<HttpResponseMessage> Get(HttpRequestMessage req, TraceWriter log)
{
string id = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
.Value;
dynamic data = await req.Content.ReadAsAsync<object>();
id = id ?? data?.id;
if (id == null)
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a id on the query string or in the request body");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["speechengfunction_STORAGE"]);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("sentences");
TableOperation retrieveOperation = TableOperation.Retrieve<QuestionEntity>("speech-eng", id);
TableResult retrievedResult = table.Execute(retrieveOperation);
if (retrievedResult.Result == null)
return req.CreateResponse(HttpStatusCode.InternalServerError, "This is a bug, maybe..");
var issue = ((QuestionEntity)retrievedResult.Result);
log.Info(issue.RowKey);
return req.CreateResponse(HttpStatusCode.OK, new {
sentence = issue.Sentence,
total = issue.ResultCount,
correct = issue.CorrectCount
});
} | mit | C# |
3e6e1e983fa300685557324c8834057e8f5d3169 | Make Redis test run well in parallel | SaladbowlCreative/TrackableData,SaladLab/TrackableData,SaladLab/TrackableData,SaladbowlCreative/TrackableData | plugins/TrackableData.Redis.Tests/Redis.cs | plugins/TrackableData.Redis.Tests/Redis.cs | using StackExchange.Redis;
using System;
using System.Configuration;
namespace TrackableData.Redis.Tests
{
public class Redis : IDisposable
{
public ConnectionMultiplexer Connection { get; private set; }
public IDatabase Db
{
get { return Connection.GetDatabase(0); }
}
public Redis()
{
var cstr = ConfigurationManager.ConnectionStrings["TestRedis"].ConnectionString;
Connection = ConnectionMultiplexer.ConnectAsync(cstr + ",allowAdmin=true").Result;
}
public void Dispose()
{
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
}
}
| using StackExchange.Redis;
using System;
using System.Configuration;
namespace TrackableData.Redis.Tests
{
public class Redis : IDisposable
{
public ConnectionMultiplexer Connection { get; private set; }
public IDatabase Db
{
get { return Connection.GetDatabase(0); }
}
public Redis()
{
var cstr = ConfigurationManager.ConnectionStrings["TestRedis"].ConnectionString;
Connection = ConnectionMultiplexer.ConnectAsync(cstr + ",allowAdmin=true").Result;
var server = Connection.GetServer(Connection.GetEndPoints()[0]);
server.FlushDatabase(0);
}
public void Dispose()
{
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
}
}
| mit | C# |
957ac5fa728bdf1daefcd85e53f6cf22d75bd4e3 | Remove Pre RS4 compatability code | File-New-Project/EarTrumpet | EarTrumpet/DataModel/DefaultEndPoint.cs | EarTrumpet/DataModel/DefaultEndPoint.cs | using EarTrumpet.DataModel.Com;
using System;
using System.Runtime.InteropServices;
namespace EarTrumpet.DataModel
{
static class DefaultEndPoint
{
[Guid("F8679F50-850A-41CF-9C72-430F290290C8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPolicyConfig
{
void __incomplete__1();
void __incomplete__2();
void __incomplete__3();
void __incomplete__4();
void __incomplete__5();
void __incomplete__6();
void __incomplete__7();
void __incomplete__8();
void __incomplete__9();
void __incomplete__10();
void SetDefaultEndpoint(string wszDeviceId, uint eRole);
}
[ComImport]
[Guid("870AF99C-171D-4F9E-AF0D-E63DF40C2BC9")]
public class PolicyConfigClient { }
public static void SetDefaultDevice(IAudioDevice device, ERole role = ERole.eMultimedia)
{
var policyClient = new PolicyConfigClient();
(policyClient as IPolicyConfig).SetDefaultEndpoint(device.Id, (uint)role);
}
}
} | using EarTrumpet.DataModel.Com;
using System;
using System.Runtime.InteropServices;
namespace EarTrumpet.DataModel
{
static class DefaultEndPoint
{
[Guid("CA286FC3-91FD-42C3-8E9B-CAAFA66242E3")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPolicyConfig_TH1
{
void Unused1();
void Unused2();
void Unused3();
void Unused4();
void Unused5();
void Unused6();
void Unused7();
void Unused8();
void Unused9();
void Unused10();
void SetDefaultEndpoint(string wszDeviceId, uint eRole);
}
[Guid("6BE54BE8-A068-4875-A49D-0C2966473B11")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPolicyConfig_TH2
{
void Unused1();
void Unused2();
void Unused3();
void Unused4();
void Unused5();
void Unused6();
void Unused7();
void Unused8();
void Unused9();
void Unused10();
void SetDefaultEndpoint(string wszDeviceId, uint eRole);
}
[Guid("F8679F50-850A-41CF-9C72-430F290290C8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPolicyConfig_RS1
{
void Unused1();
void Unused2();
void Unused3();
void Unused4();
void Unused5();
void Unused6();
void Unused7();
void Unused8();
void Unused9();
void Unused10();
void SetDefaultEndpoint(string wszDeviceId, uint eRole);
}
[ComImport]
[Guid("870AF99C-171D-4F9E-AF0D-E63DF40C2BC9")]
public class PolicyConfigClient { }
public static void SetDefaultDevice(IAudioDevice device, ERole role = ERole.eMultimedia)
{
var policyClient = new PolicyConfigClient();
var policy_th1 = policyClient as IPolicyConfig_TH1;
if (policy_th1 != null)
{
policy_th1.SetDefaultEndpoint(device.Id, (uint)role);
return;
}
var policy_th2 = policyClient as IPolicyConfig_TH2;
if (policy_th2 != null)
{
policy_th2.SetDefaultEndpoint(device.Id, (uint)role);
return;
}
var policy_rs1 = policyClient as IPolicyConfig_RS1;
if (policy_rs1 != null)
{
policy_rs1.SetDefaultEndpoint(device.Id, (uint)role);
return;
}
throw new Exception("IPolicyClient is not available.");
}
}
} | mit | C# |
c84695c3462f46a720ea43504ab5118be2580a70 | Fix casing of warden service. | cloudfoundry/IronFrame,cloudfoundry/IronFrame,stefanschneider/IronFrame,cloudfoundry-incubator/IronFrame,cloudfoundry-incubator/if_warden,cloudfoundry-incubator/if_warden,stefanschneider/IronFrame,cloudfoundry-incubator/IronFrame | IronFoundry.Warden.Service/Constants.cs | IronFoundry.Warden.Service/Constants.cs | namespace IronFoundry.Warden.Service
{
public static class Constants
{
public const string DisplayName = "Iron Foundry Warden Service";
public const string ServiceName = "IronFoundry.Warden";
}
}
| namespace IronFoundry.Warden.Service
{
public static class Constants
{
public const string DisplayName = "Iron Foundry Warden Service";
public const string ServiceName = "ironfoundry.warden";
}
}
| apache-2.0 | C# |
d1b048c2cccd115105b7bd2406502da1ebabc8ea | Make DisposableExtensions.AddTo method-chainable | OrangeCube/UniRx,ppcuni/UniRx,juggernate/UniRx,kimsama/UniRx,zillakot/UniRx,m-ishikawa/UniRx,zillakot/UniRx,zillakot/UniRx,TORISOUP/UniRx,InvertGames/UniRx,OC-Leon/UniRx,juggernate/UniRx,juggernate/UniRx,zhutaorun/UniRx,cruwel/UniRx,zhutaorun/UniRx,ufcpp/UniRx,saruiwa/UniRx,cruwel/UniRx,cruwel/UniRx,endo0407/UniRx,ataihei/UniRx,zhutaorun/UniRx,neuecc/UniRx,ic-sys/UniRx,ic-sys/UniRx,ic-sys/UniRx | Assets/UniRx/Scripts/Disposables/DisposableExtensions.cs | Assets/UniRx/Scripts/Disposables/DisposableExtensions.cs | using System;
using System.Collections.Generic;
namespace UniRx
{
public static partial class DisposableExtensions
{
/// <summary>Add disposable(self) to CompositeDisposable(or other ICollection). Return value is self disposable.</summary>
public static T AddTo<T>(this T disposable, ICollection<IDisposable> container)
where T : IDisposable
{
if (disposable == null) throw new ArgumentNullException("disposable");
if (container == null) throw new ArgumentNullException("container");
container.Add(disposable);
return disposable;
}
}
} | using System;
using System.Collections.Generic;
namespace UniRx
{
public static partial class DisposableExtensions
{
/// <summary>Add disposable(self) to CompositeDisposable(or other ICollection). Return value is self disposable.</summary>
public static IDisposable AddTo(this IDisposable disposable, ICollection<IDisposable> container)
{
if (disposable == null) throw new ArgumentNullException("disposable");
if (container == null) throw new ArgumentNullException("container");
container.Add(disposable);
return disposable;
}
}
} | mit | C# |
78f9692401e189d03b508a3cac4c04d1475e69bb | Fix flushing issue and added number of files being processed. | projectkudu/KuduSync.NET,kostrse/KuduSync.NET,uQr/KuduSync.NET,kostrse/KuduSync.NET,projectkudu/KuduSync.NET,uQr/KuduSync.NET | KuduSync.NET/Logger.cs | KuduSync.NET/Logger.cs | using System;
using System.IO;
using System.Text;
namespace KuduSync.NET
{
public class Logger : IDisposable
{
private const int KeepAliveLogTimeInSeconds = 20;
private int _logCounter = 0;
private StreamWriter _writer;
private int _maxLogLines;
private DateTime _nextLogTime;
/// <summary>
/// Logger class
/// </summary>
/// <param name="maxLogLines">sets the verbosity, 0 is verbose, less is quiet, more is the number of maximum log lines to write.</param>
public Logger(int maxLogLines)
{
var stream = Console.OpenStandardOutput();
_writer = new StreamWriter(stream);
_maxLogLines = maxLogLines;
}
public void Log(string format, params object[] args)
{
bool logged = false;
if (_maxLogLines == 0 || _logCounter < _maxLogLines)
{
_writer.WriteLine(format, args);
}
else if (_logCounter == _maxLogLines)
{
_writer.WriteLine("Omitting next output lines...");
logged = true;
}
else
{
// Make sure some output is still logged every 20 seconds
if (DateTime.Now >= _nextLogTime)
{
_writer.WriteLine("Processed {0} files...", _logCounter - 1);
logged = true;
}
}
if (logged)
{
_writer.Flush();
_nextLogTime = DateTime.Now.Add(TimeSpan.FromSeconds(KeepAliveLogTimeInSeconds));
}
_logCounter++;
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
| using System;
using System.IO;
using System.Text;
namespace KuduSync.NET
{
public class Logger : IDisposable
{
private const int KeepAliveLogTimeInSeconds = 20;
private int _logCounter = 0;
private StreamWriter _writer;
private int _maxLogLines;
private DateTime _nextLogTime;
/// <summary>
/// Logger class
/// </summary>
/// <param name="maxLogLines">sets the verbosity, 0 is verbose, less is quiet, more is the number of maximum log lines to write.</param>
public Logger(int maxLogLines)
{
var stream = Console.OpenStandardOutput();
_writer = new StreamWriter(stream);
_maxLogLines = maxLogLines;
}
public void Log(string format, params object[] args)
{
if (_maxLogLines == 0 || _logCounter < _maxLogLines)
{
_writer.WriteLine(format, args);
}
else if (_logCounter == _maxLogLines)
{
_writer.WriteLine("Omitting next output lines...");
}
else
{
// Make sure some output is still logged every 20 seconds
if (DateTime.Now >= _nextLogTime)
{
_writer.WriteLine("Working...");
_nextLogTime = DateTime.Now.Add(TimeSpan.FromSeconds(KeepAliveLogTimeInSeconds));
}
}
_logCounter++;
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
| apache-2.0 | C# |
c55bb2a0b04d35eefbecd7fd5cf84831727a1ad6 | Fix bug concerning the log level | jdno/AIChallengeFramework | IO/Logger.cs | IO/Logger.cs | //
// Copyright 2014 jdno
//
// 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 AIChallengeFramework
{
/// <summary>
/// This is a small logging facility that can be used for troubleshooting.
/// </summary>
public static class Logger
{
/// <summary>
/// These are the log level supported by this project.
/// </summary>
public enum Severity {
OFF = 0,
ERROR = 1,
INFO = 2,
DEBUG = 3
}
/// <summary>
/// Choose the severity you would like to have logged.
/// </summary>
public static Severity LogLevel { get; private set; }
/// <summary>
/// Initialize this instance.
/// </summary>
public static void Initialize ()
{
LogLevel = Severity.ERROR;
}
/// <summary>
/// Efficiently check if the log level is DEBUG.
/// </summary>
/// <returns><c>true</c> if is DEBUG; otherwise, <c>false</c>.</returns>
public static bool IsDebug ()
{
if (LogLevel == Severity.DEBUG) {
return true;
} else {
return false;
}
}
/// <summary>
/// Log the message only if the log level is error.
/// </summary>
/// <param name="message">Message.</param>
public static void Error (string message)
{
if (LogLevel <= Severity.ERROR)
print (message);
}
/// <summary>
/// Log the message only if the log level is info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Info (string message)
{
if (LogLevel <= Severity.INFO)
print (message);
}
/// <summary>
/// Log the message only if the log level is debug, info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Debug (string message)
{
if (LogLevel <= Severity.DEBUG)
print (message);
}
/// <summary>
/// Print the specified message.
/// </summary>
/// <param name="message">Message.</param>
private static void print (string message) {
Console.Error.WriteLine (message);
}
}
}
| //
// Copyright 2014 jdno
//
// 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 AIChallengeFramework
{
/// <summary>
/// This is a small logging facility that can be used for troubleshooting.
/// </summary>
public static class Logger
{
/// <summary>
/// These are the log level supported by this project.
/// </summary>
public enum Severity {
OFF = 0,
ERROR = 1,
INFO = 2,
DEBUG = 3
}
/// <summary>
/// Choose the severity you would like to have logged.
/// </summary>
public static Severity LogLevel { get; private set; }
/// <summary>
/// Initialize this instance.
/// </summary>
public static void Initialize ()
{
LogLevel = Severity.ERROR;
}
/// <summary>
/// Efficiently check if the log level is DEBUG.
/// </summary>
/// <returns><c>true</c> if is DEBUG; otherwise, <c>false</c>.</returns>
public static bool IsDebug ()
{
if (LogLevel == Severity.DEBUG) {
return true;
} else {
return false;
}
}
/// <summary>
/// Log the message only if the log level is error.
/// </summary>
/// <param name="message">Message.</param>
public static void Error (string message)
{
if (LogLevel >= Severity.ERROR)
print (message);
}
/// <summary>
/// Log the message only if the log level is info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Info (string message)
{
if (LogLevel >= Severity.INFO)
print (message);
}
/// <summary>
/// Log the message only if the log level is debug, info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Debug (string message)
{
if (LogLevel == Severity.DEBUG)
print (message);
}
/// <summary>
/// Print the specified message.
/// </summary>
/// <param name="message">Message.</param>
private static void print (string message) {
Console.Error.WriteLine (message);
}
}
}
| apache-2.0 | C# |
1d7cb7c4ab76f3f89ba408e3b99602e8da88841b | Revert to 0918690ee04719743afeaab6fa19b21cdfc66c19 There is a lua way to do it. | neolithos/neolua | NeoLua/Properties/AssemblyInfoGlobal.cs | NeoLua/Properties/AssemblyInfoGlobal.cs | using System.Reflection;
[assembly: AssemblyCompany("TecWare Gesellschaft für Softwareentwicklung mbH")]
[assembly: AssemblyProduct("Neo.Lua")]
[assembly: AssemblyCopyright("Copyright © 2013-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("5.3.0.0")]
[assembly: AssemblyFileVersion("1.2.14.0")]
[assembly: AssemblyConfiguration("beta")]
//[assembly: AssemblyConfiguration("")]
| using System.Reflection;
[assembly: AssemblyCompany("TecWare Gesellschaft für Softwareentwicklung mbH")]
[assembly: AssemblyProduct("Neo.Lua")]
[assembly: AssemblyCopyright("Copyright © 2013-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("5.3.0.0")]
[assembly: AssemblyFileVersion("1.2.10.0")]
[assembly: AssemblyConfiguration("beta")]
//[assembly: AssemblyConfiguration("")]
| apache-2.0 | C# |
49aa339a375db807b92f71fa7ddc65feb30d9e92 | Fix NullishCoalescing.ResultType | nilproject/NiL.JS,nilproject/NiL.JS,nilproject/NiL.JS | NiL.JS/Expressions/NullishCoalescing.cs | NiL.JS/Expressions/NullishCoalescing.cs | using System;
using System.Collections.Generic;
using NiL.JS.Core;
namespace NiL.JS.Expressions
{
#if !(PORTABLE || NETCORE)
[Serializable]
#endif
public sealed class NullishCoalescing : Expression
{
protected internal override PredictedType ResultType
{
get
{
var leftType = _left.ResultType;
var rightType = _right.ResultType;
return leftType == rightType ? leftType : PredictedType.Ambiguous;
}
}
internal override bool ResultInTempContainer
{
get { return false; }
}
public NullishCoalescing(Expression first, Expression second)
: base(first, second, false)
{
}
public override JSValue Evaluate(Context context)
{
var left = _left.Evaluate(context);
if (left.Defined && !left.IsNull)
return left;
else
return _right.Evaluate(context);
}
public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary<string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
{
return base.Build(ref _this, expressionDepth, variables, codeContext | CodeContext.Conditional, message, stats, opts);
}
public override T Visit<T>(Visitor<T> visitor)
{
return visitor.Visit(this);
}
public override string ToString()
{
return "(" + _left + " ?? " + _right + ")";
}
}
} | using System;
using System.Collections.Generic;
using NiL.JS.Core;
namespace NiL.JS.Expressions
{
#if !(PORTABLE || NETCORE)
[Serializable]
#endif
public sealed class NullishCoalescing : Expression
{
protected internal override PredictedType ResultType
{
get
{
return PredictedType.Bool;
}
}
internal override bool ResultInTempContainer
{
get { return false; }
}
public NullishCoalescing(Expression first, Expression second)
: base(first, second, false)
{
}
public override JSValue Evaluate(Context context)
{
var left = _left.Evaluate(context);
if (left.Defined && !left.IsNull)
return left;
else
return _right.Evaluate(context);
}
public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary<string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
{
if (message != null && expressionDepth <= 1)
message(MessageLevel.Warning, Position, 0, "Do not use logical operator as a conditional statement");
return base.Build(ref _this, expressionDepth, variables, codeContext | CodeContext.Conditional, message, stats, opts);
}
public override T Visit<T>(Visitor<T> visitor)
{
return visitor.Visit(this);
}
public override string ToString()
{
return "(" + _left + " ?? " + _right + ")";
}
}
} | bsd-3-clause | C# |
c457219929c030154d8be8bddc169feca030feaa | Clean usings. | vmichalak/Hermes.Net | src/HermesNet/Helpers/MiddlewareManager.cs | src/HermesNet/Helpers/MiddlewareManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HermesNet.Models;
using HermesNet.Models.Http;
namespace HermesNet.Helpers
{
internal class MiddlewareManager
{
private class Entry
{
public HttpMethod Method { get; set; }
public string Route { get; set; }
}
private readonly Dictionary<Entry, IMiddleware> _middlewares = new Dictionary<Entry, IMiddleware>();
public void Add(string route, HttpMethod method, IMiddleware middleware)
{
if (middleware == null) { throw new ArgumentNullException(nameof(middleware)); }
this._middlewares.Add(new Entry() { Method = method, Route = route }, middleware);
}
public void Add(string route, HttpMethod method, Func<HttpContext, Task> middlewareFunc)
{
if(middlewareFunc == null) { throw new ArgumentNullException(nameof(middlewareFunc)); }
this.Add(route, method, new MiddlewareImplementator(middlewareFunc));
}
public async Task<HttpResponse> Execute(HttpRequest request)
{
if(request == null) { throw new ArgumentNullException(nameof(request)); }
HttpContext context = new HttpContext(request);
try
{
Entry searchEntry = new Entry()
{
Method = request.Method,
Route = request.BaseUrl
};
IMiddleware middleware = FilterMiddlewares(searchEntry);
if (middleware == null)
{
context.Response.StatusCode = HttpStatusCode.NotFound;
}
else
{
await middleware.Run(context);
}
}
catch (Exception e)
{
#if !DEBUG
context.Response.StatusCode = HttpStatusCode.InternalServerError;
context.Response.Send("Internal Server Error: " + e.Message);
#else
throw new Exception("Error during MiddlewareManager Execution.", e);
#endif
}
return context.Response;
}
private IMiddleware FilterMiddlewares(Entry searchEntry)
{
KeyValuePair<Entry, IMiddleware>[] list = this._middlewares.ToList().FindAll(m =>
{
Regex regex = new Regex("^"+m.Key.Route);
return (m.Key.Method == HttpMethod.ALL || m.Key.Method == searchEntry.Method) && regex.IsMatch(searchEntry.Route);
}).ToArray();
int maxRouteSize = list[0].Key.Route.Length;
int item = 0;
for (int i = 1; i < list.Length; i++)
{
if (list[i].Key.Route.Length > maxRouteSize)
{
maxRouteSize = list[i].Key.Route.Length;
item = i;
}
}
return list[item].Value;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HermesNet.Models;
using HermesNet.Models.Http;
namespace HermesNet.Helpers
{
internal class MiddlewareManager
{
private class Entry
{
public HttpMethod Method { get; set; }
public string Route { get; set; }
}
private readonly Dictionary<Entry, IMiddleware> _middlewares = new Dictionary<Entry, IMiddleware>();
public void Add(string route, HttpMethod method, IMiddleware middleware)
{
if (middleware == null) { throw new ArgumentNullException(nameof(middleware)); }
this._middlewares.Add(new Entry() { Method = method, Route = route }, middleware);
}
public void Add(string route, HttpMethod method, Func<HttpContext, Task> middlewareFunc)
{
if(middlewareFunc == null) { throw new ArgumentNullException(nameof(middlewareFunc)); }
this.Add(route, method, new MiddlewareImplementator(middlewareFunc));
}
public async Task<HttpResponse> Execute(HttpRequest request)
{
if(request == null) { throw new ArgumentNullException(nameof(request)); }
HttpContext context = new HttpContext(request);
try
{
Entry searchEntry = new Entry()
{
Method = request.Method,
Route = request.BaseUrl
};
IMiddleware middleware = FilterMiddlewares(searchEntry);
if (middleware == null)
{
context.Response.StatusCode = HttpStatusCode.NotFound;
}
else
{
await middleware.Run(context);
}
}
catch (Exception e)
{
#if !DEBUG
context.Response.StatusCode = HttpStatusCode.InternalServerError;
context.Response.Send("Internal Server Error: " + e.Message);
#else
throw new Exception("Error during MiddlewareManager Execution.", e);
#endif
}
return context.Response;
}
private IMiddleware FilterMiddlewares(Entry searchEntry)
{
KeyValuePair<Entry, IMiddleware>[] list = this._middlewares.ToList().FindAll(m =>
{
Regex regex = new Regex("^"+m.Key.Route);
return (m.Key.Method == HttpMethod.ALL || m.Key.Method == searchEntry.Method) && regex.IsMatch(searchEntry.Route);
}).ToArray();
int maxRouteSize = list[0].Key.Route.Length;
int item = 0;
for (int i = 1; i < list.Length; i++)
{
if (list[i].Key.Route.Length > maxRouteSize)
{
maxRouteSize = list[i].Key.Route.Length;
item = i;
}
}
return list[item].Value;
}
}
}
| mit | C# |
27fab71a1c105fcbf088d070907217a9cfada889 | Remove unnecessary static method IsApplicable | Domysee/Pather.CSharp | src/Pather.CSharp/PathElements/Property.cs | src/Pather.CSharp/PathElements/Property.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : IPathElement
{
private string property;
public Property(string property)
{
this.property = property;
}
public object Apply(object target)
{
PropertyInfo p = target.GetType().GetProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : IPathElement
{
public static bool IsApplicable(string pathElement)
{
return Regex.IsMatch(pathElement, @"\w+");
}
private string property;
public Property(string property)
{
this.property = property;
}
public object Apply(object target)
{
PropertyInfo p = target.GetType().GetProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
| mit | C# |
684ee85da95232f5709cf044c79d7d2eeb9bdac6 | Add more debug information for why an EventListenerTouchOneByOne is invalid. An OnTouchBegan action needs to be defined. | hig-ag/CocosSharp,haithemaraissia/CocosSharp,hig-ag/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp,MSylvia/CocosSharp,netonjm/CocosSharp,mono/CocosSharp,TukekeSoft/CocosSharp,haithemaraissia/CocosSharp,netonjm/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp | src/events/CCEventListenerTouchOneByOne.cs | src/events/CCEventListenerTouchOneByOne.cs | using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace CocosSharp
{
public class CCEventListenerTouchOneByOne : CCEventListener
{
public static string LISTENER_ID = "__cc_touch_one_by_one";
// Event callback function for Touch Began events
public Func<CCTouch,CCEvent,bool> OnTouchBegan { get; set; }
// Event callback function for Touch Moved events
public Action<CCTouch,CCEvent> OnTouchMoved { get; set; }
// Event callback function for Touch Ended events
public Action<CCTouch,CCEvent> OnTouchEnded { get; set; }
// Event callback function for Touch Canceled events
public Action<CCTouch,CCEvent> OnTouchCancelled { get; set; }
public bool IsSwallowTouches { get; set; }
internal List<CCTouch> ClaimedTouches { get; set; }
public override bool IsAvailable {
get {
if (OnTouchBegan == null)
{
Debug.Assert(false, "Invalid EventListenerTouchOneByOne!. OnTouchBegan is not defined.");
return false;
}
return true;
}
}
public CCEventListenerTouchOneByOne() : base(CCEventListenerType.TOUCH_ONE_BY_ONE, LISTENER_ID)
{
ClaimedTouches = new List<CCTouch> ();
}
internal CCEventListenerTouchOneByOne(CCEventListenerTouchOneByOne eventListener)
: this()
{
OnTouchBegan = eventListener.OnTouchBegan;
OnTouchMoved = eventListener.OnTouchMoved;
OnTouchEnded = eventListener.OnTouchEnded;
OnTouchCancelled = eventListener.OnTouchCancelled;
ClaimedTouches.AddRange(eventListener.ClaimedTouches);
IsSwallowTouches = eventListener.IsSwallowTouches;
}
public override CCEventListener Copy()
{
return new CCEventListenerTouchOneByOne (this);
}
}
}
| using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace CocosSharp
{
public class CCEventListenerTouchOneByOne : CCEventListener
{
public static string LISTENER_ID = "__cc_touch_one_by_one";
// Event callback function for Touch Began events
public Func<CCTouch,CCEvent,bool> OnTouchBegan { get; set; }
// Event callback function for Touch Moved events
public Action<CCTouch,CCEvent> OnTouchMoved { get; set; }
// Event callback function for Touch Ended events
public Action<CCTouch,CCEvent> OnTouchEnded { get; set; }
// Event callback function for Touch Canceled events
public Action<CCTouch,CCEvent> OnTouchCancelled { get; set; }
public bool IsSwallowTouches { get; set; }
internal List<CCTouch> ClaimedTouches { get; set; }
public override bool IsAvailable {
get {
if (OnTouchBegan == null)
{
Debug.Assert(false, "Invalid EventListenerTouchOneByOne!");
return false;
}
return true;
}
}
public CCEventListenerTouchOneByOne() : base(CCEventListenerType.TOUCH_ONE_BY_ONE, LISTENER_ID)
{
ClaimedTouches = new List<CCTouch> ();
}
internal CCEventListenerTouchOneByOne(CCEventListenerTouchOneByOne eventListener)
: this()
{
OnTouchBegan = eventListener.OnTouchBegan;
OnTouchMoved = eventListener.OnTouchMoved;
OnTouchEnded = eventListener.OnTouchEnded;
OnTouchCancelled = eventListener.OnTouchCancelled;
ClaimedTouches.AddRange(eventListener.ClaimedTouches);
IsSwallowTouches = eventListener.IsSwallowTouches;
}
public override CCEventListener Copy()
{
return new CCEventListenerTouchOneByOne (this);
}
}
}
| mit | C# |
b0fdaeaf7406a78e8ba36f8fce2cd52a55b83e43 | Make DrawableTrack an IAdjustableClock | peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework | osu.Framework/Graphics/Audio/DrawableTrack.cs | osu.Framework/Graphics/Audio/DrawableTrack.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 osu.Framework.Audio.Track;
using osu.Framework.Timing;
namespace osu.Framework.Graphics.Audio
{
/// <summary>
/// A <see cref="Track"/> wrapper to allow insertion in the draw hierarchy to allow transforms, lifetime management etc.
/// </summary>
public class DrawableTrack : DrawableAudioWrapper, ITrack, IAdjustableClock
{
private readonly Track track;
/// <summary>
/// Construct a new drawable track instance.
/// </summary>
/// <param name="track">The audio track to wrap.</param>
/// <param name="disposeTrackOnDisposal">Whether the track should be automatically disposed on drawable disposal/expiry.</param>
public DrawableTrack(Track track, bool disposeTrackOnDisposal = true)
: base(track, disposeTrackOnDisposal)
{
this.track = track;
}
public event Action Completed
{
add => track.Completed += value;
remove => track.Completed -= value;
}
public event Action Failed
{
add => track.Failed += value;
remove => track.Failed -= value;
}
public bool Looping
{
get => track.Looping;
set => track.Looping = value;
}
public bool IsDummyDevice => track.IsDummyDevice;
public double RestartPoint
{
get => track.RestartPoint;
set => track.RestartPoint = value;
}
public double CurrentTime => track.CurrentTime;
public double Rate
{
get => track.Rate;
set => track.Rate = value;
}
public double Length
{
get => track.Length;
set => track.Length = value;
}
public int? Bitrate => track.Bitrate;
public bool IsRunning => track.IsRunning;
public bool IsReversed => track.IsReversed;
public bool HasCompleted => track.HasCompleted;
public void Reset() => track.Reset();
public void Restart() => track.Restart();
public void ResetSpeedAdjustments() => track.ResetSpeedAdjustments();
public bool Seek(double seek) => track.Seek(seek);
public void Start() => track.Start();
public void Stop() => track.Stop();
public ChannelAmplitudes CurrentAmplitudes => track.CurrentAmplitudes;
}
}
| // 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 osu.Framework.Audio.Track;
namespace osu.Framework.Graphics.Audio
{
/// <summary>
/// A <see cref="Track"/> wrapper to allow insertion in the draw hierarchy to allow transforms, lifetime management etc.
/// </summary>
public class DrawableTrack : DrawableAudioWrapper, ITrack
{
private readonly Track track;
/// <summary>
/// Construct a new drawable track instance.
/// </summary>
/// <param name="track">The audio track to wrap.</param>
/// <param name="disposeTrackOnDisposal">Whether the track should be automatically disposed on drawable disposal/expiry.</param>
public DrawableTrack(Track track, bool disposeTrackOnDisposal = true)
: base(track, disposeTrackOnDisposal)
{
this.track = track;
}
public event Action Completed
{
add => track.Completed += value;
remove => track.Completed -= value;
}
public event Action Failed
{
add => track.Failed += value;
remove => track.Failed -= value;
}
public bool Looping
{
get => track.Looping;
set => track.Looping = value;
}
public bool IsDummyDevice => track.IsDummyDevice;
public double RestartPoint
{
get => track.RestartPoint;
set => track.RestartPoint = value;
}
public double CurrentTime => track.CurrentTime;
public double Length
{
get => track.Length;
set => track.Length = value;
}
public int? Bitrate => track.Bitrate;
public bool IsRunning => track.IsRunning;
public bool IsReversed => track.IsReversed;
public bool HasCompleted => track.HasCompleted;
public void Reset() => track.Reset();
public void Restart() => track.Restart();
public void ResetSpeedAdjustments() => track.ResetSpeedAdjustments();
public bool Seek(double seek) => track.Seek(seek);
public void Start() => track.Start();
public void Stop() => track.Stop();
public ChannelAmplitudes CurrentAmplitudes => track.CurrentAmplitudes;
}
}
| mit | C# |
3e02a36938084dd44b199f6d29997b5e8b9b96f6 | Make Wiggle incompatible with Transform | peppy/osu,NeoAdonis/osu,smoogipoo/osu,naoey/osu,UselessToucan/osu,ppy/osu,naoey/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,EVAST9919/osu,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,ZLima12/osu,ZLima12/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu-new,naoey/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,johnneijzen/osu,DrabWeb/osu | osu.Game.Rulesets.Osu/Mods/OsuModTransform.cs | osu.Game.Rulesets.Osu/Mods/OsuModTransform.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 System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModTransform : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Transform";
public override string ShortenedName => "TR";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.Fun;
public override string Description => "Everything rotates. EVERYTHING.";
public override double ScoreMultiplier => 1;
public override Type[] IncompatibleMods => new Type[] { typeof(OsuModWiggle) };
private float theta;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var drawable in drawables)
{
var hitObject = (OsuHitObject) drawable.HitObject;
float appearDistance = (float)(hitObject.TimePreempt - hitObject.TimeFadeIn) / 2;
Vector2 originalPosition = drawable.Position;
Vector2 appearOffset = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appearDistance;
//the - 1 and + 1 prevents the hit objects to appear in the wrong position.
double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1;
double moveDuration = hitObject.TimePreempt + 1;
using (drawable.BeginAbsoluteSequence(appearTime, true))
{
drawable
.MoveToOffset(appearOffset)
.MoveTo(originalPosition, moveDuration, Easing.InOutSine);
}
theta += (float) hitObject.TimeFadeIn / 1000;
}
}
}
}
| // 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 System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModTransform : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Transform";
public override string ShortenedName => "TR";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.Fun;
public override string Description => "Everything rotates. EVERYTHING.";
public override double ScoreMultiplier => 1;
private float theta;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var drawable in drawables)
{
var hitObject = (OsuHitObject) drawable.HitObject;
float appearDistance = (float)(hitObject.TimePreempt - hitObject.TimeFadeIn) / 2;
Vector2 originalPosition = drawable.Position;
Vector2 appearOffset = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appearDistance;
//the - 1 and + 1 prevents the hit objects to appear in the wrong position.
double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1;
double moveDuration = hitObject.TimePreempt + 1;
using (drawable.BeginAbsoluteSequence(appearTime, true))
{
drawable
.MoveToOffset(appearOffset)
.MoveTo(originalPosition, moveDuration, Easing.InOutSine);
}
theta += (float) hitObject.TimeFadeIn / 1000;
}
}
}
}
| mit | C# |
c3ba5011960f5d200f8d96bb7d8573ec48c895ec | Add more quakes to map effect | ethanmoffat/EndlessClient | EOLib.IO/Map/MapEffect.cs | EOLib.IO/Map/MapEffect.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EOLib.IO.Map
{
public enum MapEffect : byte
{
None = 0,
HPDrain = 1,
TPDrain = 2,
Quake1 = 3,
Quake2 = 4,
Quake3 = 5,
Quake4 = 6
}
} | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EOLib.IO.Map
{
public enum MapEffect : byte
{
None = 0,
HPDrain = 1,
TPDrain = 2,
Quake = 3
}
} | mit | C# |
b097556f65659e03b6d9b6248b3f5e605f1a29e2 | comment clean up | smeehan82/Hermes,smeehan82/Hermes,smeehan82/Hermes | src/Hermes.Web/Controllers/BlogsController.cs | src/Hermes.Web/Controllers/BlogsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Hermes.Content.Blogs;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hermes.Web.Controllers
{
[Route("api/blogs")]
public class BlogsController : Controller
{
#region Contructor
private BlogsManager _blogsManager;
private ILogger _logger;
public BlogsController(BlogsManager blogsManager, ILoggerFactory loggerFactory)
{
_blogsManager = blogsManager;
_logger = loggerFactory.CreateLogger<BlogsController>();
}
#endregion
//GET
#region list
[HttpGet]
[Route("list")]
public async Task<IActionResult> Get()
{
var blogs = _blogsManager.Blogs;
return new ObjectResult(blogs);
}
#endregion
//GET
#region single by id
[HttpGet]
[Route("single")]
public async Task<IActionResult> Get(Guid id)
{
var blog = await _blogsManager.FindByIdAsync(id);
return new ObjectResult(blog);
}
#endregion
//GET
#region single by id
[HttpGet]
[Route("single")]
public async Task<IActionResult> Get(string slug)
{
var blog = await _blogsManager.FindBySlugAsync(slug);
return new ObjectResult(blog);
}
#endregion
//POST
#region add
[HttpPost]
[Route("add")]
public async Task<IActionResult> Put(string title, string slug)
{
var blog = new Blog();
blog.Id = new Guid();
blog.Title = title;
blog.Slug = slug;
blog.DateCreated = DateTimeOffset.Now;
blog.DateModified = DateTimeOffset.Now;
blog.DatePublished = DateTimeOffset.Now;
await _blogsManager.AddAsync(blog);
return new ObjectResult(true);
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Hermes.Content.Blogs;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hermes.Web.Controllers
{
[Route("api/blogs")]
public class BlogsController : Controller
{
#region Contructor
private BlogsManager _blogsManager;
private ILogger _logger;
public BlogsController(BlogsManager blogsManager, ILoggerFactory loggerFactory)
{
_blogsManager = blogsManager;
_logger = loggerFactory.CreateLogger<BlogsController>();
}
#endregion
// GET: api/values
#region list
[HttpGet]
[Route("list")]
public async Task<IActionResult> Get()
{
var blogs = _blogsManager.Blogs;
return new ObjectResult(blogs);
}
#endregion
//GET
#region single by id
[HttpGet]
[Route("single")]
public async Task<IActionResult> Get(Guid id)
{
var blog = await _blogsManager.FindByIdAsync(id);
return new ObjectResult(blog);
}
#endregion
//GET
#region single by id
[HttpGet]
[Route("single")]
public async Task<IActionResult> Get(string slug)
{
var blog = await _blogsManager.FindBySlugAsync(slug);
return new ObjectResult(blog);
}
#endregion
//POST
#region add
[HttpPost]
[Route("add")]
public async Task<IActionResult> Put(string title, string slug)
{
var blog = new Blog();
blog.Id = new Guid();
blog.Title = title;
blog.Slug = slug;
blog.DateCreated = DateTimeOffset.Now;
blog.DateModified = DateTimeOffset.Now;
blog.DatePublished = DateTimeOffset.Now;
await _blogsManager.AddAsync(blog);
return new ObjectResult(true);
}
#endregion
}
}
| mit | C# |
72abbff1f030252c4dc8a12aa7107348a3d146b6 | Add missing file header. | mrward/typescript-addin,chrisber/typescript-addin,chrisber/typescript-addin,mrward/typescript-addin | src/TypeScriptBinding/RegisterIconsCommand.cs | src/TypeScriptBinding/RegisterIconsCommand.cs | //
// RegisterIconsCommand.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (C) 2013 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using ICSharpCode.Core;
using ICSharpCode.SharpDevelop;
namespace ICSharpCode.TypeScriptBinding
{
public class RegisterIconsCommand : AbstractCommand
{
public override void Run()
{
Assembly assembly = typeof(RegisterIconsCommand).Assembly;
ResourceService.RegisterImages("ICSharpCode.TypeScriptBinding.Resources.ImageResources", assembly);
}
}
}
| // Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Reflection;
using ICSharpCode.Core;
using ICSharpCode.SharpDevelop;
namespace ICSharpCode.TypeScriptBinding
{
public class RegisterIconsCommand : AbstractCommand
{
public override void Run()
{
Assembly assembly = typeof(RegisterIconsCommand).Assembly;
ResourceService.RegisterImages("ICSharpCode.TypeScriptBinding.Resources.ImageResources", assembly);
}
}
}
| mit | C# |
e587de5222bbe98863bb4abe14177d990128e7e4 | Update twitter to API v1.1 | moljac/Xamarin.Social,pacificIT/Xamarin.Social,pacificIT/Xamarin.Social,moljac/Xamarin.Social,xamarin/Xamarin.Social,aphex3k/Xamarin.Social,junian/Xamarin.Social,xamarin/Xamarin.Social,aphex3k/Xamarin.Social,junian/Xamarin.Social | src/Xamarin.Social/Services/TwitterService.cs | src/Xamarin.Social/Services/TwitterService.cs | using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Linq;
using Xamarin.Auth;
namespace Xamarin.Social.Services
{
public class TwitterService : OAuth1Service
{
public TwitterService ()
: base ("Twitter", "Twitter")
{
CreateAccountLink = new Uri ("https://twitter.com/signup");
ShareTitle = "Tweet";
MaxTextLength = 140;
MaxLinks = int.MaxValue;
MaxImages = 1;
RequestTokenUrl = new Uri ("https://api.twitter.com/oauth/request_token");
AuthorizeUrl = new Uri ("https://api.twitter.com/oauth/authorize");
AccessTokenUrl = new Uri ("https://api.twitter.com/oauth/access_token");
}
public override int GetTextLength (Item item)
{
//
// There are about 22 chars (eg https://t.co/UoGgfjFd) per attachment
//
return item.Text.Length + 22*(item.Links.Count + item.Images.Count + item.Files.Count);
}
public override Task ShareItemAsync (Item item, Account account, CancellationToken cancellationToken)
{
//
// Combine the links into the tweet
//
var sb = new StringBuilder ();
sb.Append (item.Text);
foreach (var l in item.Links) {
sb.Append (" ");
sb.Append (l.AbsoluteUri);
}
var status = sb.ToString ();
//
// Create the request
//
Request req;
if (item.Images.Count == 0) {
req = CreateRequest ("POST", new Uri ("https://api.twitter.com/1.1/statuses/update.json"), account);
req.Parameters["status"] = status;
}
else {
req = CreateRequest ("POST", new Uri ("https://api.twitter.com/1.1/statuses/update_with_media.json"), account);
req.AddMultipartData ("status", status);
foreach (var i in item.Images.Take (MaxImages)) {
i.AddToRequest (req, "media[]");
}
}
//
// Send it
//
return req.GetResponseAsync (cancellationToken);/*.ContinueWith ((Task<Response> reqTask) => {
var content = reqTask.Result.GetResponseText ();
if (!content.Contains ("<status")) {
throw new SocialException ("Twitter did not return the expected response.");
}
});*/
}
}
}
| using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Linq;
using Xamarin.Auth;
namespace Xamarin.Social.Services
{
public class TwitterService : OAuth1Service
{
public TwitterService ()
: base ("Twitter", "Twitter")
{
CreateAccountLink = new Uri ("https://twitter.com/signup");
ShareTitle = "Tweet";
MaxTextLength = 140;
MaxLinks = int.MaxValue;
MaxImages = 1;
RequestTokenUrl = new Uri ("https://api.twitter.com/oauth/request_token");
AuthorizeUrl = new Uri ("https://api.twitter.com/oauth/authorize");
AccessTokenUrl = new Uri ("https://api.twitter.com/oauth/access_token");
}
public override int GetTextLength (Item item)
{
//
// There are about 22 chars (eg https://t.co/UoGgfjFd) per attachment
//
return item.Text.Length + 22*(item.Links.Count + item.Images.Count + item.Files.Count);
}
public override Task ShareItemAsync (Item item, Account account, CancellationToken cancellationToken)
{
//
// Combine the links into the tweet
//
var sb = new StringBuilder ();
sb.Append (item.Text);
foreach (var l in item.Links) {
sb.Append (" ");
sb.Append (l.AbsoluteUri);
}
var status = sb.ToString ();
//
// Create the request
//
Request req;
if (item.Images.Count == 0) {
req = CreateRequest ("POST", new Uri ("https://api.twitter.com/1/statuses/update.xml"), account);
req.Parameters["status"] = status;
}
else {
req = CreateRequest ("POST", new Uri ("https://upload.twitter.com/1/statuses/update_with_media.xml"), account);
req.AddMultipartData ("status", status);
foreach (var i in item.Images.Take (MaxImages)) {
i.AddToRequest (req, "media[]");
}
}
//
// Send it
//
return req.GetResponseAsync (cancellationToken).ContinueWith (reqTask => {
var content = reqTask.Result.GetResponseText ();
if (!content.Contains ("<status")) {
throw new SocialException ("Twitter did not return the expected response.");
}
});
}
}
}
| apache-2.0 | C# |
45f09127ea5d1fdc0f01a82315dab4107d72e10e | Remove bogus comment | kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net | JoinRpg.DataModel/User.cs | JoinRpg.DataModel/User.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Helpers;
using Microsoft.AspNet.Identity;
namespace JoinRpg.DataModel
{
public class User : IUser<int>
{
public int UserId { get; set; }
public string BornName { get; set; }
public string FatherName { get; set; }
public string SurName { get; set; }
public int Id => UserId;
public string UserName { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
public virtual ICollection<ProjectAcl> ProjectAcls { get; set; }
public virtual ICollection<Claim> Claims { get; set; }
public string DisplayName
=> new string[] {PrefferedName, FullName, Email}.SkipWhile(string.IsNullOrWhiteSpace).FirstOrDefault();
public string FullName => new[] {BornName, FatherName, SurName}.JoinIfNotNullOrWhitespace(" ");
public string PrefferedName { get; set; }
public virtual UserAuthDetails Auth { get; set; }
public virtual AllrpgUserDetails Allrpg { get; set; }
public virtual UserExtra Extra { get; set; }
}
public enum Gender : byte
{
Unknown = 0,
Male = 1,
Female = 2
}
public class UserExtra
{
public int UserId { get; set; }
public byte GenderByte { get; set; }
public Gender Gender
{
get { return (Gender) GenderByte; }
set { GenderByte = (byte) value; }
}
public string PhoneNumber { get; set; }
public string Skype { get; set; }
public string Nicknames { get; set; }
public string GroupNames { get; set; }
public DateTime? BirthDate { get; set; }
}
public class UserAuthDetails
{
public int UserId { get; set; }
public bool EmailConfirmed { get; set; }
public DateTime RegisterDate { get; set; }
}
public class AllrpgUserDetails
{
public int UserId { get; set; }
public int? Sid { get; set; }
public string JsonProfile { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Helpers;
using Microsoft.AspNet.Identity;
namespace JoinRpg.DataModel
{
public class User : IUser<int>
{
public int UserId { get; set; }
public string BornName { get; set; }
public string FatherName { get; set; }
public string SurName { get; set; }
public int Id => UserId;
public string UserName { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
public virtual ICollection<ProjectAcl> ProjectAcls { get; set; }
public virtual ICollection<Claim> Claims { get; set; }
public string DisplayName
=> new string[] {PrefferedName, FullName, Email}.SkipWhile(string.IsNullOrWhiteSpace).FirstOrDefault();
//Should create creative display name
public string FullName => new[] {BornName, FatherName, SurName}.JoinIfNotNullOrWhitespace(" ");
public string PrefferedName { get; set; }
public virtual UserAuthDetails Auth { get; set; }
public virtual AllrpgUserDetails Allrpg { get; set; }
public virtual UserExtra Extra { get; set; }
}
public enum Gender : byte
{
Unknown = 0,
Male = 1,
Female = 2
}
public class UserExtra
{
public int UserId { get; set; }
public byte GenderByte { get; set; }
public Gender Gender
{
get { return (Gender) GenderByte; }
set { GenderByte = (byte) value; }
}
public string PhoneNumber { get; set; }
public string Skype { get; set; }
public string Nicknames { get; set; }
public string GroupNames { get; set; }
public DateTime? BirthDate { get; set; }
}
public class UserAuthDetails
{
public int UserId { get; set; }
public bool EmailConfirmed { get; set; }
public DateTime RegisterDate { get; set; }
}
public class AllrpgUserDetails
{
public int UserId { get; set; }
public int? Sid { get; set; }
public string JsonProfile { get; set; }
}
} | mit | C# |
5dfbc7292130c6c4ea579f69c9c4dc9203fdc249 | Watch Dog fix | Sadikk/BlueSheep | BlueSheep/Engine/Types/WatchDog.cs | BlueSheep/Engine/Types/WatchDog.cs | using BlueSheep.Interface;
using BlueSheep.Interface.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
namespace BlueSheep.Engine.Types
{
public class WatchDog
{
#region Fields
private AccountUC m_Account;
private DateTime PathAction;
private Thread m_PathDog;
#endregion
#region Constructors
public WatchDog(AccountUC account)
{
m_Account = account;
}
#endregion
#region Public Methods
public void StartPathDog()
{
m_PathDog = new Thread(new ThreadStart(PathDog));
m_PathDog.Start();
}
public void StopPathDog()
{
if (m_PathDog != null)
m_PathDog.Abort();
}
public void Update()
{
PathAction = DateTime.Now;
}
#endregion
#region Private Methods
private void PathDog()
{
DateTime now = PathAction;
double endwait = Environment.TickCount + 10000;
while (Environment.TickCount < endwait)
{
System.Threading.Thread.Sleep(1);
System.Windows.Forms.Application.DoEvents();
}
DateTime after = PathAction;
if (DateTime.Compare(now, after) == 0 && CheckState())
{
m_Account.Log(new DebugTextInformation("[WatchDog] Relaunch path"), 0);
m_Account.Path.ParsePath();
StartPathDog();
}
else
{
m_Account.Log(new DebugTextInformation("[WatchDog] Nothing to do."), 0);
StartPathDog();
}
}
private bool CheckState()
{
return (m_Account.state == Enums.Status.None ||
m_Account.state == Enums.Status.Moving);
}
#endregion
}
}
| using BlueSheep.Interface;
using BlueSheep.Interface.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
namespace BlueSheep.Engine.Types
{
public class WatchDog
{
#region Fields
private AccountUC m_Account;
private DateTime PathAction;
private Thread m_PathDog;
#endregion
#region Constructors
public WatchDog(AccountUC account)
{
m_Account = account;
}
#endregion
#region Public Methods
public void StartPathDog()
{
m_PathDog = new Thread(new ThreadStart(PathDog));
m_PathDog.Start();
}
public void StopPathDog()
{
m_PathDog.Abort();
}
public void Update()
{
PathAction = DateTime.Now;
}
#endregion
#region Private Methods
private void PathDog()
{
DateTime now = PathAction;
double endwait = Environment.TickCount + 10000;
while (Environment.TickCount < endwait)
{
System.Threading.Thread.Sleep(1);
System.Windows.Forms.Application.DoEvents();
}
DateTime after = PathAction;
if (DateTime.Compare(now, after) == 0 && CheckState())
{
m_Account.Log(new DebugTextInformation("[WatchDog] Relaunch path"), 0);
m_Account.Path.ParsePath();
StartPathDog();
}
else
{
m_Account.Log(new DebugTextInformation("[WatchDog] Nothing to do."), 0);
StartPathDog();
}
}
private bool CheckState()
{
return (m_Account.state == Enums.Status.None ||
m_Account.state == Enums.Status.Moving);
}
#endregion
}
}
| mit | C# |
7a93ffc8eb3b96199dfa0c70b75572ee2b846fce | Add TODO | OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania | src/WebClient/Program.cs | src/WebClient/Program.cs | using Microsoft.AspNetCore.Hosting;
using System.IO;
// TODO: numarul de locuinte autorizate in fiecare luna/semestru (Beniamin Petrovai)
namespace WebClient
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace WebClient
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| mit | C# |
b44235959b730fcbed8e5ab6e8d8baf0c7e33b95 | Use switch expressions | carbon/Amazon | src/Amazon.S3/Actions/CopyObjectRequest.cs | src/Amazon.S3/Actions/CopyObjectRequest.cs | using System.Linq;
using System.Net.Http;
namespace Amazon.S3
{
public sealed class CopyObjectRequest : S3Request
{
public CopyObjectRequest(string host, S3ObjectLocation source, S3ObjectLocation target)
: base(HttpMethod.Put, host, target.BucketName, target.Key)
{
Headers.Add("x-amz-copy-source", $"/{source.BucketName}/{source.Key}");
CompletionOption = HttpCompletionOption.ResponseContentRead;
}
// If undefined, the default is COPY
public MetadataDirectiveValue? MetadataDirective
{
get
{
if (this.Headers.TryGetValues(S3HeaderNames.MetadataDirective, out var values))
{
switch (values.FirstOrDefault())
{
case "COPY": return MetadataDirectiveValue.Copy;
case "REPLACE": return MetadataDirectiveValue.Replace;
}
}
return null;
}
set
{
string? val = value switch
{
MetadataDirectiveValue.Copy => "COPY",
MetadataDirectiveValue.Replace => "REPLACE",
_ => null
};
Set(S3HeaderNames.MetadataDirective, val);
}
}
private void Set(string name, string? value)
{
if (value is null)
{
this.Headers.Remove(name);
}
this.Headers.TryAddWithoutValidation(name, value);
}
}
}
| using System.Linq;
using System.Net.Http;
namespace Amazon.S3
{
public sealed class CopyObjectRequest : S3Request
{
public CopyObjectRequest(string host, S3ObjectLocation source, S3ObjectLocation target)
: base(HttpMethod.Put, host, target.BucketName, target.Key)
{
Headers.Add("x-amz-copy-source", $"/{source.BucketName}/{source.Key}");
CompletionOption = HttpCompletionOption.ResponseContentRead;
}
// If undefined, the default is COPY
public MetadataDirectiveValue? MetadataDirective
{
get
{
if (this.Headers.TryGetValues(S3HeaderNames.MetadataDirective, out var values))
{
switch (values.FirstOrDefault())
{
case "COPY": return MetadataDirectiveValue.Copy;
case "REPLACE": return MetadataDirectiveValue.Replace;
}
}
return null;
}
set
{
string? val = null;
switch (value)
{
case MetadataDirectiveValue.Copy:
val = "COPY";
break;
case MetadataDirectiveValue.Replace:
val = "REPLACE";
break;
}
Set(S3HeaderNames.MetadataDirective, val);
}
}
private void Set(string name, string? value)
{
if (value is null)
{
this.Headers.Remove(name);
}
this.Headers.TryAddWithoutValidation(name, value);
}
}
}
| mit | C# |
b30b6bdb40a90c78ded247f0bcb87c2938292fb0 | Make SkipInjection attribute class sealed | pamidur/aspect-injector | src/AspectInjector.Broker/SkipInjection.cs | src/AspectInjector.Broker/SkipInjection.cs | using System;
namespace AspectInjector.Broker
{
/// <summary>
/// When applied to a target, suppresses injection of any aspects to it.
/// If applied to an interface or an interface method, suppresses injection to any of the corresponding implementations.
/// </summary>
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Method |
AttributeTargets.Constructor |
AttributeTargets.Property |
AttributeTargets.Event,
AllowMultiple = false)]
public sealed class SkipInjection : Attribute
{
}
}
| using System;
namespace AspectInjector.Broker
{
/// <summary>
/// When applied to a target, suppresses injection of any aspects to it.
/// If applied to an interface or an interface method, suppresses injection to any of the corresponding implementations.
/// </summary>
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Method |
AttributeTargets.Constructor |
AttributeTargets.Property |
AttributeTargets.Event,
AllowMultiple = false)]
public class SkipInjection : Attribute
{
}
}
| apache-2.0 | C# |
6a8a9d03548818042e7042e4f546a357b20798cf | Correct text | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/TransactionNotifier.cs | WalletWasabi.Gui/TransactionNotifier.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using WalletWasabi.Logging;
using WalletWasabi.Models;
namespace WalletWasabi.Gui
{
internal class TransactionNotifier
{
public readonly static TransactionNotifier Current = new TransactionNotifier();
private TransactionNotifier()
{
}
public void Start()
{
Global.WalletService.CoinReceived += OnCoinReceived;
}
public void Stop()
{
Global.WalletService.CoinReceived -= OnCoinReceived;
}
private void OnCoinReceived(object sender, SmartCoin coin)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start(new ProcessStartInfo
{
FileName = "notify-send",
Arguments = $"\"Wasabi\" \"Received {coin.Amount.ToString(false, true)} BTC\"",
CreateNoWindow = true
});
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start(new ProcessStartInfo
{
FileName = "osascript",
Arguments = $"-e display notification \"Received {coin.Amount.ToString(false, true)} BTC\" with title \"Wasabi\"",
CreateNoWindow = true
});
}
}
catch (Exception ex)
{
Logger.LogWarning<TransactionNotifier>(ex);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using WalletWasabi.Logging;
using WalletWasabi.Models;
namespace WalletWasabi.Gui
{
internal class TransactionNotifier
{
public readonly static TransactionNotifier Current = new TransactionNotifier();
private TransactionNotifier()
{
}
public void Start()
{
Global.WalletService.CoinReceived += OnCoinReceived;
}
public void Stop()
{
Global.WalletService.CoinReceived -= OnCoinReceived;
}
private void OnCoinReceived(object sender, SmartCoin coin)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start(new ProcessStartInfo
{
FileName = "notify-send",
Arguments = $"\"Wasabi Wallet\" \"You have received an incoming transaction {coin.Amount} BTC\"",
CreateNoWindow = true
});
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start(new ProcessStartInfo
{
FileName = "osascript",
Arguments = $"-e display notification \"You have received an incoming transaction {coin.Amount} BTC\" with title \"Wasabi Wallet\"",
CreateNoWindow = true
});
}
}
catch (Exception ex)
{
Logger.LogWarning<TransactionNotifier>(ex);
}
}
}
}
| mit | C# |
559e46f2d695d39d124dbf79124b841fa7c191b7 | Return view from index action | appharbor/foo,appharbor/foo | src/Foo.Web/Controllers/HomeController.cs | src/Foo.Web/Controllers/HomeController.cs | using System;
using System.Web.Mvc;
namespace Foo.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
| using System;
using System.Web.Mvc;
namespace Foo.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
throw new NotImplementedException();
}
}
}
| mit | C# |
b5d7b77225212adfeb42e52b67e8e141ac61c3c2 | fix search bar link bug | camd67/stream-surfer,camd67/stream-surfer | StreamSurfer/Views/Shared/_LoginPartial.cshtml | StreamSurfer/Views/Shared/_LoginPartial.cshtml | @using Microsoft.AspNetCore.Identity
@using StreamSurfer.Models
@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<ul class="nav navbar-nav navbar-right vertical-align">
<li>
<form asp-controller="Home" asp-action="Search" method="get" id="global-search-form" class="form-inline navbar-right">
<div class="input-group">
<i type="submit" class="glyphicon glyphicon-search input-group-addon" id="global-search-input"></i>
<input type="text" id="query" name="query" class="search-box form-control" />
</div>
</form>
</li>
<li>
<a asp-area="" asp-controller="Profile" asp-action="Overview" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</form>
</li>
</ul>
}
else
{
<ul class="nav navbar-nav navbar-right vertical-align">
<li>
<form asp-controller="Home" asp-action="Search" method="get" id="global-search-form" class="form-inline navbar-right">
<div class="input-group">
<i type="submit" class="glyphicon glyphicon-search input-group-addon" id="global-search-input"></i>
<input type="text" id="query" name="query" class="search-box form-control" />
</div>
</form>
</li>
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
| @using Microsoft.AspNetCore.Identity
@using StreamSurfer.Models
@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<ul class="nav navbar-nav navbar-right vertical-align">
<li>
<form asp-action="Search" method="get" id="global-search-form" class="form-inline navbar-right">
<div class="input-group">
<i type="submit" class="glyphicon glyphicon-search input-group-addon" id="global-search-input"></i>
<input type="text" id="query" name="query" class="search-box form-control" />
</div>
</form>
</li>
<li>
<a asp-area="" asp-controller="Profile" asp-action="Overview" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</form>
</li>
</ul>
}
else
{
<ul class="nav navbar-nav navbar-right vertical-align">
<li>
<form asp-action="Search" method="get" id="global-search-form" class="form-inline navbar-right">
<div class="input-group">
<i type="submit" class="glyphicon glyphicon-search input-group-addon" id="global-search-input"></i>
<input type="text" id="query" name="query" class="search-box form-control" />
</div>
</form>
</li>
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
| mit | C# |
22ac4215f07a88ae2355db14de61a0a5f61cb918 | Update AcceptLanguageAttribute.cs | tiksn/TIKSN-Framework | TIKSN.Core/Web/Rest/AcceptLanguageAttribute.cs | TIKSN.Core/Web/Rest/AcceptLanguageAttribute.cs | using System;
namespace TIKSN.Web.Rest
{
[AttributeUsage(AttributeTargets.Property)]
public class AcceptLanguageAttribute : Attribute
{
public AcceptLanguageAttribute() => this.Quality = null;
public AcceptLanguageAttribute(double quality) => this.Quality = quality;
public double? Quality { get; }
}
}
| using System;
namespace TIKSN.Web.Rest
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class AcceptLanguageAttribute : Attribute
{
public AcceptLanguageAttribute()
{
Quality = null;
}
public AcceptLanguageAttribute(double quality)
{
Quality = quality;
}
public double? Quality { get; }
}
} | mit | C# |
19d2fd0e987003d7c9f655b4b59bae2dde7e1d94 | Fix version bug | ErikEJ/EntityFramework7.SqlServerCompact,ErikEJ/EntityFramework.SqlServerCompact | src/Provider40/Properties/AssemblyInfo.cs | src/Provider40/Properties/AssemblyInfo.cs | using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
#if SQLCE35
[assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact35")]
[assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact35")]
[assembly: DesignTimeProviderServices(
typeName: "Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqlCeDesignTimeServices",
assemblyName: "EntityFrameworkCore.SqlServerCompact35.Design, Version=1.2.0.0, Culture=neutral, PublicKeyToken=9af395b34ac99006",
packageName: "EntityFrameworkCore.SqlServerCompact35.Design")]
#else
[assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact40")]
[assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact40")]
[assembly: DesignTimeProviderServices(
typeName: "Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqlCeDesignTimeServices",
assemblyName: "EntityFrameworkCore.SqlServerCompact40.Design, Version=1.2.0.0, Culture=neutral, PublicKeyToken=9af395b34ac99006",
packageName: "EntityFrameworkCore.SqlServerCompact40.Design")]
#endif
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0-preview1")]
| using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
#if SQLCE35
[assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact35")]
[assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact35")]
[assembly: DesignTimeProviderServices(
typeName: "Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqlCeDesignTimeServices",
assemblyName: "EntityFrameworkCore.SqlServerCompact35.Design, Version=1.2.0.0, Culture=neutral, PublicKeyToken=9af395b34ac99006",
packageName: "EntityFrameworkCore.SqlServerCompact35.Design")]
#else
[assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact40")]
[assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact40")]
[assembly: DesignTimeProviderServices(
typeName: "Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqlCeDesignTimeServices",
assemblyName: "EntityFrameworkCore.SqlServerCompact40.Design, Version=1.2.0.0, Culture=neutral, PublicKeyToken=9af395b34ac99006",
packageName: "EntityFrameworkCore.SqlServerCompact40.Design")]
#endif
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0-rtm")]
| apache-2.0 | C# |
b124b3df7f63560e6ad08702c022c386035c86e1 | Make the ASP.NET demo more interesting | praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui | PlatformSamples/AspNetCoreMvc/Controllers/HomeController.cs | PlatformSamples/AspNetCoreMvc/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreMvc.Models;
using Ooui;
using Ooui.AspNetCore;
namespace AspNetCoreMvc.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var count = 0;
var head = new Heading { Text = "Ooui!" };
var label = new Label { Text = "0" };
var btn = new Button { Text = "Increase" };
btn.Clicked += (sender, e) => {
count++;
label.Text = count.ToString ();
};
var div = new Div ();
div.AppendChild (head);
div.AppendChild (label);
div.AppendChild (btn);
return new ElementResult (div);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreMvc.Models;
using Ooui;
using Ooui.AspNetCore;
namespace AspNetCoreMvc.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var element = new Label { Text = "Hello Oooooui from Controller" };
return new ElementResult (element);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| mit | C# |
3c13cd3980337db51c2f2299454293e0f32d6308 | Update the version to 1.4.1 | ladimolnar/BitcoinDatabaseGenerator | Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs | Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BitcoinDatabaseGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitcoinDatabaseGenerator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("372a7f52-b038-43aa-a42c-3ff0ecab1124")]
// 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.4.1.0")]
[assembly: AssemblyFileVersion("1.4.1.0")]
| //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BitcoinDatabaseGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitcoinDatabaseGenerator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("372a7f52-b038-43aa-a42c-3ff0ecab1124")]
// 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.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.