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
797fa4fbf024981ed4b3bf9fc4cf31a06afd9ead
fix Back pressed detection
fabianwilliams/xamarin-forms-samples,reverence12389/xamarin-forms-samples-1,KiranKumarAlugonda/xamarin-forms-samples,teefresh/xamarin-forms-samples-1,fabianwilliams/xamarin-forms-samples,JakeShanley/xamarin-forms-samples,williamsrz/xamarin-forms-samples,pabloescribanoloza/xamarin-forms-samples-1,biste5/xamarin-forms-samples-1,JakeShanley/xamarin-forms-samples,teefresh/xamarin-forms-samples-1,pabloescribanoloza/xamarin-forms-samples-1,KiranKumarAlugonda/xamarin-forms-samples,reverence12389/xamarin-forms-samples-1,conceptdev/xamarin-forms-samples,biste5/xamarin-forms-samples-1,conceptdev/xamarin-forms-samples,williamsrz/xamarin-forms-samples
EmployeeDirectoryXaml/EmployeeDirectoryXaml.Android/MainActivity.cs
EmployeeDirectoryXaml/EmployeeDirectoryXaml.Android/MainActivity.cs
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using System.IO; using EmployeeDirectory; namespace EmployeeDirectory.Android { [Activity (Label = "Employee Directory", MainLauncher = true)] public class Activity1 : Xamarin.Forms.Platform.Android.AndroidActivity { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); Xamarin.Forms.Forms.Init (this, bundle); #region Copy static data into working folder string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); // Documents folder var path = Path.Combine(documentsPath, "XamarinDirectory.csv"); //Console.WriteLine (path); if (!File.Exists (path)) { var s = Resources.OpenRawResource(EmployeeDirectory.Android.Resource.Raw.XamarinDirectory); // RESOURCE NAME ### // create a write stream FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); // write to the stream ReadWriteStream(s, writeStream); } path = Path.Combine(documentsPath, "XamarinFavorites.xml"); //Console.WriteLine (path); if (!File.Exists (path)) { var s = Resources.OpenRawResource(EmployeeDirectory.Android.Resource.Raw.XamarinFavorites); // RESOURCE NAME ### // create a write stream FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); // write to the stream ReadWriteStream(s, writeStream); } #endregion SetPage (App.GetMainPage ()); } void ReadWriteStream(Stream readStream, Stream writeStream) { int Length = 256; Byte[] buffer = new Byte[Length]; int bytesRead = readStream.Read(buffer, 0, Length); // write the required bytes while (bytesRead > 0) { writeStream.Write(buffer, 0, bytesRead); bytesRead = readStream.Read(buffer, 0, Length); } readStream.Close(); writeStream.Close(); } public override bool OnKeyDown (Keycode keyCode, KeyEvent e) { Console.WriteLine ("OnKeyDown:" + this.ActionBar.Title); if (keyCode == Keycode.Back) { if (this.ActionBar.Title != null && this.ActionBar.Title.Contains("Login")) { // The ROOT page is initially set to have 'Login' in .Title // when the app starts (ie. it's hardcoded). // If we're on the login page, swallow the back button. // Note that when login occurs successfully, the .Title // of the page is changed so that the back button works. return false; } } return base.OnKeyDown (keyCode, e); } public override void OnBackPressed () { // could do something in this method instead of OnKeyDown above base.OnBackPressed (); } } }
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using System.IO; using EmployeeDirectory; namespace EmployeeDirectory.Android { [Activity (Label = "Employee Directory", MainLauncher = true)] public class Activity1 : Xamarin.Forms.Platform.Android.AndroidActivity { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); Xamarin.Forms.Forms.Init (this, bundle); #region Copy static data into working folder string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); // Documents folder var path = Path.Combine(documentsPath, "XamarinDirectory.csv"); //Console.WriteLine (path); if (!File.Exists (path)) { var s = Resources.OpenRawResource(EmployeeDirectory.Android.Resource.Raw.XamarinDirectory); // RESOURCE NAME ### // create a write stream FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); // write to the stream ReadWriteStream(s, writeStream); } path = Path.Combine(documentsPath, "XamarinFavorites.xml"); //Console.WriteLine (path); if (!File.Exists (path)) { var s = Resources.OpenRawResource(EmployeeDirectory.Android.Resource.Raw.XamarinFavorites); // RESOURCE NAME ### // create a write stream FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); // write to the stream ReadWriteStream(s, writeStream); } #endregion SetPage (App.GetMainPage ()); } void ReadWriteStream(Stream readStream, Stream writeStream) { int Length = 256; Byte[] buffer = new Byte[Length]; int bytesRead = readStream.Read(buffer, 0, Length); // write the required bytes while (bytesRead > 0) { writeStream.Write(buffer, 0, bytesRead); bytesRead = readStream.Read(buffer, 0, Length); } readStream.Close(); writeStream.Close(); } public override bool OnKeyDown (Keycode keyCode, KeyEvent e) { Console.WriteLine ("OnKeyDown:" + this.ActionBar.Title); if (keyCode == Keycode.Back) { if (this.ActionBar.Title.Contains("Login")) { // The ROOT page is initially set to have 'Login' in .Title // when the app starts (ie. it's hardcoded). // If we're on the login page, swallow the back button. // Note that when login occurs successfully, the .Title // of the page is changed so that the back button works. return false; } } return true; } } }
mit
C#
ad7debd8189a4c02a1a6bcce10bd9980626e465a
Update QuotesController.cs
smeehan82/Hermes,smeehan82/Hermes,smeehan82/Hermes
src/Hermes.Content.Quotes/QuotesController.cs
src/Hermes.Content.Quotes/QuotesController.cs
using Hermes.DataAccess; using Hermes.Mvc; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hermes.Content.Quotes { [Route("api/content/quotes")] public class QuoteController : ContentController<Quote, Guid> { #region Contructor public QuoteController(QuoteManager manager) : base(manager) { _manager = manager; } new protected QuoteManager _manager; #endregion //POST #region create [HttpPost] [Route("create-title")] public virtual async Task<IActionResult> Create([FromQuery]string title) { var quote = new Quote(); quote.Title = title; quote.DateCreated = DateTimeOffset.Now; quote.DateModified = DateTimeOffset.Now; quote.DatePublished = DateTimeOffset.Now; quote.Content = ""; var result = await _manager.AddAsync(quote); if (result.Succeeded) { return new ObjectResult(true); } else { return new ObjectResult(false); } } #endregion } }
using Hermes.DataAccess; using Hermes.Mvc; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hermes.Content.Quotes { [Route("api/quotes")] public class QuoteController : ContentController<Quote, Guid> { #region Contructor public QuoteController(QuoteManager manager) : base(manager) { _manager = manager; } new protected QuoteManager _manager; #endregion //POST #region create [HttpPost] [Route("create-title")] public virtual async Task<IActionResult> Create([FromQuery]string title) { var quote = new Quote(); quote.Title = title; quote.DateCreated = DateTimeOffset.Now; quote.DateModified = DateTimeOffset.Now; quote.DatePublished = DateTimeOffset.Now; quote.Content = ""; var result = await _manager.AddAsync(quote); if (result.Succeeded) { return new ObjectResult(true); } else { return new ObjectResult(false); } } #endregion } }
mit
C#
a8847431e8e04e07ae54450eaffd2a3c767a7ad2
Add ignore_missing to the remove processor (#3441)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Ingest/Processors/RemoveProcessor.cs
src/Nest/Ingest/Processors/RemoveProcessor.cs
using Newtonsoft.Json; using System; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] [JsonConverter(typeof(ProcessorJsonConverter<RemoveProcessor>))] public interface IRemoveProcessor : IProcessor { [JsonProperty("field")] Field Field { get; set; } /// <summary> /// If <c>true</c> and <see cref="Field"/> does not exist or is null, /// the processor quietly exits without modifying the document. Default is <c>false</c> /// </summary> [JsonProperty("ignore_missing")] bool? IgnoreMissing { get; set; } } /// <inheritdoc cref="IRemoveProcessor" /> public class RemoveProcessor : ProcessorBase, IRemoveProcessor { protected override string Name => "remove"; /// <inheritdoc cref="IRemoveProcessor.Field" /> public Field Field { get; set; } /// <inheritdoc cref="IRemoveProcessor.IgnoreMissing" /> public bool? IgnoreMissing { get; set; } } /// <inheritdoc cref="IRemoveProcessor" /> public class RemoveProcessorDescriptor<T> : ProcessorDescriptorBase<RemoveProcessorDescriptor<T>, IRemoveProcessor>, IRemoveProcessor where T : class { protected override string Name => "remove"; Field IRemoveProcessor.Field { get; set; } bool? IRemoveProcessor.IgnoreMissing { get; set; } /// <inheritdoc cref="IRemoveProcessor.Field" /> public RemoveProcessorDescriptor<T> Field(Field field) => Assign(a => a.Field = field); /// <inheritdoc cref="IRemoveProcessor.Field" /> public RemoveProcessorDescriptor<T> Field(Expression<Func<T, object>> objectPath) => Assign(a => a.Field = objectPath); /// <inheritdoc cref="IRemoveProcessor.IgnoreMissing" /> public RemoveProcessorDescriptor<T> IgnoreMissing(bool? ignoreMissing = true) => Assign(a => a.IgnoreMissing = ignoreMissing); } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Nest { [JsonObject(MemberSerialization.OptIn)] [JsonConverter(typeof(ProcessorJsonConverter<RemoveProcessor>))] public interface IRemoveProcessor : IProcessor { [JsonProperty("field")] Field Field { get; set; } } public class RemoveProcessor : ProcessorBase, IRemoveProcessor { protected override string Name => "remove"; public Field Field { get; set; } } public class RemoveProcessorDescriptor<T> : ProcessorDescriptorBase<RemoveProcessorDescriptor<T>, IRemoveProcessor>, IRemoveProcessor where T : class { protected override string Name => "remove"; Field IRemoveProcessor.Field { get; set; } public RemoveProcessorDescriptor<T> Field(Field field) => Assign(a => a.Field = field); public RemoveProcessorDescriptor<T> Field(Expression<Func<T, object>> objectPath) => Assign(a => a.Field = objectPath); } }
apache-2.0
C#
a13b6abcff74b5bd9782d8caf7dbf733b7417a59
Remove incorrect default specification from IRealmFactory interface
smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu
osu.Game/Database/IRealmFactory.cs
osu.Game/Database/IRealmFactory.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Realms; namespace osu.Game.Database { public interface IRealmFactory { Realm Get(); /// <summary> /// Request a context for write usage. Can be consumed in a nested fashion (and will return the same underlying context). /// This method may block if a write is already active on a different thread. /// </summary> /// <returns>A usage containing a usable context.</returns> RealmWriteUsage GetForWrite(); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Realms; namespace osu.Game.Database { public interface IRealmFactory { public Realm Get() => Realm.GetInstance(); /// <summary> /// Request a context for write usage. Can be consumed in a nested fashion (and will return the same underlying context). /// This method may block if a write is already active on a different thread. /// </summary> /// <returns>A usage containing a usable context.</returns> RealmWriteUsage GetForWrite(); } }
mit
C#
23a729c83a6f9afbf76a2cc6af5b314bae477ea8
Make avatars use a delayed load wrapper
smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,ZLima12/osu,UselessToucan/osu,EVAST9919/osu,2yangk23/osu,DrabWeb/osu,2yangk23/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,Frontear/osuKyzer,Drezi126/osu,Nabile-Rahmani/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,DrabWeb/osu,ppy/osu,DrabWeb/osu,naoey/osu,johnneijzen/osu,naoey/osu,UselessToucan/osu,naoey/osu,peppy/osu,ppy/osu,peppy/osu-new
osu.Game/Users/UpdateableAvatar.cs
osu.Game/Users/UpdateableAvatar.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Users { /// <summary> /// An avatar which can update to a new user when needed. /// </summary> public class UpdateableAvatar : Container { private Container displayedAvatar; private User user; public User User { get { return user; } set { if (user?.Id == value?.Id) return; user = value; if (IsLoaded) updateAvatar(); } } protected override void LoadComplete() { base.LoadComplete(); updateAvatar(); } private void updateAvatar() { displayedAvatar?.FadeOut(300); displayedAvatar?.Expire(); Add(displayedAvatar = new DelayedLoadWrapper(new Avatar(user) { RelativeSizeAxes = Axes.Both, OnLoadComplete = d => d.FadeInFromZero(200), })); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Users { /// <summary> /// An avatar which can update to a new user when needed. /// </summary> public class UpdateableAvatar : Container { private Container displayedAvatar; private User user; public User User { get { return user; } set { if (user?.Id == value?.Id) return; user = value; if (IsLoaded) updateAvatar(); } } protected override void LoadComplete() { base.LoadComplete(); updateAvatar(); } private void updateAvatar() { displayedAvatar?.FadeOut(300); displayedAvatar?.Expire(); Add(displayedAvatar = new AsyncLoadWrapper(new Avatar(user) { RelativeSizeAxes = Axes.Both, OnLoadComplete = d => d.FadeInFromZero(200), })); } } }
mit
C#
0f10ae12566ebc08bd72e0189b5ef4f80e1b64eb
Format SqsMessageAttributeValue
carbon/Amazon
src/Amazon.Sqs/Models/SqsMessageAttributeValue.cs
src/Amazon.Sqs/Models/SqsMessageAttributeValue.cs
#nullable disable using System.Xml.Serialization; namespace Amazon.Sqs; public sealed class SqsMessageAttributeValue { [XmlElement("StringValue")] public string StringValue { get; init; } [XmlElement("BinaryValue")] public string BinaryValue { get; init; } [XmlElement("DataType")] public string DataType { get; init; } }
#nullable disable using System.Xml.Serialization; namespace Amazon.Sqs { public sealed class SqsMessageAttributeValue { [XmlElement("StringValue")] public string StringValue { get; init; } [XmlElement("BinaryValue")] public string BinaryValue { get; init; } [XmlElement("DataType")] public string DataType { get; init; } } }
mit
C#
3da3a5dae09b1167ff4363eccf1ec86ec7653c58
test mode
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Program.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using System.Net; using System.IO; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; using System.Configuration; using Dapper; namespace Appleseed.Base.Alerts { class UserAlert { public Guid user_id { get; set; } public string email { get; set; } public string name { get; set; } public string source { get; set; } } class RootSolrObject { public SolrResponse response { get; set; } } class SolrResponse { public SolrResponseItem[] docs { get; set; } } class SolrResponseItem { public string id { get; set; } public string[] item_type { get; set; } public string[] address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string[] postal_code { get; set; } public string[] product_description { get; set; } public string[] product_quantity { get; set; } public string[] product_type { get; set; } public string[] code_info { get; set; } public string[] reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string[] recall_number { get; set; } public string recalling_firm { get; set; } public string[] voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string[] status { get; set; } } class Program { static string Mode = System.Configuration.ConfigurationManager.AppSettings["Mode"]; static void Main(string[] args) { } #region helpers static string UppercaseFirst(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using System.Net; using System.IO; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; using System.Configuration; using Dapper; namespace Appleseed.Base.Alerts { class UserAlert { public Guid user_id { get; set; } public string email { get; set; } public string name { get; set; } public string source { get; set; } } class RootSolrObject { public SolrResponse response { get; set; } } class SolrResponse { public SolrResponseItem[] docs { get; set; } } class SolrResponseItem { public string id { get; set; } public string[] item_type { get; set; } public string[] address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string[] postal_code { get; set; } public string[] product_description { get; set; } public string[] product_quantity { get; set; } public string[] product_type { get; set; } public string[] code_info { get; set; } public string[] reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string[] recall_number { get; set; } public string recalling_firm { get; set; } public string[] voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string[] status { get; set; } } class Program { static void Main(string[] args) { } #region helpers static string UppercaseFirst(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } #endregion } }
apache-2.0
C#
42e67b5c913fa59a74ccf597eca2bba40cd6d035
Estructura de herencia
Beelzenef/GestionMenu
ejemplosClase/Circunferencia.cs
ejemplosClase/Circunferencia.cs
using System; using System.Collections.Generic; namespace egb.Circunferencia { abstract class Figura { public abstract double Area { get; } public abstract double Longitud { get; } public virtual ConsoleColor Color() { return ConsoleColor.Red; } } class Circunferencia : Figura { // Campos double radio = 0; double area = 0; double longitud = 0; // Props public double Radio { get { return this.radio; } set { if (value < 0) value = 0; if (value > 100) value = 100; this.radio = value; } } override public double Area { get { this.area = Math.PI * Math.Pow (radio, 2); return this.area; } } override public double Longitud { get { this.longitud = 2 * Math.PI * radio; return this.longitud; } } // Constructores public Circunferencia() { radio = 0; area = 0; longitud = 0; } public Circunferencia(double r) { Radio = r; } public override string ToString () { return string.Format ("[Radio {0}, Area {1}, Longitud {2}]", this.Radio.ToString(), this.Area.ToString(), this.Longitud.ToString()); } public override ConsoleColor Color () { return ConsoleColor.Blue; } } class Cuadrado : Figura { double lado; double longitud; double area; public double Lado { get { return this.lado; } set { if (value < 0) value = 0; if (value > 100) value = 100; this.lado = value; this.area = Math.Pow (lado, 2); this.longitud = lado * 4; } } public override double Area { get { return this.area; } } public override double Longitud { get { return this.longitud; } } public Cuadrado(double l) { lado = l; area = lado * lado; longitud = lado * 4; } public override string ToString () { return string.Format ("[Lado {0:D3}, Area {1:D3}, Longitud {2:D3}]", Lado, Area, Longitud); } } class Triangulo { public double Base { get; set; } = 100; public double Area { get; set; } public double Perimetro { get; set; } public Triangulo() { } public Triangulo(double b) { Base = b; } public override string ToString () { return string.Format ("[Triangulo: Base {0}]", Base); } } class Inicio { public static void Main (string[] args) { Console.Title = "Clase Circunferencia"; Circunferencia cir1 = new Circunferencia (); Circunferencia cir2 = new Circunferencia (12); Console.WriteLine ("Cir1: " + cir1.ToString()); Console.WriteLine ("Cir2: " + cir2.ToString()); Console.WriteLine ("Cambiando Cir1..."); cir1.Radio = 105; Console.WriteLine ("Cir1: " + cir1.ToString()); Cuadrado cu1 = new Cuadrado (5.5); Console.WriteLine ("Cu1: " + cu1.ToString()); Triangulo t1 = new Triangulo (5); Triangulo t2 = new Triangulo (); Console.WriteLine ("T1: " + t1.ToString()); Console.WriteLine ("T2: " + t2.ToString()); Console.ReadLine (); } } }
using System; namespace egb.Circunferencia { class Circunferencia { // Campos double radio = 0; double area = 0; double longitud = 0; // Props public double Radio { get { return this.radio; } set { if (value < 0) value = 0; if (value > 100) value = 100; this.radio = value; } } public double Area { get { this.area = Math.PI * Math.Pow (this.radio, 2); return this.area; } } public double Longitud { get { this.longitud = 2 * Math.PI * this.radio; return this.longitud; } } // Constructores public Circunferencia() { radio = 0; area = 0; longitud = 0; } public Circunferencia(double r) { Radio = r; } public override string ToString () { return string.Format ("[Radio {0}, Area {1}, Longitud {2}]", this.Radio.ToString(), this.Area.ToString(), this.Longitud.ToString()); } } class Inicio { public static void Main (string[] args) { Console.Title = "Clase Circunferencia"; Circunferencia c1 = new Circunferencia (); Circunferencia c2 = new Circunferencia (12); Console.WriteLine ("C1: " + c1.ToString()); Console.WriteLine ("C2: " + c2.ToString()); Console.WriteLine ("Cambiando a C1..."); c1.Radio = 105; Console.WriteLine ("C1: " + c1.ToString()); Console.ReadLine (); } } }
mit
C#
282f9cecf8d817fee022fa8ea9c04737ff5dbdba
drop comments from rules
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/SnapshotService/RawRuleLinterExtensions.cs
src/FilterLists.Services/SnapshotService/RawRuleLinterExtensions.cs
namespace FilterLists.Services.SnapshotService { public static class RawRuleLinterExtensions { public static string LintStringForMySql(this string rule) { rule = rule.TrimLeadingAndTrailingWhitespace(); rule = rule.DropIfEmpty(); rule = rule.DropIfComment(); rule = rule.DropIfTooLong(); rule = rule.DropIfContainsBackslashSingleQuote(); rule = rule.TrimSingleBackslashFromEnd(); return rule; } private static string TrimLeadingAndTrailingWhitespace(this string rule) { char[] charsToTrim = {' ', '\t'}; return rule.Trim(charsToTrim); } private static string DropIfEmpty(this string rule) { return rule == "" ? null : rule; } private static string DropIfComment(this string rule) { if (rule != null) return rule.StartsWith(@"!") && !rule.StartsWith(@"!#") ? null : rule; return null; } private static string DropIfTooLong(this string rule) { return rule?.Length > 8192 ? null : rule; } private static string DropIfContainsBackslashSingleQuote(this string rule) { if (rule != null) return rule.Contains(@"\'") ? null : rule; return null; } private static string TrimSingleBackslashFromEnd(this string rule) { if (rule != null) return rule.EndsWith(@"\") && !rule.EndsWith(@"\\") ? rule.Remove(rule.Length - 1) : rule; return null; } } }
namespace FilterLists.Services.SnapshotService { public static class RawRuleLinterExtensions { //TODO: resolve issues and/or track dropped rules public static string LintStringForMySql(this string rule) { rule = rule.TrimLeadingAndTrailingWhitespace(); rule = rule.DropIfEmpty(); rule = rule.TrimSingleBackslashFromEnd(); rule = rule.DropIfContainsBackslashSingleQuote(); rule = rule.DropIfTooLong(); return rule; } private static string TrimLeadingAndTrailingWhitespace(this string rule) { char[] charsToTrim = {' ', '\t'}; return rule.Trim(charsToTrim); } private static string DropIfEmpty(this string rule) { return rule == "" ? null : rule; } private static string TrimSingleBackslashFromEnd(this string rule) { if (rule != null) return rule.EndsWith(@"\") && !rule.EndsWith(@"\\") ? rule.Remove(rule.Length - 1) : rule; return null; } private static string DropIfContainsBackslashSingleQuote(this string rule) { if (rule != null) return rule.Contains(@"\'") ? null : rule; return null; } private static string DropIfTooLong(this string rule) { return rule?.Length > 8192 ? null : rule; } } }
mit
C#
c744bdd0c684a33731d65ebeaa635d5f878768f2
add overload for kv store
aloneguid/config
src/Impl/Azure/Config.Net.Azure.KeyVault/ConfigurationExtensions.cs
src/Impl/Azure/Config.Net.Azure.KeyVault/ConfigurationExtensions.cs
using System; using Config.Net.Azure.KeyVault; namespace Config.Net { public static class ConfigurationExtensions { /// <summary> /// Use Azure Key Vault by authenticating with Managed Identity /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="builder"></param> /// <param name="vaultUri">Key Vault URI</param> /// <returns></returns> public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithManagedIdentity<TInterface>( this ConfigurationBuilder<TInterface> builder, Uri vaultUri) where TInterface : class { if (vaultUri == null) { throw new ArgumentNullException(nameof(vaultUri)); } builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithManagedIdentity(vaultUri)); return builder; } /// <summary> /// Use Azure Key Vault by authenticating with service principal /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="builder"></param> /// <param name="vaultUri">Key Vault URI</param> /// <param name="clientId">Service Principal Client ID</param> /// <param name="clientSecret">Service Principal Secret</param> /// <returns></returns> public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithServicePrincipal<TInterface>( this ConfigurationBuilder<TInterface> builder, Uri vaultUri, string clientId, string clientSecret) where TInterface : class { if (vaultUri == null) { throw new ArgumentNullException(nameof(vaultUri)); } if (clientId == null) { throw new ArgumentNullException(nameof(clientId)); } if (clientSecret == null) { throw new ArgumentNullException(nameof(clientSecret)); } builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithPrincipal(vaultUri, clientId, clientSecret)); return builder; } /// <summary> /// Use Azure Key Vault by authenticating either with service principal or managed identity. If clientId and clientSecret are null, managed /// identity is used /// </summary> public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithServicePrincipalOrManagedIdentity<TInterface>( this ConfigurationBuilder<TInterface> builder, Uri vaultUri, string clientId, string clientSecret) where TInterface : class { if (vaultUri == null) { throw new ArgumentNullException(nameof(vaultUri)); } if (clientId == null && clientSecret == null) { builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithManagedIdentity(vaultUri)); } else { builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithPrincipal(vaultUri, clientId, clientSecret)); } return builder; } } }
using System; using Config.Net.Azure.KeyVault; namespace Config.Net { public static class ConfigurationExtensions { /// <summary> /// Use Azure Key Vault by authenticating with Managed Identity /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="builder"></param> /// <param name="vaultUri">Key Vault URI</param> /// <returns></returns> public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithManagedIdentity<TInterface>( this ConfigurationBuilder<TInterface> builder, Uri vaultUri) where TInterface : class { builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithManagedIdentity(vaultUri)); return builder; } /// <summary> /// Use Azure Key Vault by authenticating with service principal /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="builder"></param> /// <param name="vaultUri">Key Vault URI</param> /// <param name="clientId">Service Principal Client ID</param> /// <param name="clientSecret">Service Principal Secret</param> /// <returns></returns> public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithServicePrincipal<TInterface>( this ConfigurationBuilder<TInterface> builder, Uri vaultUri, string clientId, string clientSecret) where TInterface : class { builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithPrincipal(vaultUri, clientId, clientSecret)); return builder; } } }
mit
C#
5ad295ece50f923d419a22ee5df667db550b0408
Remove C# 6 syntax
cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium
Src/MaintainableSelenium/MaintainableSelenium.MvcPages/WebPages/Navigator.cs
Src/MaintainableSelenium/MaintainableSelenium.MvcPages/WebPages/Navigator.cs
using System; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Web.Mvc; using OpenQA.Selenium.Remote; namespace MaintainableSelenium.MvcPages.WebPages { public interface INavigator { void NavigateTo<TController>(Expression<Action<TController>> action) where TController : Controller; void OnPageReload(); event EventHandler<PageReloadEventArgs> PageReload; } public class Navigator : INavigator { private readonly RemoteWebDriver driver; private readonly string rootUrl; private static readonly Regex UrlPattern = new Regex("^https?://"); public Navigator(RemoteWebDriver driver, string rootUrl) { if (UrlPattern.IsMatch(rootUrl) == false) { throw new ArgumentException("Invalid rootUrl. It should start with http:// or https://"); } this.driver = driver; this.rootUrl = rootUrl; } public void NavigateTo<TController>(Expression<Action<TController>> action) where TController : Controller { var actionAddress = UrlHelper.BuildActionAddressFromExpression(action); var url = string.Format("{0}/{1}", rootUrl, actionAddress); driver.Navigate().GoToUrl(url); OnPageReload(); } public event EventHandler<PageReloadEventArgs> PageReload; public void OnPageReload() { var handler = PageReload; if (handler != null) { handler.Invoke(this, new PageReloadEventArgs() { NewUrl = driver.Url }); } } } public class PageReloadEventArgs:EventArgs { public string NewUrl { get; set; } } }
using System; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Web.Mvc; using OpenQA.Selenium.Remote; namespace MaintainableSelenium.MvcPages.WebPages { public interface INavigator { void NavigateTo<TController>(Expression<Action<TController>> action) where TController : Controller; void OnPageReload(); event EventHandler<PageReloadEventArgs> PageReload; } public class Navigator : INavigator { private readonly RemoteWebDriver driver; private readonly string rootUrl; private static readonly Regex UrlPattern = new Regex("^https?://"); public Navigator(RemoteWebDriver driver, string rootUrl) { if (UrlPattern.IsMatch(rootUrl) == false) { throw new ArgumentException("Invalid rootUrl. It should start with http:// or https://"); } this.driver = driver; this.rootUrl = rootUrl; } public void NavigateTo<TController>(Expression<Action<TController>> action) where TController : Controller { var actionAddress = UrlHelper.BuildActionAddressFromExpression(action); var url = string.Format("{0}/{1}", rootUrl, actionAddress); driver.Navigate().GoToUrl(url); OnPageReload(); } public event EventHandler<PageReloadEventArgs> PageReload; public void OnPageReload() { var handler = PageReload; handler?.Invoke(this, new PageReloadEventArgs() { NewUrl = driver.Url }); } } public class PageReloadEventArgs:EventArgs { public string NewUrl { get; set; } } }
mit
C#
39d9a014b7b337750d1c84d39d3ced96741920f7
Fix static SetAssemblyDescriptorResolver usage in tests
AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia
tests/Avalonia.Base.UnitTests/AssetLoaderTests.cs
tests/Avalonia.Base.UnitTests/AssetLoaderTests.cs
using System; using System.Reflection; using Avalonia.Platform; using Avalonia.Platform.Internal; using Moq; using Xunit; namespace Avalonia.Base.UnitTests; public class AssetLoaderTests : IDisposable { public class MockAssembly : Assembly {} private const string AssemblyNameWithWhitespace = "Awesome Library"; private const string AssemblyNameWithNonAscii = "Какое-то-название"; public AssetLoaderTests() { var resolver = Mock.Of<IAssemblyDescriptorResolver>(); var descriptor = CreateAssemblyDescriptor(AssemblyNameWithWhitespace); Mock.Get(resolver).Setup(x => x.GetAssembly(AssemblyNameWithWhitespace)).Returns(descriptor); descriptor = CreateAssemblyDescriptor(AssemblyNameWithNonAscii); Mock.Get(resolver).Setup(x => x.GetAssembly(AssemblyNameWithNonAscii)).Returns(descriptor); AssetLoader.SetAssemblyDescriptorResolver(resolver); } [Fact] public void AssemblyName_With_Whitespace_Should_Load_Resm() { var uri = new Uri($"resm:Avalonia.Base.UnitTests.Assets.something?assembly={AssemblyNameWithWhitespace}"); var loader = new AssetLoader(); var assemblyActual = loader.GetAssembly(uri, null); Assert.Equal(AssemblyNameWithWhitespace, assemblyActual?.FullName); } [Fact(Skip = "RegisterResUriParsers breaks this test. See https://github.com/AvaloniaUI/Avalonia/issues/2555.")] public void AssemblyName_With_Non_ASCII_Should_Load_Avares() { var uri = new Uri($"avares://{AssemblyNameWithNonAscii}/Assets/something"); var loader = new AssetLoader(); var assemblyActual = loader.GetAssembly(uri, null); Assert.Equal(AssemblyNameWithNonAscii, assemblyActual?.FullName); } private static IAssemblyDescriptor CreateAssemblyDescriptor(string assemblyName) { var assembly = Mock.Of<MockAssembly>(); Mock.Get(assembly).Setup(x => x.GetName()).Returns(new AssemblyName(assemblyName)); Mock.Get(assembly).Setup(x => x.FullName).Returns(assemblyName); var descriptor = Mock.Of<IAssemblyDescriptor>(); Mock.Get(descriptor).Setup(x => x.Assembly).Returns(assembly); return descriptor; } public void Dispose() { AssetLoader.SetAssemblyDescriptorResolver(new AssemblyDescriptorResolver()); } }
using System; using System.Reflection; using Avalonia.Platform; using Avalonia.Platform.Internal; using Moq; using Xunit; namespace Avalonia.Base.UnitTests; public class AssetLoaderTests { public class MockAssembly : Assembly {} private const string AssemblyNameWithWhitespace = "Awesome Library"; private const string AssemblyNameWithNonAscii = "Какое-то-название"; static AssetLoaderTests() { var resolver = Mock.Of<IAssemblyDescriptorResolver>(); var descriptor = CreateAssemblyDescriptor(AssemblyNameWithWhitespace); Mock.Get(resolver).Setup(x => x.GetAssembly(AssemblyNameWithWhitespace)).Returns(descriptor); descriptor = CreateAssemblyDescriptor(AssemblyNameWithNonAscii); Mock.Get(resolver).Setup(x => x.GetAssembly(AssemblyNameWithNonAscii)).Returns(descriptor); AssetLoader.SetAssemblyDescriptorResolver(resolver); } [Fact] public void AssemblyName_With_Whitespace_Should_Load_Resm() { var uri = new Uri($"resm:Avalonia.Base.UnitTests.Assets.something?assembly={AssemblyNameWithWhitespace}"); var loader = new AssetLoader(); var assemblyActual = loader.GetAssembly(uri, null); Assert.Equal(AssemblyNameWithWhitespace, assemblyActual?.FullName); } [Fact(Skip = "RegisterResUriParsers breaks this test. Investigate.")] public void AssemblyName_With_Non_ASCII_Should_Load_Avares() { var uri = new Uri($"avares://{AssemblyNameWithNonAscii}/Assets/something"); var loader = new AssetLoader(); var assemblyActual = loader.GetAssembly(uri, null); Assert.Equal(AssemblyNameWithNonAscii, assemblyActual?.FullName); } private static IAssemblyDescriptor CreateAssemblyDescriptor(string assemblyName) { var assembly = Mock.Of<MockAssembly>(); Mock.Get(assembly).Setup(x => x.GetName()).Returns(new AssemblyName(assemblyName)); Mock.Get(assembly).Setup(x => x.FullName).Returns(assemblyName); var descriptor = Mock.Of<IAssemblyDescriptor>(); Mock.Get(descriptor).Setup(x => x.Assembly).Returns(assembly); return descriptor; } }
mit
C#
9dc8267b12213eb809d3b4f1f80b8e4f7ac3fa73
Remove debug logs
PUT-PTM/SuperTrackMayhem,PUT-PTM/SuperTrackMayhem,PUT-PTM/SuperTrackMayhem
UnityProject/Assets/Scripts/RaceLogic/Timer.cs
UnityProject/Assets/Scripts/RaceLogic/Timer.cs
using UnityEngine; using UnityEngine.UI; public class Timer : MonoBehaviour { private float _timeStart; private float _timeLastCheckpoint; public Text SinceStart; public Text SinceLastCheckpoint; private bool _inRace = false; void Start() { Checkpoint.CheckPointReached += OnCheckpointReached; LevelManager.RaceStarted += OnRaceStarted; LevelManager.RaceFinished += OnRaceFinished; SinceStart.text = "0.0"; SinceLastCheckpoint.text = "0.0"; } private void Update() { if (!_inRace) { return; } float timeSinceStart = (Time.time - _timeStart); float timeSinceCheckpoint = (Time.time - _timeLastCheckpoint); SinceStart.text = timeSinceStart.ToString("0.0"); SinceLastCheckpoint.text = timeSinceCheckpoint.ToString("0.0"); } private void OnRaceStarted() { _timeStart = Time.time; _timeLastCheckpoint = Time.time; _inRace = true; } void OnCheckpointReached(int checkpoint) { _timeLastCheckpoint = Time.time; } void OnRaceFinished() { _inRace = false; } void OnDestroy() { Checkpoint.CheckPointReached -= OnCheckpointReached; LevelManager.RaceStarted -= OnRaceStarted; LevelManager.RaceFinished -= OnRaceFinished; } }
using UnityEngine; using UnityEngine.UI; public class Timer : MonoBehaviour { private float _timeStart; private float _timeLastCheckpoint; public Text SinceStart; public Text SinceLastCheckpoint; private bool _inRace = false; void Start() { Checkpoint.CheckPointReached += OnCheckpointReached; LevelManager.RaceStarted += OnRaceStarted; LevelManager.RaceFinished += OnRaceFinished; SinceStart.text = "0.0"; SinceLastCheckpoint.text = "0.0"; } private void Update() { if (!_inRace) { return; } float timeSinceStart = (Time.time - _timeStart); float timeSinceCheckpoint = (Time.time - _timeLastCheckpoint); Debug.Log("----------"); Debug.Log(timeSinceStart); Debug.Log(timeSinceCheckpoint); SinceStart.text = timeSinceStart.ToString("0.0"); SinceLastCheckpoint.text = timeSinceCheckpoint.ToString("0.0"); } private void OnRaceStarted() { _timeStart = Time.time; _timeLastCheckpoint = Time.time; _inRace = true; } void OnCheckpointReached(int checkpoint) { _timeLastCheckpoint = Time.time; } void OnRaceFinished() { _inRace = false; } void OnDestroy() { Checkpoint.CheckPointReached -= OnCheckpointReached; LevelManager.RaceStarted -= OnRaceStarted; LevelManager.RaceFinished -= OnRaceFinished; } }
mit
C#
23ce4135a4c0e8657e1d788bdd3c83802d77b53b
Make attribute search more to the point
madsbangh/EasyButtons
Assets/EasyButtons/Editor/ButtonEditor.cs
Assets/EasyButtons/Editor/ButtonEditor.cs
using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => System.Attribute.IsDefined(m, typeof(ButtonAttribute), true)) .Where(m => m.GetParameters().Length == 0)) { // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { foreach (var target in targets) { method.Invoke(target, null); } } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0) .Where(m => m.GetParameters().Length == 0)) { // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { foreach (var target in targets) { method.Invoke(target, null); } } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
mit
C#
e59f43623c872f86dc333dca26dd768f5b22f17c
Fix FlashyBox regression.
paparony03/osu-framework,peppy/osu-framework,naoey/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,paparony03/osu-framework,RedNesto/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,NeoAdonis/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,NeoAdonis/osu-framework,ZLima12/osu-framework,default0/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,RedNesto/osu-framework,default0/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
osu.Framework/Graphics/Visualisation/FlashyBox.cs
osu.Framework/Graphics/Visualisation/FlashyBox.cs
// Copyright (c) 2007-2016 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK; using OpenTK.Graphics; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Sprites; namespace osu.Framework.Graphics.Visualisation { class FlashyBox : Box { Drawable target; public FlashyBox() { Size = new Vector2(4); Origin = Anchor.Centre; Colour = Color4.Red; Alpha = 0.5f; } public Drawable Target { set { target = value; } } public override Quad ScreenSpaceDrawQuad => target.ScreenSpaceDrawQuad; protected override void LoadComplete() { base.LoadComplete(); FadeColour(Color4.Red, 500); Delay(500); FadeColour(Color4.White, 500); Delay(500); Loop(); } } }
// Copyright (c) 2007-2016 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK; using OpenTK.Graphics; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Sprites; namespace osu.Framework.Graphics.Visualisation { class FlashyBox : Box { Drawable target; public FlashyBox() { Size = new Vector2(4); Origin = Anchor.Centre; Colour = Color4.Red; Alpha = 0.5f; } public Drawable Target { set { target = value; } } public override Quad ScreenSpaceDrawQuad => target.ScreenSpaceDrawQuad; protected override void Load(BaseGame game) { base.Load(game); FadeColour(Color4.Red, 500); Delay(500); FadeColour(Color4.White, 500); Delay(500); Loop(); } } }
mit
C#
448714aff76f4fd9cfd2e26f76fced9023512369
Use enum
ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Statistics/DotNetRuntimeListener.cs
osu.Framework/Statistics/DotNetRuntimeListener.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics.Tracing; namespace osu.Framework.Statistics { // https://medium.com/criteo-labs/c-in-process-clr-event-listeners-with-net-core-2-2-ef4075c14e87 internal sealed class DotNetRuntimeListener : EventListener { private const int gc_keyword = 0x0000001; private const string statistics_grouping = "GC"; protected override void OnEventSourceCreated(EventSource eventSource) { if (eventSource.Name.Equals("Microsoft-Windows-DotNETRuntime")) EnableEvents(eventSource, EventLevel.Verbose, (EventKeywords)gc_keyword); } protected override void OnEventWritten(EventWrittenEventArgs data) { switch ((EventType)data.EventId) { case EventType.GCStart_V1: // https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcstart_v1_event GlobalStatistics.Get<int>(statistics_grouping, $"Collections Gen{data.Payload[1]}").Value++; break; case EventType.GCHeapStats_V1: // https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v1_event for (int i = 0; i <= 6; i += 2) GlobalStatistics.Get<ulong>(statistics_grouping, $"Size Gen{i / 2}").Value = (ulong)data.Payload[i]; GlobalStatistics.Get<ulong>(statistics_grouping, "Finalization queue length").Value = (ulong)data.Payload[9]; GlobalStatistics.Get<uint>(statistics_grouping, "Pinned objects").Value = (uint)data.Payload[10]; break; } } private enum EventType { GCStart_V1 = 1, GCHeapStats_V1 = 4, } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics.Tracing; namespace osu.Framework.Statistics { // https://medium.com/criteo-labs/c-in-process-clr-event-listeners-with-net-core-2-2-ef4075c14e87 internal sealed class DotNetRuntimeListener : EventListener { private const int gc_keyword = 0x0000001; private const string statistics_grouping = "GC"; protected override void OnEventSourceCreated(EventSource eventSource) { if (eventSource.Name.Equals("Microsoft-Windows-DotNETRuntime")) { EnableEvents( eventSource, EventLevel.Verbose, (EventKeywords)(gc_keyword) ); } } protected override void OnEventWritten(EventWrittenEventArgs eventData) { switch (eventData.EventId) { case 1: // GCStart_V1 https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcstart_v1_event GlobalStatistics.Get<int>(statistics_grouping, $"Collections Gen{eventData.Payload[1]}").Value++; break; case 4: // GCHeapStats_V1 https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v1_event for (int i = 0; i <= 6; i += 2) GlobalStatistics.Get<ulong>(statistics_grouping, $"Size Gen{i / 2}").Value = (ulong)eventData.Payload[i]; GlobalStatistics.Get<ulong>(statistics_grouping, "Finalization queue length").Value = (ulong)eventData.Payload[9]; GlobalStatistics.Get<uint>(statistics_grouping, "Pinned objects").Value = (uint)eventData.Payload[10]; break; } } } }
mit
C#
0363c0a19f0e045044d75488e37b8157bd207cae
Add windows mouse support
ChillyFlashER/OpenInput
src/OpenInput.Windows/Mouse.cs
src/OpenInput.Windows/Mouse.cs
namespace OpenInput { using System; using DI_Mouse = SharpDX.DirectInput.Mouse; /// <summary> /// /// </summary> public class Mouse : IMouse { /// <inheritdoc /> public string Name => mouse.Information.ProductName.Trim('\0'); internal readonly DI_Mouse mouse; /// <summary> /// /// </summary> public Mouse() { var directInput = DeviceService.Service.Value.directInput; this.mouse = new DI_Mouse(directInput); this.mouse.Acquire(); } /// <inheritdoc /> public void SetHandle(IntPtr handle) { throw new NotImplementedException(); } /// <inheritdoc /> public void SetPosition(int x, int y) { throw new NotImplementedException(); } /// <inheritdoc /> public MouseState GetCurrentState() { if (mouse.IsDisposed) return new MouseState(); mouse.Poll(); var state = mouse.GetCurrentState(); return new MouseState( state.X, state.Y, state.Z, state.Buttons[0], state.Buttons[1], state.Buttons[2], state.Buttons[3], state.Buttons[4]); } } }
namespace OpenInput { using System; using DI_Mouse = SharpDX.DirectInput.Mouse; /// <summary> /// /// </summary> public class Mouse : IMouse { /// <inheritdoc /> public string Name => mouse.Information.ProductName.Trim('\0'); internal readonly DI_Mouse mouse; /// <summary> /// /// </summary> public Mouse() { var directInput = DeviceService.Service.Value.directInput; this.mouse = new DI_Mouse(directInput); this.mouse.Acquire(); } /// <inheritdoc /> public void SetHandle(IntPtr handle) { throw new NotImplementedException(); } /// <inheritdoc /> public void SetPosition(int x, int y) { throw new NotImplementedException(); } /// <inheritdoc /> public MouseState GetCurrentState() { throw new NotImplementedException(); } } }
mit
C#
d60eac7967a15544e36716d9e594b3e46114ca91
Fix quicksearch hard coding
episerver/QuicksilverB2B,vnbaaij/QuicksilverB2B,vnbaaij/QuicksilverB2B,episerver/QuicksilverB2B,episerver/QuicksilverB2B,vnbaaij/QuicksilverB2B
Sources/EPiServer.Reference.Commerce.Site/Views/Search/QuickSearch.cshtml
Sources/EPiServer.Reference.Commerce.Site/Views/Search/QuickSearch.cshtml
@model IEnumerable<EPiServer.Reference.Commerce.Site.Features.Product.ViewModels.ProductViewModel> @{ Layout = null; } <ul class="product-dropdown product-row list-unstyled"> @foreach (var product in Model.Where(x => x.DiscountedPrice.HasValue)) { bool hasDiscount = product.DiscountedPrice.GetValueOrDefault() < product.PlacedPrice; string productLevelClass = hasDiscount ? "list-group-item product-item has-discount" : "list-group-item product-item"; bool renderWishListButtons = User.Identity.IsAuthenticated && ViewBag.IsWishList != null && ViewBag.IsWishList == true; <li class="@productLevelClass"> <a href="@product.Url" class="link--black"> <div class="media"> <div class="media-left"> <img src="@product.ImageUrl" alt="@product.DisplayName" class="media-object product-row__item__image" /> </div> <div class="media-body"> <h3 class="product-row__item__title">@product.DisplayName</h3> @if (hasDiscount) { <h4 class="product-row__item__price product-price--discount">@Helpers.RenderMoney(product.DiscountedPrice.GetValueOrDefault())</h4> } <h4 class="product-row__item__price product-price">@Helpers.RenderMoney(product.PlacedPrice)</h4> <span class="product-row__item__brand product-brand text-muted">@product.Brand</span> <p class="product-row__item__description">@* TODO: Add the product description to the product view model *@</p> </div> </div> </a> </li> } </ul>
@model IEnumerable<EPiServer.Reference.Commerce.Site.Features.Product.ViewModels.ProductViewModel> @{ Layout = null; } <ul class="product-dropdown product-row list-unstyled"> @foreach (var product in Model.Where(x => x.DiscountedPrice.HasValue)) { bool hasDiscount = product.DiscountedPrice.GetValueOrDefault() < product.PlacedPrice; string productLevelClass = hasDiscount ? "list-group-item product-item has-discount" : "list-group-item product-item"; bool renderWishListButtons = User.Identity.IsAuthenticated && ViewBag.IsWishList != null && ViewBag.IsWishList == true; <li class="@productLevelClass"> <a href="@product.Url" class="link--black"> <div class="media"> <div class="media-left"> <img src="@product.ImageUrl" alt="@product.DisplayName" class="media-object product-row__item__image" /> </div> <div class="media-body"> <h3 class="product-row__item__title">@product.DisplayName</h3> @if (hasDiscount) { <h4 class="product-row__item__price product-price--discount">@Helpers.RenderMoney(product.DiscountedPrice.GetValueOrDefault())</h4> } <h4 class="product-row__item__price product-price">@Helpers.RenderMoney(product.PlacedPrice)</h4> <span class="product-row__item__brand product-brand text-muted">Lyle &amp; Scott</span> <p class="product-row__item__description">Jacket from Lyle &amp; Scott. Rounded neckline with collar and button closure. Zipper closure and two pockets at front. Elastic at each cuff and hem. Lined. Made of 100% Cotton.</p> </div> </div> </a> </li> } </ul>
apache-2.0
C#
3b10b149976288314bddfdf8ae788e22a2c98f31
Use DeveloperExceptionPage only in DEV Enviroment
dotnetgeek/shariff-backend-dotnet,dotnetgeek/shariff-backend-dotnet
src/Startup.cs
src/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Shariff.Backend { public class Startup { public Startup( IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices( IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseMvc(); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Shariff.Backend { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseMvc(); } } }
mit
C#
bff2d12f8bee1701884dc126a907629d288ae44e
Remove length property
mstrother/BmpListener
BmpListener/Bgp/BgpMessage.cs
BmpListener/Bgp/BgpMessage.cs
using System; using System.Linq; using Newtonsoft.Json; namespace BmpListener.Bgp { public abstract class BgpMessage { protected BgpMessage(ref ArraySegment<byte> data) { var bgpHeader = new BgpHeader(data); Type = bgpHeader.Type; var msgLength = (int) bgpHeader.Length - 19; data = new ArraySegment<byte>(data.Array, 19, msgLength); } public MessageType Type { get; } public abstract void DecodeFromBytes(ArraySegment<byte> data); public static BgpMessage GetBgpMessage(ArraySegment<byte> data) { var msgType = (MessageType) data.ElementAt(18); switch (msgType) { case MessageType.Open: return new BgpOpenMessage(data); case MessageType.Update: return new BgpUpdateMessage(data); case MessageType.Notification: return new BgpNotification(data); case MessageType.Keepalive: throw new NotImplementedException(); case MessageType.RouteRefresh: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }
using System; using System.Linq; using Newtonsoft.Json; namespace BmpListener.Bgp { public abstract class BgpMessage { protected BgpMessage(ref ArraySegment<byte> data) { var bgpHeader = new BgpHeader(data); Length = bgpHeader.Length; Type = bgpHeader.Type; var msgLength = (int) bgpHeader.Length - 19; data = new ArraySegment<byte>(data.Array, 19, msgLength); } [JsonIgnore] public uint Length { get; } public MessageType Type { get; } public abstract void DecodeFromBytes(ArraySegment<byte> data); public static BgpMessage GetBgpMessage(ArraySegment<byte> data) { var msgType = (MessageType) data.ElementAt(18); switch (msgType) { case MessageType.Open: return new BgpOpenMessage(data); case MessageType.Update: return new BgpUpdateMessage(data); case MessageType.Notification: return new BgpNotification(data); case MessageType.Keepalive: throw new NotImplementedException(); case MessageType.RouteRefresh: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }
mit
C#
32b745a8a7b668ece52c9d92bad732525f4d2714
Update ResponseMessageMusic.cs
lishewen/WeiXinMPSDK,JeffreySu/WxOpen,down4u/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,down4u/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,wanddy/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,wanddy/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WxOpen
Senparc.Weixin.MP/Senparc.Weixin.MP/Entities/Response/ResponseMessageMusic.cs
Senparc.Weixin.MP/Senparc.Weixin.MP/Entities/Response/ResponseMessageMusic.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Senparc.Weixin.MP.Entities { public class ResponseMessageMusic : ResponseMessageBase, IResponseMessageBase { public override ResponseMsgType MsgType { get { return ResponseMsgType.Music; } } public Music Music { get; set; } //public string ThumbMediaId { get; set; } //把该参数移动到Music对象内部 public ResponseMessageMusic() { Music = new Music(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Senparc.Weixin.MP.Entities { public class ResponseMessageMusic : ResponseMessageBase, IResponseMessageBase { public override ResponseMsgType MsgType { get { return ResponseMsgType.Music; } } public Music Music { get; set; } public string ThumbMediaId { get; set; } public ResponseMessageMusic() { Music = new Music(); } } }
apache-2.0
C#
c98a78c376a312330521fd87cee531d06e70f43b
Use IR sensors
smoy/Monkey.Robotics,milindur/Monkey.Robotics,milindur/Monkey.Robotics,DynamicDevices/Monkey.Robotics,smoy/Monkey.Robotics,islandof/Monkey.Robotics,xamarin/Monkey.Robotics,islandof/Monkey.Robotics,DynamicDevices/Monkey.Robotics,milindur/Monkey.Robotics,smoy/Monkey.Robotics,milindur/Monkey.Robotics,DynamicDevices/Monkey.Robotics,ofenerci/Monkey.Robotics,fburel/Monkey.Robotics,venkatarajasekhar/Monkey.Robotics,venkatarajasekhar/Monkey.Robotics,fburel/Monkey.Robotics,ofenerci/Monkey.Robotics,ofenerci/Monkey.Robotics,islandof/Monkey.Robotics,venkatarajasekhar/Monkey.Robotics,milindur/Monkey.Robotics,smoy/Monkey.Robotics,fburel/Monkey.Robotics,smoy/Monkey.Robotics
Source/Xamarin.Robotics/Xamarin.Robotics.Micro.Core.Netduino2Tests/Program.cs
Source/Xamarin.Robotics/Xamarin.Robotics.Micro.Core.Netduino2Tests/Program.cs
using SecretLabs.NETMF.Hardware.Netduino; using System; using System.Threading; namespace Xamarin.Robotics.Micro.Core.Netduino2Tests { public class Program { public static void Main() { var led = new Microsoft.SPOT.Hardware.OutputPort(Pins.ONBOARD_LED, false); for (var i = 0; i < 3; i++) { led.Write(true); Thread.Sleep(250); led.Write(false); Thread.Sleep(250); } // MotorShield (deprecated) // TestDrunkenRobotWithMotorShield.Run(); // TestSensors.Run (); // TestDrunkenRobot.Run (); // TestWallBouncingRobotWithHBridge.Run (); // No eyes, just motors // TestDrunkenRobotWithHbridge.Run (); // Requires IR sensors TestTwoEyedRobotWithHbridge.Run (); } } }
using SecretLabs.NETMF.Hardware.Netduino; using System; using System.Threading; namespace Xamarin.Robotics.Micro.Core.Netduino2Tests { public class Program { public static void Main() { var led = new Microsoft.SPOT.Hardware.OutputPort(Pins.ONBOARD_LED, false); for (var i = 0; i < 3; i++) { led.Write(true); Thread.Sleep(250); led.Write(false); Thread.Sleep(250); } //TestDrunkenRobotWithMotorShield.Run(); // TestSensors.Run (); // TestDrunkenRobot.Run (); // TestWallBouncingRobotWithHBridge.Run (); // TestDrunkenRobotWithHbridge.Run (); TestTwoEyedRobotWithHbridge.Run (); } } }
apache-2.0
C#
194c39914e04d106e8e35af376988d5b54ecbcf9
Update CuidCorrelationServiceTests.cs
tiksn/TIKSN-Framework
TIKSN.UnitTests.Shared/Integration/Correlation/CuidCorrelationServiceTests.cs
TIKSN.UnitTests.Shared/Integration/Correlation/CuidCorrelationServiceTests.cs
using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using TIKSN.DependencyInjection; using Xunit; namespace TIKSN.Integration.Correlation.Tests { public class CuidCorrelationServiceTests { private readonly ICorrelationService _correlationService; public CuidCorrelationServiceTests() { var services = new ServiceCollection(); services.AddFrameworkPlatform(); services.AddSingleton<ICorrelationService, CuidCorrelationService>(); var serviceProvider = services.BuildServiceProvider(); _correlationService = serviceProvider.GetRequiredService<ICorrelationService>(); } [Fact] public void GenerateAndParse() { var correlationID = _correlationService.Generate(); var correlationIDFromString = _correlationService.Create(correlationID.ToString()); var correlationIDFromBytes = _correlationService.Create(correlationID.ToByteArray()); correlationIDFromString.Should().Be(correlationID); correlationIDFromBytes.Should().Be(correlationID); correlationIDFromString.Should().Be(correlationIDFromBytes); } } }
using Microsoft.Extensions.DependencyInjection; using TIKSN.DependencyInjection; namespace TIKSN.Integration.Correlation.Tests { public class CuidCorrelationServiceTests { private readonly ICorrelationService _correlationService; public CuidCorrelationServiceTests() { var services = new ServiceCollection(); services.AddFrameworkPlatform(); services.AddSingleton<ICorrelationService, CuidCorrelationService>(); var serviceProvider = services.BuildServiceProvider(); _correlationService = serviceProvider.GetRequiredService<ICorrelationService>(); } } }
mit
C#
ab3d765a4bc6f535fea266408d1bc2da7028fd58
Test Refactor, Evaluate using Machine.RootContext
ajlopez/ClojSharp
Src/ClojSharp.Core.Tests/EvaluateTests.cs
Src/ClojSharp.Core.Tests/EvaluateTests.cs
namespace ClojSharp.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Compiler; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class EvaluateTests { private Machine machine; [TestInitialize] public void Setup() { this.machine = new Machine(); } [TestMethod] public void EvaluateInteger() { Assert.AreEqual(123, this.Evaluate("123", null)); } [TestMethod] public void EvaluateSymbolInContext() { Context context = new Context(); context.SetValue("one", 1); Assert.AreEqual(1, this.Evaluate("one", context)); } [TestMethod] public void EvaluateAdd() { Assert.AreEqual(3, this.Evaluate("(+ 1 2)")); Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)")); Assert.AreEqual(5, this.Evaluate("(+ 5)")); Assert.AreEqual(0, this.Evaluate("(+)")); } [TestMethod] public void EvaluateSubtract() { Assert.AreEqual(-1, this.Evaluate("(- 1 2)")); Assert.AreEqual(-4, this.Evaluate("(- 1 2 3)")); Assert.AreEqual(-5, this.Evaluate("(- 5)")); } private object Evaluate(string text) { return this.Evaluate(text, this.machine.RootContext); } private object Evaluate(string text, Context context) { Parser parser = new Parser(text); var expr = parser.ParseExpression(); Assert.IsNull(parser.ParseExpression()); return this.machine.Evaluate(expr, context); } } }
namespace ClojSharp.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Compiler; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class EvaluateTests { private Machine machine; [TestInitialize] public void Setup() { this.machine = new Machine(); } [TestMethod] public void EvaluateInteger() { Assert.AreEqual(123, this.Evaluate("123", null)); } [TestMethod] public void EvaluateSymbolInContext() { Context context = new Context(); context.SetValue("one", 1); Assert.AreEqual(1, this.Evaluate("one", context)); } [TestMethod] public void EvaluateAdd() { Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext)); Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext)); Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext)); Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext)); } [TestMethod] public void EvaluateSubtract() { Assert.AreEqual(-1, this.Evaluate("(- 1 2)", this.machine.RootContext)); Assert.AreEqual(-4, this.Evaluate("(- 1 2 3)", this.machine.RootContext)); Assert.AreEqual(-5, this.Evaluate("(- 5)", this.machine.RootContext)); } private object Evaluate(string text, Context context) { Parser parser = new Parser(text); var expr = parser.ParseExpression(); Assert.IsNull(parser.ParseExpression()); return this.machine.Evaluate(expr, context); } } }
mit
C#
eca4e04dce69ad3acef112772a591e148f654c3b
Define PhoneNumber struct
SICU-Stress-Measurement-System/frontend-cs
StressMeasurementSystem/Models/Patient.cs
StressMeasurementSystem/Models/Patient.cs
namespace StressMeasurementSystem.Models { public class Patient { #region Structs struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } struct PhoneNumber { internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } #endregion } }
namespace StressMeasurementSystem.Models { public class Patient { #region Structs struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } #endregion } }
apache-2.0
C#
2b08a3ed6c6a4cf61f5f318a1d7c14c3b30a011d
Set version to 0.8.0
jaenyph/DelegateDecompiler,hazzik/DelegateDecompiler,morgen2009/DelegateDecompiler
src/DelegateDecompiler/Properties/AssemblyInfo.cs
src/DelegateDecompiler/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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 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("cec0a257-502b-4718-91c3-9e67555c5e1b")] // 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.8.0.0")] [assembly: AssemblyFileVersion("0.8.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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 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("cec0a257-502b-4718-91c3-9e67555c5e1b")] // 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.7.2.0")] [assembly: AssemblyFileVersion("0.7.2.0")]
mit
C#
08a54a4e99d10fb789f228caf4d0e4b3976a728b
Change the page title to show the name of our business
ISEPTrabalhos/BizzKit,ISEPTrabalhos/BizzKit,ISEPTrabalhos/BizzKit,ISEPTrabalhos/BizzKit
WebDev/WebDev/Views/Shared/_Layout.cshtml
WebDev/WebDev/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>BizzKit :: @ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("BizzKit", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> @Html.Partial("_LoginPartial") </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> @Html.Partial("_LoginPartial") </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
apache-2.0
C#
e02e1405c13164be2566a1f7fe194984ea9bd6e6
Split config and command line parsing into separate private methods.
Cisien/OniBot
OniBot/Program.cs
OniBot/Program.cs
using Microsoft.Extensions.Configuration; using OniBot.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace OniBot { class Program { static void Main(string[] args) { var ctx = new SynchronizationContext(); AsyncPump.Run(a => MainAsync(args), args); Console.ReadKey(); } private static readonly CancellationTokenSource cts = new CancellationTokenSource(); private static async Task MainAsync(string[] args) { Console.CancelKeyPress += (s, e) => { cts.Cancel(); }; try { var commandLineConfig = ParseCommandline(args); var config = BuildConfig(commandLineConfig); await Task.Yield(); } catch (Exception ex) { Console.WriteLine(ex); } } private static IConfigurationRoot BuildConfig(IConfigurationRoot commandLineConfig) { var environment = commandLineConfig["environment"]?.ToLower() ?? "production"; var config = new ConfigurationBuilder(); config.AddJsonFile("config.json", false); config.AddJsonFile($"config.{environment}.json", true); config.AddEnvironmentVariables(); if (environment == "development") { config.AddUserSecrets(); } config.AddInMemoryCollection(commandLineConfig.AsEnumerable()); var configuration = config.Build(); #if DEBUG foreach (var key in configuration.AsEnumerable()) { Console.WriteLine($"{key.Key.PadRight(40)}: {key.Value}"); } #endif return configuration; } private static IConfigurationRoot ParseCommandline(string[] args) { var switchMappings = new Dictionary<string, string> { { "-environment", "environment" } }; var commandLine = new ConfigurationBuilder(); commandLine.AddCommandLine(args, switchMappings); var commandLineConfig = commandLine.Build(); return commandLineConfig; } } }
using Microsoft.Extensions.Configuration; using OniBot.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace OniBot { class Program { static void Main(string[] args) { var ctx = new SynchronizationContext(); AsyncPump.Run(a => MainAsync(args), args); } private static async Task MainAsync(string[] args) { try { var switchMappings = new Dictionary<string, string> { { "-environment", "environment" } }; var commandLine = new ConfigurationBuilder(); commandLine.AddCommandLine(args, switchMappings); var commandLineConfig = commandLine.Build(); var environment = commandLineConfig["environment"]?.ToLower() ?? "production"; var config = new ConfigurationBuilder(); config.AddJsonFile("config.json", false); config.AddJsonFile($"config.{environment}.json", true); config.AddEnvironmentVariables(); if (environment == "development") { config.AddUserSecrets(); } config.AddInMemoryCollection(commandLineConfig.AsEnumerable()); var configuration = config.Build(); foreach (var key in configuration.AsEnumerable()) { Console.WriteLine($"{key.Key.PadRight(40)}: {key.Value}"); } await Task.Yield(); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadKey(); } } }
apache-2.0
C#
ebaaf9546aaa1aace3863b115004db7e02431f70
Improve diff.
stephentoub/roslyn,TyOverby/roslyn,orthoxerox/roslyn,robinsedlaczek/roslyn,jmarolf/roslyn,gafter/roslyn,reaction1989/roslyn,kelltrick/roslyn,yeaicc/roslyn,cston/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,khyperia/roslyn,cston/roslyn,aelij/roslyn,mavasani/roslyn,jamesqo/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,mattscheffer/roslyn,Giftednewt/roslyn,jcouv/roslyn,TyOverby/roslyn,genlu/roslyn,nguerrera/roslyn,mavasani/roslyn,genlu/roslyn,tmat/roslyn,amcasey/roslyn,heejaechang/roslyn,tvand7093/roslyn,shyamnamboodiripad/roslyn,tmeschter/roslyn,agocke/roslyn,mattscheffer/roslyn,jamesqo/roslyn,bkoelman/roslyn,AlekseyTs/roslyn,dotnet/roslyn,DustinCampbell/roslyn,abock/roslyn,dotnet/roslyn,AlekseyTs/roslyn,srivatsn/roslyn,davkean/roslyn,DustinCampbell/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,srivatsn/roslyn,pdelvo/roslyn,nguerrera/roslyn,jcouv/roslyn,dpoeschl/roslyn,Hosch250/roslyn,OmarTawfik/roslyn,brettfo/roslyn,pdelvo/roslyn,mmitche/roslyn,MattWindsor91/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,AmadeusW/roslyn,yeaicc/roslyn,MichalStrehovsky/roslyn,Giftednewt/roslyn,davkean/roslyn,amcasey/roslyn,khyperia/roslyn,aelij/roslyn,bartdesmet/roslyn,lorcanmooney/roslyn,reaction1989/roslyn,agocke/roslyn,tannergooding/roslyn,jmarolf/roslyn,sharwell/roslyn,jkotas/roslyn,mavasani/roslyn,Giftednewt/roslyn,robinsedlaczek/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,OmarTawfik/roslyn,gafter/roslyn,jcouv/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,AmadeusW/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,CaptainHayashi/roslyn,yeaicc/roslyn,lorcanmooney/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,amcasey/roslyn,jamesqo/roslyn,CaptainHayashi/roslyn,tvand7093/roslyn,jasonmalinowski/roslyn,genlu/roslyn,AnthonyDGreen/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,VSadov/roslyn,pdelvo/roslyn,bartdesmet/roslyn,gafter/roslyn,sharwell/roslyn,bkoelman/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,brettfo/roslyn,tmeschter/roslyn,orthoxerox/roslyn,cston/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,eriawan/roslyn,physhi/roslyn,agocke/roslyn,robinsedlaczek/roslyn,panopticoncentral/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,xasx/roslyn,bkoelman/roslyn,swaroop-sridhar/roslyn,xasx/roslyn,khyperia/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,dpoeschl/roslyn,tvand7093/roslyn,eriawan/roslyn,heejaechang/roslyn,MattWindsor91/roslyn,paulvanbrenk/roslyn,srivatsn/roslyn,OmarTawfik/roslyn,weltkante/roslyn,DustinCampbell/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,paulvanbrenk/roslyn,xasx/roslyn,sharwell/roslyn,wvdd007/roslyn,physhi/roslyn,CaptainHayashi/roslyn,wvdd007/roslyn,diryboy/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,Hosch250/roslyn,davkean/roslyn,diryboy/roslyn,mmitche/roslyn,lorcanmooney/roslyn,mattscheffer/roslyn,tannergooding/roslyn,brettfo/roslyn,stephentoub/roslyn,kelltrick/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,AnthonyDGreen/roslyn,dpoeschl/roslyn,jkotas/roslyn,KirillOsenkov/roslyn,jkotas/roslyn,abock/roslyn,AnthonyDGreen/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,abock/roslyn,dotnet/roslyn,eriawan/roslyn,MattWindsor91/roslyn,orthoxerox/roslyn,kelltrick/roslyn,paulvanbrenk/roslyn,swaroop-sridhar/roslyn,tmeschter/roslyn,tmat/roslyn
src/Features/Core/Portable/DocumentHighlighting/IDocumentHighlightsService.cs
src/Features/Core/Portable/DocumentHighlighting/IDocumentHighlightsService.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentHighlighting { internal enum HighlightSpanKind { None, Definition, Reference, WrittenReference, } internal struct HighlightSpan { public TextSpan TextSpan { get; } public HighlightSpanKind Kind { get; } public HighlightSpan(TextSpan textSpan, HighlightSpanKind kind) : this() { this.TextSpan = textSpan; this.Kind = kind; } } internal struct DocumentHighlights { public Document Document { get; } public ImmutableArray<HighlightSpan> HighlightSpans { get; } public DocumentHighlights(Document document, ImmutableArray<HighlightSpan> highlightSpans) { this.Document = document; this.HighlightSpans = highlightSpans; } } /// <summary> /// Note: This is the new version of the language service and superceded the same named type /// in the EditorFeatures layer. /// </summary> internal interface IDocumentHighlightsService : ILanguageService { Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentHighlighting { internal enum HighlightSpanKind { None, Definition, Reference, WrittenReference, } internal struct HighlightSpan { public TextSpan TextSpan { get; } public HighlightSpanKind Kind { get; } public HighlightSpan(TextSpan textSpan, HighlightSpanKind kind) : this() { this.TextSpan = textSpan; this.Kind = kind; } } internal struct DocumentHighlights { public Document Document { get; } public ImmutableArray<HighlightSpan> HighlightSpans { get; } public DocumentHighlights(Document document, ImmutableArray<HighlightSpan> highlightSpans) { this.Document = document; this.HighlightSpans = highlightSpans; } } /// <summary> /// Note: This is the new version of the language service and superceded the same named type /// in the EditorFeatures layer. /// </summary> internal interface IDocumentHighlightsService : ILanguageService { Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken); } }
mit
C#
666af3597c0d0ae7972e69b0a489a881407cece3
Improve code documentation in the IComponentBuilder interface
openchain/openchain
src/Openchain.Infrastructure/IComponentBuilder.cs
src/Openchain.Infrastructure/IComponentBuilder.cs
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace Openchain.Infrastructure { /// <summary> /// Represents a builder class capable of instanciating an object of a given type. /// </summary> /// <typeparam name="T">The type of object that can be instanciated by the builder.</typeparam> public interface IComponentBuilder<out T> { /// <summary> /// Gets the name of the builder. /// </summary> string Name { get; } /// <summary> /// Initializes the builder. /// </summary> /// <param name="serviceProvider">The service provider for the current context.</param> /// <param name="configuration">The builder configuration.</param> /// <returns></returns> Task Initialize(IServiceProvider serviceProvider, IConfigurationSection configuration); /// <summary> /// Builds the target object. /// </summary> /// <param name="serviceProvider">The service provider for the current context.</param> /// <returns>The built object.</returns> T Build(IServiceProvider serviceProvider); } }
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace Openchain.Infrastructure { public interface IComponentBuilder<out T> { string Name { get; } Task Initialize(IServiceProvider serviceProvider, IConfigurationSection configuration); T Build(IServiceProvider serviceProvider); } }
apache-2.0
C#
bca76068bc43cd3821924ccad0db0785ca0be925
Fix load template source
toddams/RazorLight,gr8woo/RazorLight,gr8woo/RazorLight,toddams/RazorLight
src/RazorLight/Templating/LoadedTemplateSource.cs
src/RazorLight/Templating/LoadedTemplateSource.cs
using System; using System.IO; namespace RazorLight.Templating { public class LoadedTemplateSource : ITemplateSource { public string Content { get; private set; } public string FilePath { get; private set; } public string TemplateKey { get; } public LoadedTemplateSource(string content) : this(GetRandomString(), content) { } public LoadedTemplateSource(string key, string content) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (string.IsNullOrEmpty(content)) { throw new ArgumentNullException(nameof(content)); } this.Content = content; this.TemplateKey = key; this.FilePath = null; } private static string GetRandomString() { return Path.GetFileName(Path.GetRandomFileName()); } public TextReader CreateReader() { return new StringReader(Content); } } }
using System; using System.IO; namespace RazorLight.Templating { public class LoadedTemplateSource : ITemplateSource { public string Content { get; private set; } public string FilePath { get; private set; } public string TemplateKey { get; } public LoadedTemplateSource(string key) : this(key, GetRandomString()) { } public LoadedTemplateSource(string key, string content) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (string.IsNullOrEmpty(content)) { throw new ArgumentNullException(nameof(content)); } this.Content = content; this.TemplateKey = key; this.FilePath = null; } private static string GetRandomString() { return Path.GetFileName(Path.GetRandomFileName()); } public TextReader CreateReader() { return new StringReader(Content); } } }
apache-2.0
C#
ecb958820060c409bba5f7fd625aacb817591b75
Fix to support virtual directories/folders in IIS.
aaronpowell/glimpse-knockout,modulexcite/glimpse-knockout,modulexcite/glimpse-knockout,modulexcite/glimpse-knockout,aaronpowell/glimpse-knockout
src/VisualStudio/Glimpse.Knockout/ClientScript.cs
src/VisualStudio/Glimpse.Knockout/ClientScript.cs
using Glimpse.Core.Extensibility; namespace Glimpse.Knockout { public sealed class ClientScript : IStaticClientScript { public ScriptOrder Order { get { return ScriptOrder.IncludeAfterClientInterfaceScript; } } public string GetUri(string version) { return System.Web.VirtualPathUtility.ToAbsolute("~/Scripts/glimpse-knockout.js"); } } }
using Glimpse.Core.Extensibility; namespace Glimpse.Knockout { public sealed class ClientScript : IStaticClientScript { public ScriptOrder Order { get { return ScriptOrder.IncludeAfterClientInterfaceScript; } } public string GetUri(string version) { return "/Scripts/glimpse-knockout.js"; } } }
mit
C#
278083ae8e8a13ec105c3a5b971271564fec0f61
Check when list is null and campaign details doesn't exist
productinfo/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,TypeW/eShopOnContainers
src/Web/WebMVC/Controllers/CampaignsController.cs
src/Web/WebMVC/Controllers/CampaignsController.cs
namespace Microsoft.eShopOnContainers.WebMVC.Controllers { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.WebMVC.Models; using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.ViewModels; using System.Collections.Generic; using System.Threading.Tasks; [Authorize] public class CampaignsController : Controller { private ICampaignService _campaignService; public CampaignsController(ICampaignService campaignService) => _campaignService = campaignService; public async Task<IActionResult> Index() { var campaignDtoList = await _campaignService.GetCampaigns(); if(campaignDtoList is null) { return View(); } var campaignList = MapCampaignModelListToDtoList(campaignDtoList); return View(campaignList); } public async Task<IActionResult> Details(int id) { var campaignDto = await _campaignService.GetCampaignById(id); if (campaignDto is null) { return NotFound(); } var campaign = new Campaign { Id = campaignDto.Id, Name = campaignDto.Name, Description = campaignDto.Description, From = campaignDto.From, To = campaignDto.To, PictureUri = campaignDto.PictureUri }; return View(campaign); } private List<Campaign> MapCampaignModelListToDtoList(IEnumerable<CampaignDTO> campaignDtoList) { var campaignList = new List<Campaign>(); foreach(var campaignDto in campaignDtoList) { campaignList.Add(MapCampaignDtoToModel(campaignDto)); } return campaignList; } private Campaign MapCampaignDtoToModel(CampaignDTO campaign) { return new Campaign { Id = campaign.Id, Name = campaign.Name, Description = campaign.Description, From = campaign.From, To = campaign.To, PictureUri = campaign.PictureUri }; } } }
namespace Microsoft.eShopOnContainers.WebMVC.Controllers { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.ViewModels; using System; using System.Collections.Generic; using System.Threading.Tasks; [Authorize] public class CampaignsController : Controller { private ICampaignService _campaignService; public CampaignsController(ICampaignService campaignService) => _campaignService = campaignService; public async Task<IActionResult> Index() { var campaignList = await _campaignService.GetCampaigns(); return View(campaignList); } public async Task<IActionResult> Details(int id) { var campaignDto = await _campaignService.GetCampaignById(id); var campaign = new Campaign { Id = campaignDto.Id, Name = campaignDto.Name, Description = campaignDto.Description, From = campaignDto.From, To = campaignDto.To, PictureUri = campaignDto.PictureUri }; return View(campaign); } } }
mit
C#
0b0f7b120a6bff5708ed62ca2deb88d9852dfcba
Add support for APP_IN_USE dependency change
rit-sse-mycroft/core
Mycroft/Cmd/App/AppCommand.cs
Mycroft/Cmd/App/AppCommand.cs
using Mycroft.App; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd.App { class AppCommand : Command { /// <summary> /// Parses JSON into App command objects /// </summary> /// <param name="messageType">The message type that determines the command to create</param> /// <param name="json">The JSON body of the message</param> /// <returns>Returns a command object for the parsed message</returns> public static Command Parse(String type, String json, AppInstance instance) { switch (type) { case "APP_UP": return new DependencyChange(instance, Status.up); case "APP_DOWN": return new DependencyChange(instance, Status.down); case "APP_IN_USE": return new DependencyChange(instance, Status.in_use); case "APP_MANIFEST": return Manifest.Parse(json, instance); default: //data is incorrect - can't do anything with it // TODO notify that is wrong break; } return null ; } } }
using Mycroft.App; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd.App { class AppCommand : Command { /// <summary> /// Parses JSON into App command objects /// </summary> /// <param name="messageType">The message type that determines the command to create</param> /// <param name="json">The JSON body of the message</param> /// <returns>Returns a command object for the parsed message</returns> public static Command Parse(String type, String json, AppInstance instance) { switch (type) { case "APP_UP": return new DependencyChange(instance, Status.up); case "APP_DOWN": return new DependencyChange(instance, Status.down); case "APP_MANIFEST": return Manifest.Parse(json, instance); default: //data is incorrect - can't do anything with it // TODO notify that is wrong break; } return null ; } } }
bsd-3-clause
C#
fe6192bbbd114e29a7050a39cda7f8c33e07284b
Remove unused constant
JasperFx/jasper,JasperFx/jasper,JasperFx/jasper
src/Jasper.ConfluentKafka/KafkaTransportProtocol.cs
src/Jasper.ConfluentKafka/KafkaTransportProtocol.cs
using System.Collections.Generic; using System.Linq; using System.Text; using Confluent.Kafka; using Jasper.Transports; namespace Jasper.ConfluentKafka { public class KafkaTransportProtocol : ITransportProtocol<Message<byte[], byte[]>> { public Message<byte[], byte[]> WriteFromEnvelope(Envelope envelope) { var message = new Message<byte[], byte[]> { Headers = new Headers(), Value = envelope.Data }; IDictionary<string, object> envelopHeaders = new Dictionary<string, object>(); envelope.WriteToDictionary(envelopHeaders); var headers = new Headers(); foreach (Header header in envelopHeaders.Select(h => new Header(h.Key, Encoding.UTF8.GetBytes(h.Value.ToString())))) { headers.Add(header); } message.Headers = headers; return message; } public Envelope ReadEnvelope(Message<byte[], byte[]> message) { var env = new Envelope() { Data = message.Value }; Dictionary<string, object> incomingHeaders = message.Headers.Select(h => new {h.Key, Value = h.GetValueBytes()}) .ToDictionary(k => k.Key, v => (object)Encoding.UTF8.GetString(v.Value)); env.ReadPropertiesFromDictionary(incomingHeaders); return env; } } }
using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Text; using Confluent.Kafka; using Jasper.Transports; namespace Jasper.ConfluentKafka { public class KafkaTransportProtocol : ITransportProtocol<Message<byte[], byte[]>> { private const string JasperMessageIdHeader = "Jasper_MessageId"; public Message<byte[], byte[]> WriteFromEnvelope(Envelope envelope) { var message = new Message<byte[], byte[]> { Headers = new Headers(), Value = envelope.Data }; IDictionary<string, object> envelopHeaders = new Dictionary<string, object>(); envelope.WriteToDictionary(envelopHeaders); var headers = new Headers(); foreach (Header header in envelopHeaders.Select(h => new Header(h.Key, Encoding.UTF8.GetBytes(h.Value.ToString())))) { headers.Add(header); } message.Headers = headers; return message; } public Envelope ReadEnvelope(Message<byte[], byte[]> message) { var env = new Envelope() { Data = message.Value }; Dictionary<string, object> incomingHeaders = message.Headers.Select(h => new {h.Key, Value = h.GetValueBytes()}) .ToDictionary(k => k.Key, v => (object)Encoding.UTF8.GetString(v.Value)); env.ReadPropertiesFromDictionary(incomingHeaders); return env; } } }
mit
C#
c1410bf7bbd0b2c1cbcf1eccbbcb2c8e70d79950
Remove LINQ dependency
mstrother/BmpListener
BmpListener/Bgp/IPAddrPrefix.cs
BmpListener/Bgp/IPAddrPrefix.cs
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(byte[] data, AddressFamily afi) { Length = data[0]; if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(byte[] data, AddressFamily afi) { Length = data.ElementAt(0); if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
mit
C#
96eeb562739ac67bdead54cb98d457034e8e536e
Update ExchangeRate.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/ForeignExchange/ExchangeRate.cs
TIKSN.Core/Finance/ForeignExchange/ExchangeRate.cs
using System; namespace TIKSN.Finance.ForeignExchange { public class ExchangeRate : IEquatable<ExchangeRate> { public ExchangeRate(CurrencyPair pair, DateTimeOffset asOn, decimal rate) { if (rate <= decimal.Zero) { throw new ArgumentOutOfRangeException(nameof(rate), rate, "Rate must be a positive number."); } this.Pair = pair ?? throw new ArgumentNullException(nameof(pair)); this.AsOn = asOn; this.Rate = rate; } public DateTimeOffset AsOn { get; } public CurrencyPair Pair { get; } public decimal Rate { get; } public bool Equals(ExchangeRate other) { if (other == null) { return false; } return this.AsOn == other.AsOn && this.Pair == other.Pair && this.Rate == other.Rate; } public override bool Equals(object obj) => this.Equals(obj as ExchangeRate); public ExchangeRate Reverse() => new(this.Pair.Reverse(), this.AsOn, decimal.One / this.Rate); public override int GetHashCode() => this.AsOn.GetHashCode() ^ this.Pair.GetHashCode() ^ this.Rate.GetHashCode(); } }
using System; namespace TIKSN.Finance.ForeignExchange { public class ExchangeRate : IEquatable<ExchangeRate> { public ExchangeRate(CurrencyPair pair, DateTimeOffset asOn, decimal rate) { if (pair == null) { throw new ArgumentNullException(nameof(pair)); } if (rate <= decimal.Zero) { throw new ArgumentOutOfRangeException(nameof(rate), rate, "Rate must be a positive number."); } this.Pair = pair; this.AsOn = asOn; this.Rate = rate; } public DateTimeOffset AsOn { get; } public CurrencyPair Pair { get; } public decimal Rate { get; } public bool Equals(ExchangeRate other) { if (other == null) { return false; } return this.AsOn == other.AsOn && this.Pair == other.Pair && this.Rate == other.Rate; } public override bool Equals(object obj) => this.Equals(obj as ExchangeRate); public ExchangeRate Reverse() => new(this.Pair.Reverse(), this.AsOn, decimal.One / this.Rate); public override int GetHashCode() => this.AsOn.GetHashCode() ^ this.Pair.GetHashCode() ^ this.Rate.GetHashCode(); } }
mit
C#
45bcfab3a59a3db22ce4330a387dfd6b386fcd12
Update Cake.Issues.Reporting to 0.6.1
cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe
Cake.Recipe/Content/addins.cake
Cake.Recipe/Content/addins.cake
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.4.0 #addin nuget:?package=Cake.Coveralls&version=0.9.0 #addin nuget:?package=Cake.Figlet&version=1.2.0 #addin nuget:?package=Cake.Git&version=0.19.0 #addin nuget:?package=Cake.Gitter&version=0.10.0 #addin nuget:?package=Cake.Graph&version=0.6.0 #addin nuget:?package=Cake.Incubator&version=3.0.0 #addin nuget:?package=Cake.Kudu&version=0.8.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.8.0 #addin nuget:?package=Cake.ReSharperReports&version=0.10.0 #addin nuget:?package=Cake.Slack&version=0.12.0 #addin nuget:?package=Cake.Transifex&version=0.7.0 #addin nuget:?package=Cake.Twitter&version=0.9.0 #addin nuget:?package=Cake.Wyam&version=1.7.4 #addin nuget:?package=Cake.Issues&version=0.6.2 #addin nuget:?package=Cake.Issues.MsBuild&version=0.6.2 #addin nuget:?package=Cake.Issues.InspectCode&version=0.6.1 #addin nuget:?package=Cake.Issues.Reporting&version=0.6.1 #addin nuget:?package=Cake.Issues.Reporting.Generic&version=0.6.1 // Needed for Cake.Graph #addin nuget:?package=RazorEngine&version=3.10.0&loaddependencies=true Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.4.0 #addin nuget:?package=Cake.Coveralls&version=0.9.0 #addin nuget:?package=Cake.Figlet&version=1.2.0 #addin nuget:?package=Cake.Git&version=0.19.0 #addin nuget:?package=Cake.Gitter&version=0.10.0 #addin nuget:?package=Cake.Graph&version=0.6.0 #addin nuget:?package=Cake.Incubator&version=3.0.0 #addin nuget:?package=Cake.Kudu&version=0.8.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.8.0 #addin nuget:?package=Cake.ReSharperReports&version=0.10.0 #addin nuget:?package=Cake.Slack&version=0.12.0 #addin nuget:?package=Cake.Transifex&version=0.7.0 #addin nuget:?package=Cake.Twitter&version=0.9.0 #addin nuget:?package=Cake.Wyam&version=1.7.4 #addin nuget:?package=Cake.Issues&version=0.6.2 #addin nuget:?package=Cake.Issues.MsBuild&version=0.6.2 #addin nuget:?package=Cake.Issues.InspectCode&version=0.6.1 #addin nuget:?package=Cake.Issues.Reporting&version=0.6.0 #addin nuget:?package=Cake.Issues.Reporting.Generic&version=0.6.1 // Needed for Cake.Graph #addin nuget:?package=RazorEngine&version=3.10.0&loaddependencies=true Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
mit
C#
23a6748163e8f544ef8d047ca01a7cf1cdba4ecf
Fix Mono compiler error
ProgramFOX/Chess.NET
ChessDotNet/PositionDistance.cs
ChessDotNet/PositionDistance.cs
using System; namespace ChessDotNet { public struct PositionDistance { int _distanceX; public int DistanceX { get { return _distanceX; } } int _distanceY; public int DistanceY { get { return _distanceY; } } public PositionDistance(Position position1, Position position2) { if (position1 == null) throw new ArgumentNullException("position1"); if (position2 == null) throw new ArgumentNullException("position2"); _distanceX = Math.Abs((int)position1.File - (int)position2.File); _distanceY = Math.Abs((int)position1.Rank - (int)position2.Rank); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; PositionDistance distance2 = (PositionDistance)obj; return DistanceX == distance2.DistanceX && DistanceY == distance2.DistanceY; } public override int GetHashCode() { return new { DistanceX, DistanceY }.GetHashCode(); } public static bool operator ==(PositionDistance distance1, PositionDistance distance2) { return distance1.Equals(distance2); } public static bool operator !=(PositionDistance distance1, PositionDistance distance2) { return !distance1.Equals(distance2); } } }
using System; namespace ChessDotNet { public struct PositionDistance { public int DistanceX { get; private set; } public int DistanceY { get; private set; } public PositionDistance(Position position1, Position position2) { if (position1 == null) throw new ArgumentNullException("position1"); if (position2 == null) throw new ArgumentNullException("position2"); DistanceX = Math.Abs((int)position1.File - (int)position2.File); DistanceY = Math.Abs((int)position1.Rank - (int)position2.Rank); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; PositionDistance distance2 = (PositionDistance)obj; return DistanceX == distance2.DistanceX && DistanceY == distance2.DistanceY; } public override int GetHashCode() { return new { DistanceX, DistanceY }.GetHashCode(); } public static bool operator ==(PositionDistance distance1, PositionDistance distance2) { return distance1.Equals(distance2); } public static bool operator !=(PositionDistance distance1, PositionDistance distance2) { return !distance1.Equals(distance2); } } }
mit
C#
f08a83021b9f26b9cbd77273cc69d9c4d3812c97
add summary comment.
dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap
src/DotNetCore.CAP/ICapOptionsExtension.cs
src/DotNetCore.CAP/ICapOptionsExtension.cs
using Microsoft.Extensions.DependencyInjection; namespace DotNetCore.CAP { /// <summary> /// Cap options extension /// </summary> public interface ICapOptionsExtension { /// <summary> /// Registered child service. /// </summary> /// <param name="services">add service to the <see cref="IServiceCollection"/></param> void AddServices(IServiceCollection services); } }
using Microsoft.Extensions.DependencyInjection; namespace DotNetCore.CAP { public interface ICapOptionsExtension { void AddServices(IServiceCollection services); } }
mit
C#
dd32c771bbc62f5ba9e16767d04970b7775fe1fa
modify comment.
tangxuehua/enode,Aaron-Liu/enode
src/ENode/Infrastructure/ENodeException.cs
src/ENode/Infrastructure/ENodeException.cs
using System; namespace ENode.Infrastructure { /// <summary>Represents a common exception of enode framework. /// </summary> [Serializable] public class ENodeException : Exception { /// <summary>Default constructor. /// </summary> public ENodeException() { } /// <summary>Parameterized constructor. /// </summary> /// <param name="message"></param> public ENodeException(string message) : base(message) { } /// <summary>Parameterized constructor. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ENodeException(string message, Exception innerException) : base(message, innerException) { } /// <summary>Parameterized constructor. /// </summary> /// <param name="message"></param> /// <param name="args"></param> public ENodeException(string message, params object[] args) : base(string.Format(message, args)) { } } }
using System; namespace ENode.Infrastructure { /// <summary>Represents a concurrent exception. /// </summary> [Serializable] public class ENodeException : Exception { /// <summary>Default constructor. /// </summary> public ENodeException() { } /// <summary>Parameterized constructor. /// </summary> /// <param name="message"></param> public ENodeException(string message) : base(message) { } /// <summary>Parameterized constructor. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ENodeException(string message, Exception innerException) : base(message, innerException) { } /// <summary>Parameterized constructor. /// </summary> /// <param name="message"></param> /// <param name="args"></param> public ENodeException(string message, params object[] args) : base(string.Format(message, args)) { } } }
mit
C#
45c37578c618afc0b06203a95fe3da14be3d3d05
Add Listing_Standard extension methods.
neitsa/PrepareLanding,neitsa/PrepareLanding
src/Extensions/ListingStandardExtension.cs
src/Extensions/ListingStandardExtension.cs
using UnityEngine; using Verse; namespace PrepareLanding.Extensions { /// <summary> /// Extension class for <see cref="Verse.Listing_Standard" />. /// </summary> public static class ListingStandardExtension { /// <summary> /// Start a scroll view inside a <see cref="Listing_Standard" />. /// </summary> /// <param name="ls"><see cref="Listing_Standard" /> instance.</param> /// <param name="outerRectHeight">The containing <see cref="Rect" /> for the scroll view.</param> /// <param name="scrollViewHeight">The height of the (virtual) scroll view.</param> /// <param name="scrollViewPos">The scroll position.</param> /// <remarks>This call must be matched with a call to <see cref="EndScrollView" />.</remarks> public static Listing_Standard BeginScrollView(this Listing_Standard ls, float outerRectHeight, float scrollViewHeight, ref Vector2 scrollViewPos) { var outerRect = ls.GetRect(outerRectHeight); var scrollViewRect = new Rect(0, 0, ls.ColumnWidth, scrollViewHeight); Widgets.BeginScrollView(outerRect, ref scrollViewPos, scrollViewRect); var internalLs = new Listing_Standard {ColumnWidth = ls.ColumnWidth}; internalLs.Begin(scrollViewRect); return internalLs; } /// <summary> /// End a scroll view in a <see cref="Listing_Standard" /> started with <see cref="BeginScrollView" />. /// </summary> /// <param name="ls"><see cref="Listing_Standard" /> instance.</param> /// <param name="internalLs"></param> /// <remarks>This call must be matched with a call to <see cref="BeginScrollView" />.</remarks> public static void EndScrollView(this Listing_Standard ls, Listing_Standard internalLs) { internalLs.End(); Widgets.EndScrollView(); } public static float StartCaptureHeight(this Listing_Standard ls) { return ls.CurHeight; } public static Rect EndCaptureHeight(this Listing_Standard ls, float startHeight) { var r = ls.GetRect(0f); r.y = startHeight; r.height = ls.CurHeight - startHeight; return r; } public static Rect VirtualRect(this Listing_Standard ls, float height) { var r = ls.GetRect(0f); r.height = height; return r; } } }
using UnityEngine; using Verse; namespace PrepareLanding.Extensions { /// <summary> /// Extension class for <see cref="Verse.Listing_Standard" />. /// </summary> public static class ListingStandardExtension { /// <summary> /// Start a scroll view inside a <see cref="Listing_Standard" />. /// </summary> /// <param name="ls"><see cref="Listing_Standard" /> instance.</param> /// <param name="outerRectHeight">The containing <see cref="Rect" /> for the scroll view.</param> /// <param name="scrollViewHeight">The height of the (virtual) scroll view.</param> /// <param name="scrollViewPos">The scroll position.</param> /// <remarks>This call must be matched with a call to <see cref="EndScrollView" />.</remarks> public static Listing_Standard BeginScrollView(this Listing_Standard ls, float outerRectHeight, float scrollViewHeight, ref Vector2 scrollViewPos) { var outerRect = ls.GetRect(outerRectHeight); var scrollViewRect = new Rect(0, 0, ls.ColumnWidth, scrollViewHeight); Widgets.BeginScrollView(outerRect, ref scrollViewPos, scrollViewRect); var internalLs = new Listing_Standard {ColumnWidth = ls.ColumnWidth}; internalLs.Begin(scrollViewRect); return internalLs; } /// <summary> /// End a scroll view in a <see cref="Listing_Standard" /> started with <see cref="BeginScrollView" />. /// </summary> /// <param name="ls"><see cref="Listing_Standard" /> instance.</param> /// <param name="internalLs"></param> /// <remarks>This call must be matched with a call to <see cref="BeginScrollView" />.</remarks> public static void EndScrollView(this Listing_Standard ls, Listing_Standard internalLs) { internalLs.End(); Widgets.EndScrollView(); } } }
mit
C#
b07918de09972c8b38e66d325790ef3e17725ea2
Disable some unit tests that are broken on Mono
jstedfast/MimeKit,jstedfast/MimeKit,nachocove/MimeKit,nachocove/MimeKit,nachocove/MimeKit,jstedfast/MimeKit
UnitTests/MimeVisitorTests.cs
UnitTests/MimeVisitorTests.cs
// // MimeVisitorTests.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Text; using NUnit.Framework; using MimeKit; namespace UnitTests { [TestFixture] public class MimeVisitorTests { [Test] public void TestMimeVisitor () { var dataDir = Path.Combine ("..", "..", "TestData", "mbox"); var visitor = new HtmlPreviewVisitor (); int index = 0; using (var stream = File.OpenRead (Path.Combine (dataDir, "jwz.mbox.txt"))) { var parser = new MimeParser (stream, MimeFormat.Mbox); while (!parser.IsEndOfStream) { var filename = string.Format ("jwz.body.{0}.html", index); var path = Path.Combine (dataDir, filename); var message = parser.ParseMessage (); string expected, actual; visitor.Visit (message); actual = visitor.HtmlBody; if (!string.IsNullOrEmpty (actual)) actual = actual.Replace ("\r\n", "\n"); if (!File.Exists (path) && actual != null) File.WriteAllText (path, actual); if (File.Exists (path)) expected = File.ReadAllText (path, Encoding.UTF8).Replace ("\r\n", "\n"); else expected = null; if (index != 6 && index != 13 && index != 31) { // message 6, 13 and 31 contain some japanese text that is broken in Mono Assert.AreEqual (expected, actual, "The bodies do not match for message {0}", index); } visitor.Reset (); index++; } } } } }
// // MimeVisitorTests.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Text; using NUnit.Framework; using MimeKit; namespace UnitTests { [TestFixture] public class MimeVisitorTests { [Test] public void TestMimeVisitor () { var dataDir = Path.Combine ("..", "..", "TestData", "mbox"); var visitor = new HtmlPreviewVisitor (); int index = 0; using (var stream = File.OpenRead (Path.Combine (dataDir, "jwz.mbox.txt"))) { var parser = new MimeParser (stream, MimeFormat.Mbox); while (!parser.IsEndOfStream) { var filename = string.Format ("jwz.body.{0}.html", index); var path = Path.Combine (dataDir, filename); var message = parser.ParseMessage (); string expected, actual; visitor.Visit (message); actual = visitor.HtmlBody; if (!string.IsNullOrEmpty (actual)) actual = actual.Replace ("\r\n", "\n"); if (!File.Exists (path) && actual != null) File.WriteAllText (path, actual); if (File.Exists (path)) expected = File.ReadAllText (path, Encoding.UTF8).Replace ("\r\n", "\n"); else expected = null; if (index != 6) { // message 6 contains some japanese text that is broken in Mono Assert.AreEqual (expected, actual, "The bodies do not match for message {0}", index); } visitor.Reset (); index++; } } } } }
mit
C#
6a15132c761cf95d88455d663f4fe9f9ef5360f0
Fix reference plane rotation bug.
Starstrider42/Custom-Asteroids
src/Coordinates/SimplePlane.cs
src/Coordinates/SimplePlane.cs
using UnityEngine; namespace Starstrider42.CustomAsteroids { /// <summary>Standard implementation of <see cref="ReferencePlane"/>.</summary> internal class SimplePlane : ReferencePlane { public string name { get; private set; } /// <summary>Rotation used to implement toDefaultFrame.</summary> private readonly Quaternion xform; /// <summary> /// Creates a new ReferencePlane with the given name and rotation. /// </summary> /// <param name="id">A unique identifier for this object. Initialises the <see cref="name"/> property.</param> /// <param name="thisToDefault">A rotation that transforms vectors from this reference frame /// to the KSP default reference frame.</param> internal SimplePlane(string id, Quaternion thisToDefault) { this.name = id; this.xform = thisToDefault; } public Vector3d toDefaultFrame(Vector3d inFrame) { Quaternion frameCorrection = Planetarium.Zup.Rotation; return Quaternion.Inverse(frameCorrection) * xform * frameCorrection * inFrame; } } }
using UnityEngine; using System; namespace Starstrider42.CustomAsteroids { /// <summary>Standard implementation of <see cref="ReferencePlane"/>.</summary> internal class SimplePlane : ReferencePlane { public string name { get; private set; } /// <summary>Rotation used to implement toDefaultFrame.</summary> private readonly Quaternion xform; /// <summary> /// Creates a new ReferencePlane with the given name and rotation. /// </summary> /// <param name="id">A unique identifier for this object. Initialises the <see cref="name"/> property.</param> /// <param name="thisToDefault">A rotation that transforms vectors from this reference frame /// to the KSP default reference frame.</param> internal SimplePlane(string id, Quaternion thisToDefault) { this.name = id; this.xform = thisToDefault; } public Vector3d toDefaultFrame(Vector3d inFrame) { Quaternion frameCorrection = Planetarium.Rotation; return frameCorrection * xform * Quaternion.Inverse(frameCorrection) * inFrame; } } }
mit
C#
b5cceb0e68ea36db3fab8567e76a3ba92f533ad7
Fix to allow email addresses as users names, Issue #163 #158
gencer/Bonobo-Git-Server,crowar/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,crowar/Bonobo-Git-Server,YelaSeamless/Bonobo-Git-Server,gencer/Bonobo-Git-Server,jiangzm/Bonobo-Git-Server,dunderburken/Bonobo-Git-Server,crowar/Bonobo-Git-Server,darioajr/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,NipponSysits/IIS.Git-Connector,hakim89/Bonobo-Git-Server,dunderburken/Bonobo-Git-Server,larrynung/Bonobo-Git-Server,YelaSeamless/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,yonglehou/Bonobo-Git-Server,larshg/Bonobo-Git-Server,YelaSeamless/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,forgetz/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,jiangzm/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,crowar/Bonobo-Git-Server,snoopydo/Bonobo-Git-Server,KiritoStudio/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,snoopydo/Bonobo-Git-Server,larshg/Bonobo-Git-Server,Monepi/Bonobo-Git-Server,jiangzm/Bonobo-Git-Server,yonglehou/Bonobo-Git-Server,larrynung/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,hakim89/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,willdean/Bonobo-Git-Server,larrynung/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,hakim89/Bonobo-Git-Server,gencer/Bonobo-Git-Server,dunderburken/Bonobo-Git-Server,crowar/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,Monepi/Bonobo-Git-Server,lkho/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,jiangzm/Bonobo-Git-Server,yonglehou/Bonobo-Git-Server,darioajr/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,jiangzm/Bonobo-Git-Server,larshg/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,larrynung/Bonobo-Git-Server,dunderburken/Bonobo-Git-Server,lkho/Bonobo-Git-Server,snoopydo/Bonobo-Git-Server,yonglehou/Bonobo-Git-Server,YelaSeamless/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,YelaSeamless/Bonobo-Git-Server,KiritoStudio/Bonobo-Git-Server,willdean/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,willdean/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,larrynung/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,lkho/Bonobo-Git-Server,yonglehou/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,hakim89/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,KiritoStudio/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,KiritoStudio/Bonobo-Git-Server,Monepi/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,crowar/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,snoopydo/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,YelaSeamless/Bonobo-Git-Server,darioajr/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,yonglehou/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,hakim89/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,Monepi/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,anyeloamt1/Bonobo-Git-Server,KiritoStudio/Bonobo-Git-Server,KiritoStudio/Bonobo-Git-Server,larshg/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,snoopydo/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,darioajr/Bonobo-Git-Server,dunderburken/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,gencer/Bonobo-Git-Server,darioajr/Bonobo-Git-Server,larrynung/Bonobo-Git-Server,dunderburken/Bonobo-Git-Server,willdean/Bonobo-Git-Server,lkho/Bonobo-Git-Server,Monepi/Bonobo-Git-Server,willdean/Bonobo-Git-Server,Monepi/Bonobo-Git-Server,hakim89/Bonobo-Git-Server,snoopydo/Bonobo-Git-Server,jiangzm/Bonobo-Git-Server,darioajr/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector
Bonobo.Git.Server/UsernameUrl.cs
Bonobo.Git.Server/UsernameUrl.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; namespace Bonobo.Git.Server { public class UsernameUrl { //to allow support for email addresses as user names, only encode/decode user name if it is not an email address private static Regex _isEmailRegEx = new Regex( @"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", RegexOptions.Compiled); public static string Encode(string username) { var nameParts = username.Split('\\'); if ( nameParts.Count() == 2 && !_isEmailRegEx.IsMatch(username) ) { return nameParts[1] + "@" + nameParts[0]; } return username; } public static string Decode(string username) { var nameParts = username.Split('@'); if ( nameParts.Count() == 2 && !_isEmailRegEx.IsMatch(username) ) { return nameParts[1] + "\\" + nameParts[0]; } return username; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Bonobo.Git.Server { public class UsernameUrl { public static string Encode(string username) { var nameParts = username.Split('\\'); if (nameParts.Count() == 2) { return nameParts[1] + "@" + nameParts[0]; } return username; } public static string Decode(string username) { var nameParts = username.Split('@'); if (nameParts.Count() == 2) { return nameParts[1] + "\\" + nameParts[0]; } return username; } } }
mit
C#
b7a3f3f0aa087277ba5e4f8081403e0ab2060cfb
Fix a typo in IBusControl.StartAsync XML doc
MassTransit/MassTransit,MassTransit/MassTransit,phatboyg/MassTransit,phatboyg/MassTransit
src/MassTransit/IBusControl.cs
src/MassTransit/IBusControl.cs
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit { using System.Threading; using System.Threading.Tasks; public interface IBusControl : IBus { /// <summary> /// Starts the bus (assuming the battery isn't dead). Once the bus has been started it cannot be started again, even after it has been stopped. /// </summary> /// <returns>The BusHandle for the started bus. This is no longer needed, as calling Stop on the IBusControl will stop the bus equally well.</returns> Task<BusHandle> StartAsync(CancellationToken cancellationToken = default); /// <summary> /// Stops the bus if it has been started. If the bus hasn't been started, the method returns without any warning. /// </summary> Task StopAsync(CancellationToken cancellationToken = default); } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit { using System.Threading; using System.Threading.Tasks; public interface IBusControl : IBus { /// <summary> /// Starts the bus (assuming the battery isn't dead). Once the bus has been started, it cannot be started again, even after is has been stopped. /// </summary> /// <returns>The BusHandle for the started bus. This is no longer needed, as calling Stop on the IBusControl will stop the bus equally well.</returns> Task<BusHandle> StartAsync(CancellationToken cancellationToken = default); /// <summary> /// Stops the bus if it has been started. If the bus hasn't been started, the method returns without any warning. /// </summary> Task StopAsync(CancellationToken cancellationToken = default); } }
apache-2.0
C#
f30ac4089c5d351a2fad5055b4a2bf3652f59e0a
Add properties to BufferRange
vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSGL.Vulkan/Vulkan/BufferView.cs
CSGL.Vulkan/Vulkan/BufferView.cs
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class BufferViewCreateInfo { public Buffer buffer; public VkFormat format; public ulong offset; public ulong range; } public class BufferView : INative<VkBufferView>, IDisposable { bool disposed; VkBufferView bufferView; public Device Device { get; private set; } public ulong Offset { get; private set; } public ulong Range { get; private set; } public VkBufferView Native { get { return bufferView; } } public BufferView(Device device, BufferViewCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; } void CreateBufferView(BufferViewCreateInfo mInfo) { VkBufferViewCreateInfo info = new VkBufferViewCreateInfo(); info.sType = VkStructureType.BufferViewCreateInfo; info.buffer = mInfo.buffer.Native; info.format = mInfo.format; info.offset = mInfo.offset; info.range = mInfo.range; var result = Device.Commands.createBufferView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out bufferView); if (result != VkResult.Success) throw new BufferViewException(string.Format("Error creating buffer view: {0}", result)); Offset = mInfo.offset; Range = mInfo.range; } public void Dispose() { if (disposed) return; Device.Commands.destroyBufferView(Device.Native, bufferView, Device.Instance.AllocationCallbacks); disposed = true; } } public class BufferViewException : Exception { public BufferViewException(string message) : base(message) { } } }
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class BufferViewCreateInfo { public Buffer buffer; public VkFormat format; public ulong offset; public ulong range; } public class BufferView : INative<VkBufferView>, IDisposable { bool disposed; VkBufferView bufferView; public Device Device { get; private set; } public VkBufferView Native { get { return bufferView; } } public BufferView(Device device, BufferViewCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; } void CreateBufferView(BufferViewCreateInfo mInfo) { VkBufferViewCreateInfo info = new VkBufferViewCreateInfo(); info.sType = VkStructureType.BufferViewCreateInfo; info.buffer = mInfo.buffer.Native; info.format = mInfo.format; info.offset = mInfo.offset; info.range = mInfo.range; var result = Device.Commands.createBufferView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out bufferView); if (result != VkResult.Success) throw new BufferViewException(string.Format("Error creating buffer view: {0}", result)); } public void Dispose() { if (disposed) return; Device.Commands.destroyBufferView(Device.Native, bufferView, Device.Instance.AllocationCallbacks); disposed = true; } } public class BufferViewException : Exception { public BufferViewException(string message) : base(message) { } } }
mit
C#
beba54fde781c3ce498adcb1ed26e8831ba6fa58
Increment version to 1.0.0
LeCantaloop/MassTransit.Extras.MessageData.DocumentDb,MattKotsenas/MassTransit.Extras.MessageData.DocumentDb
src/Properties/AssemblyInfo.cs
src/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("MassTransit.Extras.MessageData.DocumentDb")] [assembly: AssemblyDescription("MassTransit extension to use Azure DocumentDB as a large message data repository")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Matt Kotsenas")] [assembly: AssemblyProduct("MassTransit.Extras.MessageData.DocumentDb")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6d14b5e9-2de2-477f-8431-9f5e58506bbf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: InternalsVisibleTo("MassTransit.Extras.MessageData.DocumentDb.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MassTransit.Extras.MessageData.DocumentDb")] [assembly: AssemblyDescription("MassTransit extension to use Azure DocumentDB as a large message data repository")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Matt Kotsenas")] [assembly: AssemblyProduct("MassTransit.Extras.MessageData.DocumentDb")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6d14b5e9-2de2-477f-8431-9f5e58506bbf")] // 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.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")] [assembly: AssemblyInformationalVersion("0.0.1-alpha")] [assembly: InternalsVisibleTo("MassTransit.Extras.MessageData.DocumentDb.Tests")]
apache-2.0
C#
704be66806bb7b37b141a90eee6d9f75bb1d064f
tidy up a bit
DHancock/Countdown
Countdown/ViewModels/ItemBase.cs
Countdown/ViewModels/ItemBase.cs
namespace Countdown.ViewModels { abstract internal class ItemBase : PropertyChangedBase { public string Content { get; protected set; } private bool isSelected = false; public ItemBase() { } public ItemBase(string item) { Content = item ?? string.Empty; } public bool IsSelected { get { return isSelected; } set { if (isSelected != value) { isSelected = value; RaisePropertyChanged(nameof(IsSelected)); } } } public override string ToString() => Content; } }
namespace Countdown.ViewModels { abstract internal class ItemBase : PropertyChangedBase { public string Content { get; protected set; } private bool isSelected = false; public ItemBase() : this(null) { } public ItemBase(string item) { Content = item ?? string.Empty; } public bool IsSelected { get { return isSelected; } set { if (isSelected != value) { isSelected = value; RaisePropertyChanged(nameof(IsSelected)); } } } public override string ToString() => Content; } }
unlicense
C#
debb99056204b943f7e6a72603d11de8c47426d9
Mark sub-header navigation link as 'last' so that the trailing vertical bar goes away.
dafrito/trac-mirror,dafrito/trac-mirror,dokipen/trac,moreati/trac-gitsvn,dokipen/trac,exocad/exotrac,dafrito/trac-mirror,moreati/trac-gitsvn,exocad/exotrac,exocad/exotrac,moreati/trac-gitsvn,exocad/exotrac,moreati/trac-gitsvn,dafrito/trac-mirror,dokipen/trac
templates/log.cs
templates/log.cs
<?cs include "header.cs"?> <?cs include "macros.cs"?> <div id="page-content"> <ul class="subheader-links"> <li class="last"><a href="<?cs var:log.items.0.file_href ?>">View Latest Revision</a></li> </ul> <div id="main"> <div id="main-content"> <h1 id="log-hdr" class="hide">Revision log for <?cs var:log.path ?></h1> <?cs call:browser_path_links(log.path, log) ?> <div id="browser-nav"> <ul class="menulist"><li class="last"><a href="<?cs var:log.items.0.file_href ?>">View Latest Revision</a></li></ul> <form id="browser-chgrev" action="<?cs var:log.items.0.file_href ?>" method="get"> <label for="rev">View rev:</label> <input type="text" id="rev" name="rev" value="<?cs var:log.items.0.rev ?>" size="4" /> <input type="submit" value="View"/> </form> <div class="tiny" style="clear: both">&nbsp;</div> </div> <table id="browser-list" cellspacing="0" cellpadding="0"> <tr class="browser-listhdr"> <th>Date</th> <th>Rev</th> <th>Chgset</th> <th>Author</th> <th>Log Message</th> </tr> <?cs each:item = log.items ?> <?cs if idx % #2 ?> <tr class="br-row-even"> <?cs else ?> <tr class="br-row-odd"> <?cs /if ?> <td class="br-date-col"><?cs var:item.date ?></td> <td class="br-rev-col"> <a class="block-link" href="<?cs var:item.file_href ?>"><?cs var:item.rev ?></a> </td> <td class="br-chg-col"> <a class="block-link" href="<?cs var:item.changeset_href ?>"><?cs var:item.rev ?></a> </td> <td class="br-author-col"> <?cs var:item.author ?> </td> <td class="br-summary-col"><?cs var:item.log ?></td> </tr> <?cs set:idx = idx + #1 ?> <?cs /each ?> </table> <div id="main-footer"> Download history in other formats: <br /> <a class="noline" href="?format=rss"><img src="<?cs var:htdocs_location ?>xml.png" alt="RSS Feed" style="vertical-align: bottom"/></a>&nbsp; <a href="?format=rss">(RSS 2.0)</a> <br /> </div> </div> </div> </div> <?cs include:"footer.cs"?>
<?cs include "header.cs"?> <?cs include "macros.cs"?> <div id="page-content"> <ul class="subheader-links"> <li><a href="<?cs var:log.items.0.file_href ?>">View Latest Revision</a></li> </ul> <div id="main"> <div id="main-content"> <h1 id="log-hdr" class="hide">Revision log for <?cs var:log.path ?></h1> <?cs call:browser_path_links(log.path, log) ?> <div id="browser-nav"> <ul class="menulist"><li class="last"><a href="<?cs var:log.items.0.file_href ?>">View Latest Revision</a></li></ul> <form id="browser-chgrev" action="<?cs var:log.items.0.file_href ?>" method="get"> <label for="rev">View rev:</label> <input type="text" id="rev" name="rev" value="<?cs var:log.items.0.rev ?>" size="4" /> <input type="submit" value="View"/> </form> <div class="tiny" style="clear: both">&nbsp;</div> </div> <table id="browser-list" cellspacing="0" cellpadding="0"> <tr class="browser-listhdr"> <th>Date</th> <th>Rev</th> <th>Chgset</th> <th>Author</th> <th>Log Message</th> </tr> <?cs each:item = log.items ?> <?cs if idx % #2 ?> <tr class="br-row-even"> <?cs else ?> <tr class="br-row-odd"> <?cs /if ?> <td class="br-date-col"><?cs var:item.date ?></td> <td class="br-rev-col"> <a class="block-link" href="<?cs var:item.file_href ?>"><?cs var:item.rev ?></a> </td> <td class="br-chg-col"> <a class="block-link" href="<?cs var:item.changeset_href ?>"><?cs var:item.rev ?></a> </td> <td class="br-author-col"> <?cs var:item.author ?> </td> <td class="br-summary-col"><?cs var:item.log ?></td> </tr> <?cs set:idx = idx + #1 ?> <?cs /each ?> </table> <div id="main-footer"> Download history in other formats: <br /> <a class="noline" href="?format=rss"><img src="<?cs var:htdocs_location ?>xml.png" alt="RSS Feed" style="vertical-align: bottom"/></a>&nbsp; <a href="?format=rss">(RSS 2.0)</a> <br /> </div> </div> </div> </div> <?cs include:"footer.cs"?>
bsd-3-clause
C#
ae33680a9dda174087dede6fdebff83596333bcf
Fix to ensure HTMLElement uses the Caption when loading up the actual HTML page.
MonoCross/MonoCross,MonoCross/MonoCross,sam-lippert/DialogSampleApp,MonoCross/MonoCross,TimeIncOSS/MonoDroid.Dialog,Clancey/MonoDroid.Dialog
MonoDroid.Dialog/HtmlElement.cs
MonoDroid.Dialog/HtmlElement.cs
using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Webkit; using Uri = Android.Net.Uri; namespace MonoDroid.Dialog { public class HtmlElement : StringElement { // public string Value; public HtmlElement(string caption, string url) : base(caption) { Url = Uri.Parse(url); } public HtmlElement(string caption, Uri uri) : base(caption) { Url = uri; } public Uri Url { get; set; } void OpenUrl(Context context) { Intent intent = new Intent(context, typeof(HtmlActivity)); intent.PutExtra("URL",this.Url.ToString()); intent.PutExtra("Title",Caption); intent.AddFlags(ActivityFlags.NewTask); context.StartActivity(intent); } public override View GetView(Context context, View convertView, ViewGroup parent) { View view = base.GetView (context, convertView, parent); this.Click = (o, e) => OpenUrl(context); return view; } } [Activity] public class HtmlActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Intent i = this.Intent; string url = i.GetStringExtra("URL"); this.Title = i.GetStringExtra("Title"); WebView webview = new WebView(this); webview.Settings.JavaScriptEnabled = true; SetContentView(webview); webview.LoadUrl(url); } } }
using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Webkit; using Uri = Android.Net.Uri; namespace MonoDroid.Dialog { public class HtmlElement : StringElement { // public string Value; public HtmlElement(string caption, string url) : base(caption) { Url = Uri.Parse(url); } public HtmlElement(string caption, Uri uri) : base(caption) { Url = uri; } public Uri Url { get; set; } void OpenUrl(Context context) { Intent intent = new Intent(context, typeof(HtmlActivity)); intent.PutExtra("URL",this.Url.ToString()); intent.AddFlags(ActivityFlags.NewTask); context.StartActivity(intent); } public override View GetView(Context context, View convertView, ViewGroup parent) { View view = base.GetView (context, convertView, parent); this.Click = (o, e) => OpenUrl(context); return view; } } [Activity] public class HtmlActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Intent i = this.Intent; string url = i.GetStringExtra("URL"); WebView webview = new WebView(this); webview.Settings.JavaScriptEnabled = true; SetContentView(webview); webview.LoadUrl(url); } } }
mit
C#
e9638a221312c8c99f4a7011f2c645fde57d12c9
Fix a image naming bug.
zhen08/PiDashcam,zhen08/PiDashcam
PiDashcam/PiDashcam/StillCam.cs
PiDashcam/PiDashcam/StillCam.cs
using System; using System.IO; using System.Timers; using Shell.Execute; namespace PiDashcam { public class StillCam { Timer timer; int imgcounter; string folder; public StillCam(string imageFolder) { imgcounter = 1; folder = imageFolder; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } foreach (var file in Directory.EnumerateFiles(folder)) { int count = Int32.Parse(file.Remove(file.IndexOf('.')).Substring(file.LastIndexOf('/') + 1)); if (imgcounter <= count) { imgcounter = count + 1; } } timer = new Timer(6000); timer.Elapsed += Timer_Elapsed; timer.Start(); } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { ProgramLauncher.Execute("raspistill", String.Format("-h 1080 -w 1920 -n -o {0}/{1}.jpg", folder, imgcounter.ToString("D8"))); imgcounter++; } } }
using System; using System.IO; using System.Timers; using Shell.Execute; namespace PiDashcam { public class StillCam { Timer timer; int imgcounter; string folder; public StillCam(string imageFolder) { folder = imageFolder; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } foreach (var file in Directory.EnumerateFiles(folder)) { int count = Int32.Parse(file.Remove(file.IndexOf('.')).Substring(file.LastIndexOf('/') + 1)); if (imgcounter <= count) { imgcounter = count + 1; } } timer = new Timer(6000); timer.Elapsed += Timer_Elapsed; timer.Start(); imgcounter = 1; } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { ProgramLauncher.Execute("raspistill", String.Format("-h 1080 -w 1920 -n -o {0}/{1}.jpg", folder, imgcounter.ToString("D8"))); imgcounter++; } } }
mit
C#
04df802e54962a2ac2ab53a0dee0bad1338f993d
Add ReliabilityContract for the ReleaseHandle on SafeSspiHandle so that it can fully participate in the implicit CER that is created during finalization.
antiduh/nsspi
NSspi/SspiHandle.cs
NSspi/SspiHandle.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using NSspi.Contexts; namespace NSspi { /// <summary> /// Represents any SSPI handle created for credential handles, context handles, and security package /// handles. Any SSPI handle is always the size of two native pointers. /// </summary> /// <remarks> /// The documentation for SSPI handles can be found here: /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa380495(v=vs.85).aspx /// /// This class is not reference safe - if used directly, or referenced directly, it may be leaked, /// or subject to finalizer races, or any of the hundred of things SafeHandles were designed to fix. /// Do not directly use this class - use only though SafeHandle wrapper objects. Any reference needed /// to this handle for performing work (InitializeSecurityContext, eg), should be done through /// a second class SafeSspiHandleReference so that reference counting is properly executed. /// </remarks> [StructLayout( LayoutKind.Sequential, Pack = 1 ) ] internal struct RawSspiHandle { private IntPtr lowPart; private IntPtr highPart; public bool IsZero() { return this.lowPart == IntPtr.Zero && this.highPart == IntPtr.Zero; } // This guy has to be executed in a CER. [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)] public void SetInvalid() { this.lowPart = IntPtr.Zero; this.highPart = IntPtr.Zero; } } public abstract class SafeSspiHandle : SafeHandle { internal RawSspiHandle rawHandle; protected SafeSspiHandle() : base( IntPtr.Zero, true ) { this.rawHandle = new RawSspiHandle(); } public override bool IsInvalid { get { return IsClosed || this.rawHandle.IsZero(); } } [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] protected override bool ReleaseHandle() { this.rawHandle.SetInvalid(); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using NSspi.Contexts; namespace NSspi { /// <summary> /// Represents any SSPI handle created for credential handles, context handles, and security package /// handles. Any SSPI handle is always the size of two native pointers. /// </summary> /// <remarks> /// The documentation for SSPI handles can be found here: /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa380495(v=vs.85).aspx /// /// This class is not reference safe - if used directly, or referenced directly, it may be leaked, /// or subject to finalizer races, or any of the hundred of things SafeHandles were designed to fix. /// Do not directly use this class - use only though SafeHandle wrapper objects. Any reference needed /// to this handle for performing work (InitializeSecurityContext, eg), should be done through /// a second class SafeSspiHandleReference so that reference counting is properly executed. /// </remarks> [StructLayout( LayoutKind.Sequential, Pack = 1 ) ] internal struct RawSspiHandle { private IntPtr lowPart; private IntPtr highPart; public bool IsZero() { return this.lowPart == IntPtr.Zero && this.highPart == IntPtr.Zero; } // This guy has to be executed in a CER. [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)] public void SetInvalid() { this.lowPart = IntPtr.Zero; this.highPart = IntPtr.Zero; } } public abstract class SafeSspiHandle : SafeHandle { internal RawSspiHandle rawHandle; protected SafeSspiHandle() : base( IntPtr.Zero, true ) { this.rawHandle = new RawSspiHandle(); } public override bool IsInvalid { get { return IsClosed || this.rawHandle.IsZero(); } } protected override bool ReleaseHandle() { this.rawHandle.SetInvalid(); return true; } } }
bsd-2-clause
C#
f89640b7398c0107ed48dd35b5715b558d0fc46e
Clear all input lines
ivanmishev/ShipGame
ShipGame/Logger.cs
ShipGame/Logger.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShipGame { class Logger { private static List<string> messages = new List<string>(); private static int startingLine = 0; private static int LOG_LENGTH = 5; public static void Write(string message) { messages.Add(message); if(startingLine == 0) { startingLine = Console.CursorTop; } if (Console.CursorTop >= startingLine + LOG_LENGTH) { CleaLog(); } Console.WriteLine(message); } private static void CleaLog() { for (int i = 0; i <= LOG_LENGTH; i++) { Console.SetCursorPosition(0, startingLine + i); Console.Write("\r" + new string(' ', Console.BufferWidth) + "\r"); Console.SetCursorPosition(0, startingLine); } } public static void SaveToFile() { string path = "GameLog_" + DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss") + ".txt"; File.WriteAllLines(path, messages.ToArray()); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShipGame { class Logger { private static List<string> messages = new List<string>(); private static int startingLine = 0; private static int LOG_LENGTH = 5; public static void Write(string message) { messages.Add(message); if(startingLine == 0) { startingLine = Console.CursorTop; } if (Console.CursorTop >= startingLine + LOG_LENGTH) { CleaLog(); } Console.WriteLine(message); } private static void CleaLog() { for (int i = 0; i < LOG_LENGTH; i++) { Console.SetCursorPosition(0, startingLine + i); Console.Write("\r" + new string(' ', Console.BufferWidth) + "\r"); Console.SetCursorPosition(0, startingLine); } } public static void SaveToFile() { string path = "GameLog_" + DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss") + ".txt"; File.WriteAllLines(path, messages.ToArray()); } } }
mit
C#
5025a8926113e79847e82057ace756065c80ee05
Set AssemblyVersion as 0.1
felipebz/ndapi
Ndapi/Properties/AssemblyInfo.cs
Ndapi/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("Ndapi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ndapi")] [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("9debde14-7c3c-4ebb-a3e9-5c8fbb7e0c04")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.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("Ndapi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ndapi")] [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("9debde14-7c3c-4ebb-a3e9-5c8fbb7e0c04")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
2eda53ed39adb2badcd7f0d5bf3bb05432bb4cd1
Update SolutionVersion.cs
gigya/microdot
SolutionVersion.cs
SolutionVersion.cs
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Gigya Inc.")] [assembly: AssemblyCopyright("© 2017 Gigya Inc.")] [assembly: AssemblyDescription("Microdot Framework")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")] [assembly: AssemblyInformationalVersion("1.4.0.0")] // 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)] [assembly: CLSCompliant(false)]
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Gigya Inc.")] [assembly: AssemblyCopyright("© 2017 Gigya Inc.")] [assembly: AssemblyDescription("Microdot Framework")] [assembly: AssemblyVersion("1.3.2.0")] [assembly: AssemblyFileVersion("1.3.2.0")] [assembly: AssemblyInformationalVersion("1.3.2.0")] // 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)] [assembly: CLSCompliant(false)]
apache-2.0
C#
cd756b12fe0e16bffb02b3152c19049940823568
increase version no
gigya/microdot
SolutionVersion.cs
SolutionVersion.cs
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Gigya Inc.")] [assembly: AssemblyCopyright("© 2017 Gigya Inc.")] [assembly: AssemblyDescription("Microdot Framework")] [assembly: AssemblyVersion("1.1.3.0")] [assembly: AssemblyFileVersion("1.1.3.0")] [assembly: AssemblyInformationalVersion("1.1.3.0")] // 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)] [assembly: CLSCompliant(false)]
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Gigya Inc.")] [assembly: AssemblyCopyright("© 2017 Gigya Inc.")] [assembly: AssemblyDescription("Microdot Framework")] [assembly: AssemblyVersion("1.1.2.0")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: AssemblyInformationalVersion("1.1.2.0")] // 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)] [assembly: CLSCompliant(false)]
apache-2.0
C#
07532064887dc0778e40fc527e7af9392b846ffb
fix unit test
Kusumoto/PromptPayQrCode
PromptPayQrCode.Test/ThaiPromptPayQrCodeImageTest.cs
PromptPayQrCode.Test/ThaiPromptPayQrCodeImageTest.cs
using System; using System.IO; using Xunit; namespace PromptPayQrCode.Test { public class ThaiPromptPayQrCodeImageTest { [Fact] public void Generate_PromptPay_Qr_With_Local_Phone_Number_No_Amount_Test() { var path = AppDomain.CurrentDomain.BaseDirectory; var filename = "test_qr"; var phoneNumber = "0801234567"; new PromptPayQrCode(phoneNumber).GeneratePromptPayQrCode(path, filename); Assert.True(File.Exists(string.Concat(path, filename, ".jpg"))); } } }
using System; using System.IO; using Xunit; namespace PromptPayQrCode.Test { public class ThaiPromptPayQrCodeImageTest { [Fact] public void Generate_PromptPay_Qr_With_Local_Phone_Number_No_Amount_Test() { var path = AppDomain.CurrentDomain.BaseDirectory; var filename = "test_qr"; var phoneNumber = "0801234567"; new PromptPayQrCode(phoneNumber).GeneratePromptPayQrCode(path, filename); Assert.True(File.Exists(string.Concat(path, filename, ".png"))); } } }
mit
C#
5663f45b027a642cf3fb39c9dafc327e19ec4c6c
Clean up PastebinException
nikibobi/pastebin-csharp
PastebinAPI/PastebinException.cs
PastebinAPI/PastebinException.cs
using System; using System.Collections.Generic; namespace PastebinAPI { public class PastebinException : Exception { public enum ParameterType { None, DevKey, ExpireDate, Option, PasteFormat, PastePrivate, UserKey, Login, DeletePastePermision, PostParameters } private static Dictionary<string, ParameterType> parameters = new Dictionary<string, ParameterType> { { "", ParameterType.None }, { "api_dev_key", ParameterType.DevKey }, { "api_expire_date", ParameterType.ExpireDate }, { "api_option", ParameterType.Option }, { "api_paste_format", ParameterType.PasteFormat }, { "api_paste_private", ParameterType.PastePrivate }, { "api_user_key", ParameterType.UserKey }, { "login", ParameterType.Login }, { "permission to remove paste", ParameterType.DeletePastePermision }, { "POST parameters", ParameterType.PostParameters } }; public ParameterType Parameter { get; private set; } public PastebinException(string message) : this(message, null) { } public PastebinException(string message, Exception innerException) : base(message, innerException) { if (message.Contains("Bad API request, invalid ")) { Parameter = parameters[message.Replace("Bad API request, invalid ", "")]; } } } }
using System; using System.Collections.Generic; namespace PastebinAPI { public class PastebinException : Exception { public enum ParameterType { None, DevKey, ExpireDate, Option, PasteFormat, PastePrivate, UserKey, Login, DeletePastePermision, PostParameters } private static Dictionary<string, ParameterType> parameters = new Dictionary<string, ParameterType> { {"", ParameterType.None}, { "api_dev_key", ParameterType.DevKey }, { "api_expire_date", ParameterType.ExpireDate }, { "api_option", ParameterType.Option }, { "api_paste_format", ParameterType.PasteFormat }, { "api_paste_private", ParameterType.PastePrivate }, { "api_user_key", ParameterType.UserKey }, { "login", ParameterType.Login }, { "permission to remove paste", ParameterType.DeletePastePermision }, { "POST parameters", ParameterType.PostParameters } }; public ParameterType Parameter { get; private set; } public PastebinException(string message) :this(message, null) { } public PastebinException(string message, Exception innerException) : base(message, innerException) { if (message.Contains("Bad API request, invalid ")) Parameter = parameters[message.Replace("Bad API request, invalid ", "")]; else Parameter = parameters[""]; } } }
mit
C#
c1177d19e86f439b7ee24b54d9e4e98e5fe61e2c
return IRazorLightEngine from EngineFactory
toddams/RazorLight,toddams/RazorLight
src/RazorLight/EngineFactory.cs
src/RazorLight/EngineFactory.cs
using System; using RazorLight.Caching; using RazorLight.Templating; using RazorLight.Templating.Embedded; using RazorLight.Templating.FileSystem; namespace RazorLight { public static class EngineFactory { /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates by searching them on physical storage /// and tracks file changes with <seealso cref="System.IO.FileSystemWatcher"/> /// </summary> /// <param name="root">Root folder where views are stored</param> public static IRazorLightEngine CreatePhysical(string root) { return CreatePhysical(root, EngineConfiguration.Default); } /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates by searching /// them on physical storage with a given <see cref="IEngineConfiguration"/> /// and tracks file changes with <seealso cref="System.IO.FileSystemWatcher"/> /// </summary> /// <param name="root">Root folder where views are stored</param> /// <param name="configuration">Engine configuration</param> public static IRazorLightEngine CreatePhysical(string root, IEngineConfiguration configuration) { if (string.IsNullOrEmpty(root)) { throw new ArgumentNullException(nameof(root)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } ITemplateManager templateManager = new FilesystemTemplateManager(root); IEngineCore core = new EngineCore(templateManager, configuration); ICompilerCache compilerCache = new TrackingCompilerCache(root); IPageFactoryProvider pageFactory = new CachingPageFactory(core.KeyCompile, compilerCache); IPageLookup pageLookup = new FilesystemPageLookup(pageFactory); return new RazorLightEngine(core, pageLookup); } /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates inside given type assembly as a EmbeddedResource /// </summary> /// <param name="rootType">Root type where resource is located</param> public static IRazorLightEngine CreateEmbedded(Type rootType) { return CreateEmbedded(rootType, EngineConfiguration.Default); } /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates inside given type assembly as a EmbeddedResource /// with a given <see cref="IEngineConfiguration"/> /// </summary> /// <param name="rootType">Root type where resource is located</param> /// <param name="configuration">Engine configuration</param> public static IRazorLightEngine CreateEmbedded(Type rootType, IEngineConfiguration configuration) { ITemplateManager manager = new EmbeddedResourceTemplateManager(rootType); var dependencies = CreateDefaultDependencies(manager, configuration); return new RazorLightEngine(dependencies.Item1, dependencies.Item2); } private static Tuple<IEngineCore, IPageLookup> CreateDefaultDependencies(ITemplateManager manager) { return CreateDefaultDependencies(manager, EngineConfiguration.Default); } private static Tuple<IEngineCore, IPageLookup> CreateDefaultDependencies( ITemplateManager manager, IEngineConfiguration configuration) { IEngineCore core = new EngineCore(manager, configuration); IPageFactoryProvider pageFactory = new DefaultPageFactory(core.KeyCompile); IPageLookup lookup = new DefaultPageLookup(pageFactory); return new Tuple<IEngineCore, IPageLookup>(core, lookup); } } }
using System; using RazorLight.Caching; using RazorLight.Templating; using RazorLight.Templating.Embedded; using RazorLight.Templating.FileSystem; namespace RazorLight { public static class EngineFactory { /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates by searching them on physical storage /// and tracks file changes with <seealso cref="System.IO.FileSystemWatcher"/> /// </summary> /// <param name="root">Root folder where views are stored</param> public static RazorLightEngine CreatePhysical(string root) { return CreatePhysical(root, EngineConfiguration.Default); } /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates by searching /// them on physical storage with a given <see cref="IEngineConfiguration"/> /// and tracks file changes with <seealso cref="System.IO.FileSystemWatcher"/> /// </summary> /// <param name="root">Root folder where views are stored</param> /// <param name="configuration">Engine configuration</param> public static RazorLightEngine CreatePhysical(string root, IEngineConfiguration configuration) { if (string.IsNullOrEmpty(root)) { throw new ArgumentNullException(nameof(root)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } ITemplateManager templateManager = new FilesystemTemplateManager(root); IEngineCore core = new EngineCore(templateManager, configuration); ICompilerCache compilerCache = new TrackingCompilerCache(root); IPageFactoryProvider pageFactory = new CachingPageFactory(core.KeyCompile, compilerCache); IPageLookup pageLookup = new FilesystemPageLookup(pageFactory); return new RazorLightEngine(core, pageLookup); } /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates inside given type assembly as a EmbeddedResource /// </summary> /// <param name="rootType">Root type where resource is located</param> public static RazorLightEngine CreateEmbedded(Type rootType) { return CreateEmbedded(rootType, EngineConfiguration.Default); } /// <summary> /// Creates a <see cref="RazorLightEngine"/> that resolves templates inside given type assembly as a EmbeddedResource /// with a given <see cref="IEngineConfiguration"/> /// </summary> /// <param name="rootType">Root type where resource is located</param> /// <param name="configuration">Engine configuration</param> public static RazorLightEngine CreateEmbedded(Type rootType, IEngineConfiguration configuration) { ITemplateManager manager = new EmbeddedResourceTemplateManager(rootType); var dependencies = CreateDefaultDependencies(manager, configuration); return new RazorLightEngine(dependencies.Item1, dependencies.Item2); } private static Tuple<IEngineCore, IPageLookup> CreateDefaultDependencies(ITemplateManager manager) { return CreateDefaultDependencies(manager, EngineConfiguration.Default); } private static Tuple<IEngineCore, IPageLookup> CreateDefaultDependencies( ITemplateManager manager, IEngineConfiguration configuration) { IEngineCore core = new EngineCore(manager, configuration); IPageFactoryProvider pageFactory = new DefaultPageFactory(core.KeyCompile); IPageLookup lookup = new DefaultPageLookup(pageFactory); return new Tuple<IEngineCore, IPageLookup>(core, lookup); } } }
apache-2.0
C#
d0a54dfaff12e5e4aaa25a4e7294b41f4b8e0ed1
Compress save files with GZip to save space (~20 times)
manio143/ShadowsOfShadows
src/Serialization/Serializer.cs
src/Serialization/Serializer.cs
using System; using System.IO; using System.IO.Compression; using System.Linq; using Microsoft.Xna.Framework; using YamlDotNet.Serialization; using ShadowsOfShadows.Entities; using ShadowsOfShadows.Items; using ShadowsOfShadows.Renderables; using ShadowsOfShadows.Helpers; namespace ShadowsOfShadows.Serialization { public static class Serializer { private static string SaveFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ShadowsOfShadows", "savedgames"); private static FileStream OpenFile(SaveSlot slot, bool create = false) { if (!Directory.Exists(SaveFolder)) Directory.CreateDirectory(SaveFolder); if (File.Exists(SaveFolder + "/" + slot + ".sav") && create) File.WriteAllText(SaveFolder + "/" + slot + ".sav", String.Empty); return File.Open(SaveFolder + "/" + slot + ".sav", create ? FileMode.OpenOrCreate : FileMode.Open); } public static void Save(SaveSlot slot, GameState state) { try { var serializer = new SerializerBuilder() .EnsureRoundtrip() //save type info .EmitDefaults() //save default values .WithTypeConverter(new PrimitivesConverter()) .Build(); using (var compression = new GZipStream(OpenFile(slot, true), CompressionMode.Compress)) using (var writer = new StreamWriter(compression)) serializer.Serialize(writer, state); } catch (Exception e) { Console.WriteLine("{0}\n{1}", e.GetType(), e.Message); } } public static GameState Load(SaveSlot slot) { var deserializer = new DeserializerBuilder() .WithTypeConverter(new PrimitivesConverter()) .Build(); using (var compression = new GZipStream(OpenFile(slot), CompressionMode.Decompress)) using (var reader = new StreamReader(compression)) return deserializer.Deserialize<GameState>(reader); } } }
using System; using System.IO; using System.Linq; using Microsoft.Xna.Framework; using YamlDotNet.Serialization; using ShadowsOfShadows.Entities; using ShadowsOfShadows.Items; using ShadowsOfShadows.Renderables; using ShadowsOfShadows.Helpers; namespace ShadowsOfShadows.Serialization { public static class Serializer { private static string SaveFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ShadowsOfShadows", "savedgames"); private static FileStream OpenFile(SaveSlot slot, bool create = false) { if (!Directory.Exists(SaveFolder)) Directory.CreateDirectory(SaveFolder); if (File.Exists(SaveFolder + "/" + slot + ".sav") && create) File.WriteAllText(SaveFolder + "/" + slot + ".sav", String.Empty); return File.Open(SaveFolder + "/" + slot + ".sav", create ? FileMode.OpenOrCreate : FileMode.Open); } public static void Save(SaveSlot slot, GameState state) { try { var serializer = new SerializerBuilder() .EnsureRoundtrip() //save type info .EmitDefaults() //save default values .WithTypeConverter(new PrimitivesConverter()) .Build(); using (var writer = new StreamWriter(OpenFile(slot, true))) serializer.Serialize(writer, state); } catch (Exception e) { Console.WriteLine("{0}\n{1}", e.GetType(), e.Message); } } public static GameState Load(SaveSlot slot) { var deserializer = new DeserializerBuilder() .WithTypeConverter(new PrimitivesConverter()) .Build(); using (var reader = new StreamReader(OpenFile(slot))) return deserializer.Deserialize<GameState>(reader); } } }
mit
C#
9b19884ff44d731a9c18db49a6ed246b3d12964c
Change serialize/deserialize functions to abstract
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/LiteNetLibMessageBase.cs
Scripts/LiteNetLibMessageBase.cs
using LiteNetLib.Utils; namespace LiteNetLibHighLevel { public abstract class LiteNetLibMessageBase { public abstract void Deserialize(NetDataReader reader); public abstract void Serialize(NetDataWriter writer); } }
using LiteNetLib.Utils; namespace LiteNetLibHighLevel { public abstract class LiteNetLibMessageBase { public virtual void Deserialize(NetDataReader reader) { } public virtual void Serialize(NetDataWriter writer) { } } }
mit
C#
941e4fe184f9c71343f7bfbfc4e38fe200e644a8
Fix task name.
wbap/hackathon-2017-sample,wbap/hackathon-2017-sample,wbap/hackathon-2017-sample,wbap/hackathon-2017-sample
environment/Assets/Scripts/OneDimTask7.cs
environment/Assets/Scripts/OneDimTask7.cs
using UnityEngine; public class OneDimTask7 : OneDimTaskBase { public GameObject reward; public ShapeSelector selector; bool rewardShown = false; int waited = 0; int elapsed = 0; Range range; public override string Name() { return "One Dimensional Task 7"; } public override void Initialize(int success, int failure) { int phase = (int)(Random.value * 3); selector.Selection = phase; switch(phase) { case 0: range = Range.Red; break; case 1: range = Range.Green; break; case 2: range = Range.Blue; break; default: break; } } void Update() { float z = agent.transform.position.z; if(elapsed < 120) { agent.controller.Paralyzed = true; selector.Visible = true; elapsed += 1; } else { agent.controller.Paralyzed = false; selector.Visible = false; } if(range.start <= z && z <= range.end) { if(!rewardShown && waited >= 2 * 60) { rewardCount += 1; Reward.Add(2.0F); GameObject rewardObj = (GameObject)GameObject.Instantiate( reward, new Vector3(0.0F, 0.5F, 23.0F), Quaternion.identity ); rewardObj.transform.parent = transform; rewardShown = true; } waited += 1; } else { waited = 0; } } }
using UnityEngine; public class OneDimTask7 : OneDimTaskBase { public GameObject reward; public ShapeSelector selector; bool rewardShown = false; int waited = 0; int elapsed = 0; Range range; public override string Name() { return "One Dimensional Task 6"; } public override void Initialize(int success, int failure) { int phase = (int)(Random.value * 3); selector.Selection = phase; switch(phase) { case 0: range = Range.Red; break; case 1: range = Range.Green; break; case 2: range = Range.Blue; break; default: break; } } void Update() { float z = agent.transform.position.z; if(elapsed < 120) { agent.controller.Paralyzed = true; selector.Visible = true; elapsed += 1; } else { agent.controller.Paralyzed = false; selector.Visible = false; } if(range.start <= z && z <= range.end) { if(!rewardShown && waited >= 2 * 60) { rewardCount += 1; Reward.Add(2.0F); GameObject rewardObj = (GameObject)GameObject.Instantiate( reward, new Vector3(0.0F, 0.5F, 23.0F), Quaternion.identity ); rewardObj.transform.parent = transform; rewardShown = true; } waited += 1; } else { waited = 0; } } }
apache-2.0
C#
65f063788dfc8c3cdddf63c16c4e027342c1e9f3
Check admin user from controller.
RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,nvisionative/Dnn.Platform,nvisionative/Dnn.Platform,EPTamminga/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,dnnsoftware/Dnn.Platform,robsiera/Dnn.Platform,robsiera/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform
src/Modules/Content/Dnn.PersonaBar.Pages/MenuControllers/PagesMenuController.cs
src/Modules/Content/Dnn.PersonaBar.Pages/MenuControllers/PagesMenuController.cs
#region Copyright // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2017 // by DotNetNuke Corporation // // 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. #endregion using System.Collections.Generic; using System.Linq; using Dnn.PersonaBar.Library.Controllers; using Dnn.PersonaBar.Library.Model; using Dnn.PersonaBar.Library.Permissions; using Dnn.PersonaBar.Pages.Components.Security; using DotNetNuke.Application; using DotNetNuke.Entities.Portals; namespace Dnn.PersonaBar.Pages.MenuControllers { public class PagesMenuController : IMenuItemController { private readonly ISecurityService _securityService; public PagesMenuController() { _securityService = SecurityService.Instance; } public void UpdateParameters(MenuItem menuItem) { } public bool Visible(MenuItem menuItem) { return _securityService.IsVisible(menuItem); } public IDictionary<string, object> GetSettings(MenuItem menuItem) { var settings = new Dictionary<string, object> { {"canSeePagesList", _securityService.CanViewPageList(menuItem.MenuId)}, {"portalName", PortalSettings.Current.PortalName}, {"currentPagePermissions", _securityService.GetCurrentPagePermissions()}, {"currentPageName", PortalSettings.Current?.ActiveTab?.TabName}, {"productSKU", DotNetNukeContext.Current.Application.SKU}, {"isAdmin", _securityService.IsPageAdminUser() } }; return settings; } } }
#region Copyright // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2017 // by DotNetNuke Corporation // // 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. #endregion using System.Collections.Generic; using System.Linq; using Dnn.PersonaBar.Library.Controllers; using Dnn.PersonaBar.Library.Model; using Dnn.PersonaBar.Library.Permissions; using Dnn.PersonaBar.Pages.Components.Security; using DotNetNuke.Application; using DotNetNuke.Entities.Portals; namespace Dnn.PersonaBar.Pages.MenuControllers { public class PagesMenuController : IMenuItemController { private readonly ISecurityService _securityService; public PagesMenuController() { _securityService = SecurityService.Instance; } public void UpdateParameters(MenuItem menuItem) { } public bool Visible(MenuItem menuItem) { return _securityService.IsVisible(menuItem); } public IDictionary<string, object> GetSettings(MenuItem menuItem) { var settings = new Dictionary<string, object> { {"canSeePagesList", _securityService.CanViewPageList(menuItem.MenuId)}, {"portalName", PortalSettings.Current.PortalName}, {"currentPagePermissions", _securityService.GetCurrentPagePermissions()}, {"currentPageName", PortalSettings.Current?.ActiveTab?.TabName}, {"productSKU", DotNetNukeContext.Current.Application.SKU} }; return settings; } } }
mit
C#
5cae927cf03737bdfd013d84654cb076266095bf
Add dbus-sharp-glib to friend assemblies
tmds/Tmds.DBus
AssemblyInfo.cs
AssemblyInfo.cs
// Copyright 2006 Alp Toker <[email protected]> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-sharp-glib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
// Copyright 2006 Alp Toker <[email protected]> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
mit
C#
2df89d46b243ea121369fe8c4ce46d634e40bad4
Add client_iden field to push requests
adamyeager/PushbulletSharp,DriesPeeters/PushbulletSharp
PushbulletSharp/Models/Requests/PushRequestBase.cs
PushbulletSharp/Models/Requests/PushRequestBase.cs
using System.Runtime.Serialization; namespace PushbulletSharp.Models.Requests { [DataContract] public abstract class PushRequestBase { /// <summary> /// Gets or sets the device iden. /// </summary> /// <value> /// The device iden. /// </value> [DataMember(Name = "device_iden")] public string DeviceIden { get; set; } /// <summary> /// Gets or sets the email. /// </summary> /// <value> /// The email. /// </value> [DataMember(Name = "email")] public string Email { get; set; } /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> [DataMember(Name = "type")] public string Type { get; protected set; } /// <summary> /// Gets or sets the source_device_iden. /// </summary> /// <value> /// The source_device_iden. /// </value> [DataMember(Name = "source_device_iden")] public string SourceDeviceIden { get; set; } /// <summary> /// Gets or sets the client_iden /// </summary> /// <value> /// The client_iden. /// </value> [DataMember(Name = "client_iden")] public string ClientIden { get; set; } /// <summary> /// Gets or sets the channel tag /// </summary> /// <value> /// The channel_tag. /// </value> [DataMember(Name = "channel_tag")] public string ChannelTag { get; set; } } }
using System.Runtime.Serialization; namespace PushbulletSharp.Models.Requests { [DataContract] public abstract class PushRequestBase { /// <summary> /// Gets or sets the device iden. /// </summary> /// <value> /// The device iden. /// </value> [DataMember(Name = "device_iden")] public string DeviceIden { get; set; } /// <summary> /// Gets or sets the email. /// </summary> /// <value> /// The email. /// </value> [DataMember(Name = "email")] public string Email { get; set; } /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> [DataMember(Name = "type")] public string Type { get; protected set; } /// <summary> /// Gets or sets the source_device_iden. /// </summary> /// <value> /// The source_device_iden. /// </value> [DataMember(Name = "source_device_iden")] public string SourceDeviceIden { get; set; } /// <summary> /// Gets or sets the channel tag /// </summary> /// <value> /// The channel_tag. /// </value> [DataMember(Name = "channel_tag")] public string ChannelTag { get; set; } } }
mit
C#
093b76e0ff59662353cd04ee865ccd54f5ba755d
Fix drawable mania judgement scene looking broken
ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game.Rulesets.Mania.Tests/Skinning/TestSceneDrawableJudgement.cs
osu.Game.Rulesets.Mania.Tests/Skinning/TestSceneDrawableJudgement.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Scoring; using osu.Game.Rulesets.Mania.Skinning.Legacy; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Tests.Skinning { public class TestSceneDrawableJudgement : ManiaSkinnableTestScene { public TestSceneDrawableJudgement() { var hitWindows = new ManiaHitWindows(); foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1)) { if (hitWindows.IsHitResultAllowed(result)) { AddStep("Show " + result.GetDescription(), () => { SetContents(_ => new DrawableManiaJudgement(new JudgementResult(new HitObject { StartTime = Time.Current }, new Judgement()) { Type = result }, null) { Anchor = Anchor.Centre, Origin = Anchor.Centre, }); // for test purposes, undo the Y adjustment related to the `ScorePosition` legacy positioning config value // (see `LegacyManiaJudgementPiece.load()`). // this prevents the judgements showing somewhere below or above the bounding box of the judgement. foreach (var legacyPiece in this.ChildrenOfType<LegacyManiaJudgementPiece>()) legacyPiece.Y = 0; }); } } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Scoring; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Tests.Skinning { public class TestSceneDrawableJudgement : ManiaSkinnableTestScene { public TestSceneDrawableJudgement() { var hitWindows = new ManiaHitWindows(); foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1)) { if (hitWindows.IsHitResultAllowed(result)) { AddStep("Show " + result.GetDescription(), () => SetContents(_ => new DrawableManiaJudgement(new JudgementResult(new HitObject { StartTime = Time.Current }, new Judgement()) { Type = result }, null) { Anchor = Anchor.Centre, Origin = Anchor.Centre, })); } } } } }
mit
C#
a33f84d5251382cc0f7ca5a5b4231240e843ca7a
Fix #95: Restrict platforms the P/Invoke SetEnvironmentVariable.
IronLanguages/ironpython2,slozier/ironpython2,slozier/ironpython2,slozier/ironpython2,slozier/ironpython2,slozier/ironpython2,IronLanguages/ironpython2,IronLanguages/ironpython2,IronLanguages/ironpython2,slozier/ironpython2,IronLanguages/ironpython2,slozier/ironpython2,IronLanguages/ironpython2,IronLanguages/ironpython2
Runtime/Microsoft.Scripting/Utils/NativeMethods.cs
Runtime/Microsoft.Scripting/Utils/NativeMethods.cs
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_NATIVE using System; using System.Runtime.InteropServices; namespace Microsoft.Scripting.Utils { internal static class NativeMethods { [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError=true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetEnvironmentVariable(string name, string value); } } #endif
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !SILVERLIGHT using System; using System.Runtime.InteropServices; namespace Microsoft.Scripting.Utils { internal static class NativeMethods { [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError=true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetEnvironmentVariable(string name, string value); } } #endif
apache-2.0
C#
366040c3a625dbb31265e56f2f3204412ff01f05
break the build to check travis ci
Isantipov/mqpi,Isantipov/mqpi
mqpi/Controllers/MockedController.cs
mqpi/Controllers/MockedController.cs
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace mqpi.Controllers { [Route("api/{type}")] public class MockedController : Controller { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MockedController)); // GET api/values [HttpGet] public IEnumerable<dynamic> Get(string type) { log.Info($"GET {type}"); return new dynamic[]{; } // GET api/values/5 [HttpGet("{id}")] public ActionResult Get(string type, int id) { log.Info($"GET {type} id = {id}"); return new NotFoundObjectResult($"{type} with id='{id}' was not found"); } // POST api/values [HttpPost] public object Post(string type, [FromBody]dynamic value) { var random = new Random(DateTime.UtcNow.Second); value.Id = random.Next(); return value; } // PUT api/values/5 [HttpPut("{id}")] public dynamic Put(string type, [FromBody]dynamic value, int id) { if (value.Id != id) { return new BadRequestObjectResult("Id in the object must match id in URI"); } return value; } // DELETE api/values/5 [HttpDelete("{id}")] public ActionResult Delete(string type, int id) { return Ok($"{type} {id} has been removed"); } } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace mqpi.Controllers { [Route("api/{type}")] public class MockedController : Controller { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MockedController)); // GET api/values [HttpGet] public IEnumerable<dynamic> Get(string type) { log.Info($"GET {type}"); return new dynamic[]{}; } // GET api/values/5 [HttpGet("{id}")] public ActionResult Get(string type, int id) { log.Info($"GET {type} id = {id}"); return new NotFoundObjectResult($"{type} with id='{id}' was not found"); } // POST api/values [HttpPost] public object Post(string type, [FromBody]dynamic value) { var random = new Random(DateTime.UtcNow.Second); value.Id = random.Next(); return value; } // PUT api/values/5 [HttpPut("{id}")] public dynamic Put(string type, [FromBody]dynamic value, int id) { if (value.Id != id) { return new BadRequestObjectResult("Id in the object must match id in URI"); } return value; } // DELETE api/values/5 [HttpDelete("{id}")] public ActionResult Delete(string type, int id) { return Ok($"{type} {id} has been removed"); } } }
mit
C#
ff5c47be59506173113c8bca608d93b87e701faf
Write if differ file write tests.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Tests/StoreTests.cs
WalletWasabi.Tests/StoreTests.cs
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using WalletWasabi.Stores; using Xunit; namespace WalletWasabi.Tests { public class StoreTests { [Fact] public async Task IndexStoreTestsAsync() { var indexStore = new IndexStore(); var dir = Path.Combine(Global.DataDir, nameof(IndexStoreTestsAsync)); var network = Network.Main; await indexStore.InitializeAsync(dir, network); } [Fact] public async Task IoManagerTestsAsync() { var file1 = Path.Combine(Global.DataDir, nameof(IoManagerTestsAsync), $"file1.dat"); var file2 = Path.Combine(Global.DataDir, nameof(IoManagerTestsAsync), $"file2.dat"); Random random = new Random(); List<string> lines = new List<string>(); for (int i = 0; i < 1000; i++) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string line = new string(Enumerable.Repeat(chars, 100) .Select(s => s[random.Next(s.Length)]).ToArray()); lines.Add(line); } // Single thread file operations. IoManager ioman1 = new IoManager(file1); // Delete the file if Exist. ioman1.DeleteMe(); Assert.False(ioman1.Exists()); Assert.False(File.Exists(ioman1.DigestFilePath)); // Write the data to the file. await ioman1.WriteAllLinesAsync(lines); Assert.True(ioman1.Exists()); // Check if the digest file is created. Assert.True(File.Exists(ioman1.DigestFilePath)); // Read back the content and check. var readLines = await ioman1.ReadAllLinesAsync(); Assert.Equal(readLines.Length, lines.Count); for (int i = 0; i < lines.Count; i++) { string line = lines[i]; var readline = readLines[i]; Assert.Equal(readline, line); } // Check digest file, and write only differ logic. using (File.OpenWrite(ioman1.OriginalFilePath)) { // Should be OK because the same data is written. await ioman1.WriteAllLinesAsync(lines); } lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit."); using (File.OpenWrite(ioman1.OriginalFilePath)) { // Should fail because different data is written. await Assert.ThrowsAsync<IOException>(async () => await ioman1.WriteAllLinesAsync(lines)); } } } }
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using WalletWasabi.Stores; using Xunit; namespace WalletWasabi.Tests { public class StoreTests { [Fact] public async Task IndexStoreTestsAsync() { var indexStore = new IndexStore(); var dir = Path.Combine(Global.DataDir, nameof(IndexStoreTestsAsync)); var network = Network.Main; await indexStore.InitializeAsync(dir, network); } [Fact] public async Task IoManagerTestsAsync() { var file1 = Path.Combine(Global.DataDir, nameof(IoManagerTestsAsync), $"file1.dat"); var file2 = Path.Combine(Global.DataDir, nameof(IoManagerTestsAsync), $"file2.dat"); Random random = new Random(); List<string> lines = new List<string>(); for (int i = 0; i < 1000; i++) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string line = new string(Enumerable.Repeat(chars, 100) .Select(s => s[random.Next(s.Length)]).ToArray()); lines.Add(line); } // Single thread file operations. IoManager ioman1 = new IoManager(file1); // Delete the file if Exist. ioman1.DeleteMe(); Assert.False(ioman1.Exists()); // Write the data to the file. await ioman1.WriteAllLinesAsync(lines); Assert.True(ioman1.Exists()); // Read back the content and check. var readLines = await ioman1.ReadAllLinesAsync(); Assert.Equal(readLines.Length, lines.Count); for (int i = 0; i < lines.Count; i++) { string line = lines[i]; var readline = readLines[i]; Assert.Equal(readline, line); } } } }
mit
C#
143589c9cb670b50d9c760068d683590c99a2e26
remove not needed #if directives - AnalyticsServices
RadicalFx/radical
src/Radical/AnalyticsService.cs
src/Radical/AnalyticsService.cs
using System; using System.Security.Principal; using System.Threading; namespace Radical { namespace ComponentModel { public interface IAnalyticsServices { Boolean IsEnabled { get; set; } void TrackUserActionAsync(Analytics.AnalyticsEvent action); } } namespace Services { class AnalyticsServices : ComponentModel.IAnalyticsServices { public void TrackUserActionAsync(Analytics.AnalyticsEvent action) { Analytics.AnalyticsServices.TrackUserActionAsync(action); } public bool IsEnabled { get { return Analytics.AnalyticsServices.IsEnabled; } set { Analytics.AnalyticsServices.IsEnabled = value; } } } } namespace Analytics { public static class AnalyticsServices { public static Boolean IsEnabled { get; set; } public static void TrackUserActionAsync(AnalyticsEvent action) { if (IsEnabled && UserActionTrackingHandler != null) { System.Threading.Tasks.Task.Factory.StartNew(() => { UserActionTrackingHandler(action); }); } } public static Action<AnalyticsEvent> UserActionTrackingHandler { get; set; } } /// <summary> /// TODO /// </summary> public class AnalyticsEvent { /// <summary> /// Initializes a new instance of the <see cref="AnalyticsEvent" /> class. /// </summary> public AnalyticsEvent() { this.ExecutedOn = DateTimeOffset.Now; } public DateTimeOffset ExecutedOn { get; set; } public String Name { get; set; } public Object Data { get; set; } } } }
using System; using System.Security.Principal; using System.Threading; namespace Radical { namespace ComponentModel { public interface IAnalyticsServices { Boolean IsEnabled { get; set; } void TrackUserActionAsync(Analytics.AnalyticsEvent action); } } namespace Services { class AnalyticsServices : ComponentModel.IAnalyticsServices { public void TrackUserActionAsync(Analytics.AnalyticsEvent action) { Analytics.AnalyticsServices.TrackUserActionAsync(action); } public bool IsEnabled { get { return Analytics.AnalyticsServices.IsEnabled; } set { Analytics.AnalyticsServices.IsEnabled = value; } } } } namespace Analytics { public static class AnalyticsServices { public static Boolean IsEnabled { get; set; } public static void TrackUserActionAsync(AnalyticsEvent action) { if (IsEnabled && UserActionTrackingHandler != null) { System.Threading.Tasks.Task.Factory.StartNew(() => { UserActionTrackingHandler(action); }); } } public static Action<AnalyticsEvent> UserActionTrackingHandler { get; set; } } /// <summary> /// TODO /// </summary> public class AnalyticsEvent { /// <summary> /// Initializes a new instance of the <see cref="AnalyticsEvent" /> class. /// </summary> public AnalyticsEvent() { this.ExecutedOn = DateTimeOffset.Now; #if !SILVERLIGHT && !NETFX_CORE this.Identity = Thread.CurrentPrincipal.Identity; #endif } public DateTimeOffset ExecutedOn { get; set; } public String Name { get; set; } public Object Data { get; set; } #if !SILVERLIGHT && !NETFX_CORE public IIdentity Identity { get; set; } #endif } } }
mit
C#
f79728b63a0fffe12f18b84c381d8d88f61d14ef
Add cull as final step
RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake
src/Snowflake.Framework/Scraping/GameScrapeContextAsyncEnumerator.cs
src/Snowflake.Framework/Scraping/GameScrapeContextAsyncEnumerator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Snowflake.Scraping { internal class GameScrapeContextAsyncEnumerator : IAsyncEnumerator<IEnumerable<ISeed>> { public GameScrapeContextAsyncEnumerator(GameScrapeContext context, CancellationToken token) { this.Current = Enumerable.Empty<ISeed>(); this.Context = context; this.Token = token; this.CullersRun = false; } public IEnumerable<ISeed> Current { get; private set; } private GameScrapeContext Context { get; } public CancellationToken Token { get; } private bool CullersRun { get; set; } public ValueTask DisposeAsync() { // what do i do here? there's nothing to dispose! return new ValueTask(); } public async ValueTask<bool> MoveNextAsync() { // is this the correct value for this? if (this.Token.IsCancellationRequested) return false; bool retVal = await this.Context.Proceed(); this.Current = this.Context.Context.GetUnculled(); if (!retVal && !this.CullersRun) { this.Context.Cull(); this.CullersRun = true; return true; } return retVal; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Snowflake.Scraping { internal class GameScrapeContextAsyncEnumerator : IAsyncEnumerator<IEnumerable<ISeed>> { public GameScrapeContextAsyncEnumerator(GameScrapeContext context, CancellationToken token) { this.Current = Enumerable.Empty<ISeed>(); this.Context = context; this.Token = token; } public IEnumerable<ISeed> Current { get; private set; } private GameScrapeContext Context { get; } public CancellationToken Token { get; } public ValueTask DisposeAsync() { // what do i do here? there's nothing to dispose! return new ValueTask(); } public async ValueTask<bool> MoveNextAsync() { // is this the correct value for this? if (this.Token.IsCancellationRequested) return false; bool retVal = await this.Context.Proceed(); this.Current = this.Context.Context.GetUnculled(); return retVal; } } }
mpl-2.0
C#
139070df59b53014f81120c11e1caadb5850c0db
Fix AssemblyInfo for Security.Interop.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.Owin.Security.Interop.Test/Properties/AssemblyInfo.cs
test/Microsoft.Owin.Security.Interop.Test/Properties/AssemblyInfo.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a2b5dc39-68d5-4145-a8cc-6aeab7d33a24")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Owin.Security.Interop.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Owin.Security.Interop.Test")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a2b5dc39-68d5-4145-a8cc-6aeab7d33a24")]
apache-2.0
C#
a5bb516052e5623a6c0cb25e76097b6197a68d41
Update XProperty.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D/Data/XProperty.cs
src/Core2D/Data/XProperty.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Core2D.Attributes; namespace Core2D.Data { /// <summary> /// Data property. /// </summary> public class XProperty : ObservableObject { private string _value; private XContext _owner; /// <summary> /// Gets or sets property value. /// </summary> [Content] public string Value { get => _value; set => Update(ref _value, value); } /// <summary> /// Gets or sets property owner. /// </summary> public XContext Owner { get => _owner; set => Update(ref _owner, value); } /// <summary> /// Creates a new <see cref="XProperty"/> instance. /// </summary> /// <param name="owner">The property owner.</param> /// <param name="name">The property name.</param> /// <param name="value">The property value.</param> /// <returns>The new instance of the <see cref="XProperty"/> class.</returns> public static XProperty Create(XContext owner, string name, string value) { return new XProperty() { Name = name, Value = value, Owner = owner }; } /// <inheritdoc/> public override string ToString() => _value.ToString(); /// <summary> /// Check whether the <see cref="Value"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeValue() => !String.IsNullOrWhiteSpace(_value); /// <summary> /// Check whether the <see cref="Owner"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeOwner() => _owner != null; } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Core2D.Attributes; namespace Core2D.Data { /// <summary> /// Data property. /// </summary> public class XProperty : ObservableObject { private string _name; private string _value; private XContext _owner; /// <summary> /// Gets or sets property name. /// </summary> public string Name { get => _name; set => Update(ref _name, value); } /// <summary> /// Gets or sets property value. /// </summary> [Content] public string Value { get => _value; set => Update(ref _value, value); } /// <summary> /// Gets or sets property owner. /// </summary> public XContext Owner { get => _owner; set => Update(ref _owner, value); } /// <summary> /// Creates a new <see cref="XProperty"/> instance. /// </summary> /// <param name="owner">The property owner.</param> /// <param name="name">The property name.</param> /// <param name="value">The property value.</param> /// <returns>The new instance of the <see cref="XProperty"/> class.</returns> public static XProperty Create(XContext owner, string name, string value) { return new XProperty() { Name = name, Value = value, Owner = owner }; } /// <inheritdoc/> public override string ToString() => _value.ToString(); /// <summary> /// Check whether the <see cref="Name"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeName() => !String.IsNullOrWhiteSpace(_name); /// <summary> /// Check whether the <see cref="Value"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeValue() => !String.IsNullOrWhiteSpace(_value); /// <summary> /// Check whether the <see cref="Owner"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeOwner() => _owner != null; } }
mit
C#
bd09157978581d6463c5320b92f11b96ae5542f5
change to list interface
tparnell8/XIVSync.Net
src/XIVSync.Net/LodestoneApi.cs
src/XIVSync.Net/LodestoneApi.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using CsQuery; using CsQuery.ExtensionMethods; using CsQuery.Web; using Newtonsoft.Json; using RestSharp; namespace XIVSync.Net { public class LodestoneApi { public LodestoneSearch SearchCharacter(string character, string server, int timeout = 90000) { var client = new RestClient("http://xivsync.com/") {Timeout = timeout}; var req = new RestRequest("search/character", Method.GET); req.AddParameter("name", character); req.AddParameter("server", server); var response = client.Execute(req); return response.StatusCode != HttpStatusCode.OK ? null : JsonConvert.DeserializeObject<LodestoneSearch>(response.Content); } public LodestoneCharacter GetCharacter(string characterId, int timeout = 90000) { var client = new RestClient("http://xivsync.com/") {Timeout = timeout}; var req = new RestRequest("character/get"); req.AddParameter("lodestone", characterId); var response = client.Execute(req); return response.StatusCode != HttpStatusCode.OK ? null : JsonConvert.DeserializeObject<LodestoneCharacter>(response.Content); } public IList<Server> GetServers(double timeoutSeconds = 90) { var dom = CQ.CreateFromUrl("http://na.finalfantasyxiv.com/lodestone/worldstatus/", new ServerConfig() {TimeoutSeconds = timeoutSeconds}); var servers = new List<Server>(); foreach (var node in dom[".worldstatus_1"]) { var serverName = node.ChildNodes.First(a => a.NodeName == "TD").FirstElementChild.InnerText.Trim(); var online = node.ChildNodes.Last(a => a.NodeName == "TD").FirstElementChild.InnerText.Trim(); servers.Add(new Server() {World = serverName, Online = online.Contains("Online")}); } return servers; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using CsQuery; using CsQuery.ExtensionMethods; using CsQuery.Web; using Newtonsoft.Json; using RestSharp; namespace XIVSync.Net { public class LodestoneApi { public LodestoneSearch SearchCharacter(string character, string server, int timeout = 90000) { var client = new RestClient("http://xivsync.com/") {Timeout = timeout}; var req = new RestRequest("search/character", Method.GET); req.AddParameter("name", character); req.AddParameter("server", server); var response = client.Execute(req); return response.StatusCode != HttpStatusCode.OK ? null : JsonConvert.DeserializeObject<LodestoneSearch>(response.Content); } public LodestoneCharacter GetCharacter(string characterId, int timeout = 90000) { var client = new RestClient("http://xivsync.com/") {Timeout = timeout}; var req = new RestRequest("character/get"); req.AddParameter("lodestone", characterId); var response = client.Execute(req); return response.StatusCode != HttpStatusCode.OK ? null : JsonConvert.DeserializeObject<LodestoneCharacter>(response.Content); } public IEnumerable<Server> GetServers(double timeoutSeconds = 90) { var dom = CQ.CreateFromUrl("http://na.finalfantasyxiv.com/lodestone/worldstatus/", new ServerConfig() {TimeoutSeconds = timeoutSeconds}); var servers = new List<Server>(); foreach (var node in dom[".worldstatus_1"]) { var serverName = node.ChildNodes.First(a => a.NodeName == "TD").FirstElementChild.InnerText.Trim(); var online = node.ChildNodes.Last(a => a.NodeName == "TD").FirstElementChild.InnerText.Trim(); servers.Add(new Server() {World = serverName, Online = online.Contains("Online")}); } return servers; } } }
mit
C#
d52a7362d4290b6b6d00759e5ab05581195a8eb2
set console encoding to UTF-8
cityindex/LogSearchShipper,modulexcite/LogSearchShipper
src/MtLogTailer/Program.cs
src/MtLogTailer/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace MtLogTailer { static class Program { static void Main(string[] args) { try { if (args.Length != 1) throw new ApplicationException("Invalid args. Should use MtLogTailer.exe <filePath> <encoding: optional>"); var path = args[0]; var encoding = 936; //Default to gb2312-> ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) if (args.Length >= 2) encoding = Convert.ToInt32(args[1]); Console.OutputEncoding = Encoding.UTF8; var watcher = new PathWatcher(path, encoding); Console.CancelKeyPress += (sender, eventArgs) => { Terminate = true; watcher.Stop(); eventArgs.Cancel = true; }; watcher.Process(); } catch (ThreadInterruptedException) { } catch (ApplicationException exc) { Log("{0} {1}", FormatTime(), Escape(exc.Message)); } catch (Exception exc) { Log("{0} {1}", FormatTime(), Escape(exc.ToString())); } } static void Log(string format, params object[] args) { try { var message = string.Format(format, args); Console.WriteLine(message); File.AppendAllText("MtLogTailer.log", message); } catch (Exception exc) { Trace.WriteLine(exc); } } static string Escape(string val) { return val.Replace(Environment.NewLine, "\\r\\n"); } static string FormatTime() { return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); } public static volatile bool Terminate; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace MtLogTailer { static class Program { static void Main(string[] args) { try { if (args.Length != 1) throw new ApplicationException("Invalid args. Should use MtLogTailer.exe <filePath> <encoding: optional>"); var path = args[0]; var encoding = 936; //Default to gb2312-> ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) if (args.Length >= 2) encoding = Convert.ToInt32(args[1]); var watcher = new PathWatcher(path, encoding); Console.CancelKeyPress += (sender, eventArgs) => { Terminate = true; watcher.Stop(); eventArgs.Cancel = true; }; watcher.Process(); } catch (ThreadInterruptedException) { } catch (ApplicationException exc) { Log("{0} {1}", FormatTime(), Escape(exc.Message)); } catch (Exception exc) { Log("{0} {1}", FormatTime(), Escape(exc.ToString())); } } static void Log(string format, params object[] args) { try { var message = string.Format(format, args); Console.WriteLine(message); File.AppendAllText("MtLogTailer.log", message); } catch (Exception exc) { Trace.WriteLine(exc); } } static string Escape(string val) { return val.Replace(Environment.NewLine, "\\r\\n"); } static string FormatTime() { return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); } public static volatile bool Terminate; } }
apache-2.0
C#
2751cbfaba65569c2fdefad87fa00a89be9e9968
Bump version.
FacilityApi/FacilityCSharp
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("0.4.1.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
mit
C#
d08aad712447d5a78992464df9523d36fe7754a0
Bump version to v1.2.1, breaking change for Data.HashFunction.CRC only.
brandondahler/Data.HashFunction,dbckr/Data.HashFunction
SolutionInfo.cs
SolutionInfo.cs
using System; using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Data.HashFunction Developers")] [assembly: AssemblyCopyright("Copyright 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("1.2.1")]
using System; using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Data.HashFunction Developers")] [assembly: AssemblyCopyright("Copyright 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("1.1.1")]
mit
C#
70758b2850faeb9710a201216d881d78d680ac82
Add helper methods to http descriptor. This provides a more fluent interface between setting name and description with actions.
khalidabuhakmeh/descriptor,kendaleiv/descriptor,ritterim/descriptor,kendaleiv/descriptor
src/Descriptor/HttpDescriptor.cs
src/Descriptor/HttpDescriptor.cs
using System; using System.Linq.Expressions; using RimDev.Descriptor.Generic; namespace RimDev.Descriptor { public class HttpDescriptor<TClass> : Descriptor<TClass> where TClass : class, new() { public HttpDescriptor( string name = null, string description = null, string type = null) :base(name, description, type) { } public HttpDescriptor<TClass> Action<TModel>( Expression<Func<TClass, Func<TModel, object>>> method, string description = null, string rel = null, string uri = null, Action<HttpMethodDescriptorContainer<TModel>> model = null) { var methodInfo = ExtractMemberInfoFromExpression<TModel>(method); var methodName = methodInfo.Name; var methodContainer = HydrateMethodDescriptionContainer<HttpMethodDescriptorContainer<TModel>, TModel>( methodName, description, Convert<HttpMethodDescriptorContainer<TModel>>(model)); methodContainer.Rel = methodContainer.Rel ?? rel ?? "n/a"; methodContainer.Uri = methodContainer.Uri ?? uri ?? "n/a"; Methods.Add(methodContainer); return this; } public new HttpDescriptor<TClass> SetDescription(string description) { base.SetDescription(description); return this; } public new HttpDescriptor<TClass> SetName(string name) { base.SetName(name); return this; } public new HttpDescriptor<TClass> SetType(string type) { base.SetType(type); return this; } } }
using System; using System.Linq.Expressions; using RimDev.Descriptor.Generic; namespace RimDev.Descriptor { public class HttpDescriptor<TClass> : Descriptor<TClass> where TClass : class, new() { public HttpDescriptor<TClass> Action<TModel>( Expression<Func<TClass, Func<TModel, object>>> method, string description = null, string rel = null, string uri = null, Action<HttpMethodDescriptorContainer<TModel>> model = null) { var methodInfo = ExtractMemberInfoFromExpression<TModel>(method); var methodName = methodInfo.Name; var methodContainer = HydrateMethodDescriptionContainer<HttpMethodDescriptorContainer<TModel>, TModel>( methodName, description, Convert<HttpMethodDescriptorContainer<TModel>>(model)); methodContainer.Rel = methodContainer.Rel ?? rel ?? "n/a"; methodContainer.Uri = methodContainer.Uri ?? uri ?? "n/a"; Methods.Add(methodContainer); return this; } } }
mit
C#
17d86538682af854d7f6c4b1edc4d54d69ae53f3
Update FSharpServiceFeatureOnOffOptions.cs
davkean/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,physhi/roslyn,agocke/roslyn,dotnet/roslyn,nguerrera/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,AmadeusW/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,gafter/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,dotnet/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,physhi/roslyn,davkean/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,AmadeusW/roslyn,reaction1989/roslyn,eriawan/roslyn,davkean/roslyn,panopticoncentral/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,abock/roslyn,wvdd007/roslyn,brettfo/roslyn,KevinRansom/roslyn,weltkante/roslyn,bartdesmet/roslyn,stephentoub/roslyn,abock/roslyn,nguerrera/roslyn,tmat/roslyn,tannergooding/roslyn,weltkante/roslyn,genlu/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,sharwell/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,brettfo/roslyn,heejaechang/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,agocke/roslyn,heejaechang/roslyn,sharwell/roslyn,mavasani/roslyn,gafter/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,tmat/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,aelij/roslyn,genlu/roslyn,mavasani/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,genlu/roslyn,agocke/roslyn,abock/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,nguerrera/roslyn,aelij/roslyn,wvdd007/roslyn,tannergooding/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,jmarolf/roslyn,stephentoub/roslyn,diryboy/roslyn,eriawan/roslyn,bartdesmet/roslyn,AmadeusW/roslyn
src/Tools/ExternalAccess/FSharp/Shared/Options/FSharpServiceFeatureOnOffOptions.cs
src/Tools/ExternalAccess/FSharp/Shared/Options/FSharpServiceFeatureOnOffOptions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Shared.Options { internal static class FSharpServiceFeatureOnOffOptions { /// <summary> /// this option is solely for performance. don't confused by option name. /// this option doesn't mean we will show all diagnostics that belong to opened files when turned off, /// rather it means we will only show diagnostics that are cheap to calculate for small scope such as opened files. /// </summary> public static PerLanguageOption<bool?> ClosedFileDiagnostic => Microsoft.CodeAnalysis.Shared.Options.ServiceFeatureOnOffOptions.ClosedFileDiagnostic; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Shared.Options { internal static class FSharpServiceFeatureOnOffOptions { /// <summary> /// this option is solely for performance. don't confused by option name. /// this option doesn't mean we will show all diagnostics that belong to opened files when turned off, /// rather it means we will only show diagnostics that are cheap to calculate for small scope such as opened files. /// </summary> public static PerLanguageOption<bool?> ClosedFileDiagnostic = Microsoft.CodeAnalysis.Shared.Options.ServiceFeatureOnOffOptions.ClosedFileDiagnostic; } }
mit
C#
054d17863604701910d74da26fef158086ca787a
Update SharedAssemblyInfo.cs
wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter
src/Shared/SharedAssemblyInfo.cs
src/Shared/SharedAssemblyInfo.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; [assembly: AssemblyCompany("Wiesław Šoltés")] [assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2010-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("0.3.2")] [assembly: AssemblyFileVersion("0.3.2")] [assembly: AssemblyInformationalVersion("0.3.2")]
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; [assembly: AssemblyCompany("Wiesław Šoltés")] [assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2010-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("0.3.1")] [assembly: AssemblyFileVersion("0.3.1")] [assembly: AssemblyInformationalVersion("0.3.1")]
mit
C#
be58c4a881c502cc2deb19376f9cebfa6fe82169
Fix to detect Mac OS X
CodeComb/Package,CodeComb/Package
src/CodeComb.Package/OS.cs
src/CodeComb.Package/OS.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Runtime.InteropServices; #if DNXCORE50 || DNX451 using Microsoft.Extensions.DependencyInjection; using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Runtime.Infrastructure; #endif namespace CodeComb.Package { public enum OSType { Windows, OSX, Linux } public static class OS { public static OSType Current { get { #if DNXCORE50 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return OSType.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return OSType.OSX; else return OSType.Linux; #elif DNX451 var services = CallContextServiceLocator.Locator.ServiceProvider; var env = services.GetService<IRuntimeEnvironment>(); if (env.OperatingSystem == "Windows") return OSType.Windows; else if (env.OperatingSystem == "Darwin") return OSType.OSX; else return OSType.Linux; #else if (Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE) return OSType.Windows; else if (Environment.OSVersion.Platform == PlatformID.MacOSX) return OSType.OSX; else return OSType.Linux; #endif } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Runtime.InteropServices; #if DNXCORE50 || DNX451 using Microsoft.Extensions.DependencyInjection; using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Runtime.Infrastructure; #endif namespace CodeComb.Package { public enum OSType { Windows, OSX, Linux } public static class OS { public static OSType Current { get { #if DNXCORE50 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return OSType.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return OSType.OSX; else return OSType.Linux; #elif DNX451 var services = CallContextServiceLocator.Locator.ServiceProvider; var env = services.GetService<IRuntimeEnvironment>(); if (env.OperatingSystem == "Windows") return OSType.Windows; else if (env.OperatingSystem == "Mac") return OSType.OSX; else return OSType.Linux; #else if (Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE) return OSType.Windows; else if (Environment.OSVersion.Platform == PlatformID.MacOSX) return OSType.OSX; else return OSType.Linux; #endif } } } }
apache-2.0
C#
9cce05ea7396879d52a6bad05186818dc7dadaa2
Update ai ranges
GameMakersUnion/JurassicCraft,GameMakersUnion/JurassicCraft,GameMakersUnion/JurassicCraft
Assets/EnemyAI.cs
Assets/EnemyAI.cs
using UnityEngine; using System.Collections; public class EnemyAI : MonoBehaviour { public GameObject enemies; public GameObject friends; private int targetUnit; // Use this for initialization void Start () { targetUnit = 0; } // Update is called once per frame void Update () { foreach (Transform enemy in enemies.transform) { Vector3 target = Vector3.zero; target = friends.transform.GetChild(targetUnit).position; enemy.GetComponent<Unit>().ChooseNewTarget(target); Debug.Log(enemy.name); } } }
using UnityEngine; using System.Collections; public class EnemyAI : MonoBehaviour { public GameObject enemies; public GameObject friends; // Use this for initialization void Start () { } // Update is called once per frame void Update () { foreach (Transform enemy in enemies.transform) { Vector3 target = Vector3.zero; target = friends.transform.GetChild(1).position; enemy.GetComponent<Unit>().ChooseNewTarget(target); Debug.Log(enemy.name); } } }
apache-2.0
C#
57fc25c385575d0ce790e9d11b44a4a9a08e70e1
change to minor version update instead of patch
cadon/ARKStatsExtractor
ARKBreedingStats/Properties/AssemblyInfo.cs
ARKBreedingStats/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; 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("ARK Smart Breeding")] [assembly: AssemblyDescription("Extracts stats of creatures of the game ARK: Survival Evolved, saves them in a library, suggests breeding pairs and shows them in a list or pedigree.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ARK Smart Breeding")] [assembly: AssemblyCopyright("Copyright © 2015 – 2019, made by cadon")] [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("991563ce-6b2c-40ae-bc80-a14f090a4d26")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("0.41.0.0")] [assembly: NeutralResourcesLanguage("en")]
using System.Reflection; using System.Resources; 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("ARK Smart Breeding")] [assembly: AssemblyDescription("Extracts stats of creatures of the game ARK: Survival Evolved, saves them in a library, suggests breeding pairs and shows them in a list or pedigree.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ARK Smart Breeding")] [assembly: AssemblyCopyright("Copyright © 2015 – 2019, made by cadon")] [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("991563ce-6b2c-40ae-bc80-a14f090a4d26")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("0.40.6.0")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
3dbb41d13e2fda9b8004c3473e072e5c8c8e9d63
Fix comments
quartz-software/kephas,quartz-software/kephas
src/Kephas.Core/Security/Authorization/RequiresPermissionAttribute.cs
src/Kephas.Core/Security/Authorization/RequiresPermissionAttribute.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RequiresPermissionAttribute.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the requires permission attribute class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Security.Authorization { using System; using Kephas.Diagnostics.Contracts; /// <summary> /// Attribute indicating the required permission to access/execute/use the decorated element. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = true, Inherited = false)] public class RequiresPermissionAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="RequiresPermissionAttribute"/> class. /// </summary> /// <param name="permissions">A variable-length parameters list containing the required permissions.</param> public RequiresPermissionAttribute(params string[] permissions) { Requires.NotNullOrEmpty(permissions, nameof(permissions)); this.Permissions = permissions; } /// <summary> /// Gets the required permissions. /// </summary> /// <value> /// The required permissions. /// </value> public string[] Permissions { get; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DemandPermissionAttribute.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the demand permission attribute class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Security.Authorization { using System; using Kephas.Diagnostics.Contracts; /// <summary> /// Attribute indicating the required permission to access/execute/use the decorated element. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = true, Inherited = false)] public class RequiresPermissionAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="RequiresPermissionAttribute"/> class. /// </summary> /// <param name="permissions">A variable-length parameters list containing the required permissions.</param> public RequiresPermissionAttribute(params string[] permissions) { Requires.NotNullOrEmpty(permissions, nameof(permissions)); this.Permissions = permissions; } /// <summary> /// Gets the required permissions. /// </summary> /// <value> /// The required permissions. /// </value> public string[] Permissions { get; } } }
mit
C#
09aefef415755dc457e476cb873325580740b95d
add Digest structure and ComputeDigest for computing hash code for a given buffer.
kingsamchen/EasyKeeper
VaultMarshal.cs
VaultMarshal.cs
/* @ Kingsley Chen */ using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; namespace EasyKeeper { public static class VaultMarshal { private class Digest { private readonly byte[] _data; public Digest(byte[] data) { _data = data; } public byte[] Data { get { return _data; } } } private const uint ProtoclVersion = 1U; public static void Marshal(string pwd, AccountStore store, Stream outStream) {} public static AccountStore Unmarshal(Stream inStream, string pwd) { return null; } private static byte[] AccountStoreToBytes(AccountStore store) { using (MemoryStream mem = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(mem, store); return mem.ToArray(); } } private static AccountStore AccountStoreFromBytes(byte[] rawBytes) { using (MemoryStream mem = new MemoryStream(rawBytes)) { IFormatter formatter = new BinaryFormatter(); var accountStore = formatter.Deserialize(mem) as AccountStore; return accountStore; } } private static Digest ComputeDigest(byte[] rawBytes) { using (SHA1 sha = new SHA1Managed()) { var hash = sha.ComputeHash(rawBytes); return new Digest(hash); } } } }
/* @ Kingsley Chen */ using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace EasyKeeper { public static class VaultMarshal { private const uint ProtoclVersion = 1U; public static void Marshal(string pwd, AccountStore store, Stream outStream) {} public static AccountStore Unmarshal(Stream inStream, string pwd) { return null; } private static byte[] AccountStoreToBytes(AccountStore store) { using (MemoryStream mem = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(mem, store); return mem.ToArray(); } } private static AccountStore AccountStoreFromBytes(byte[] rawBytes) { using (MemoryStream mem = new MemoryStream(rawBytes)) { IFormatter formatter = new BinaryFormatter(); var accountStore = formatter.Deserialize(mem) as AccountStore; return accountStore; } } } }
mit
C#
2508f241b323ac8ca6cdcac8734105f4ff671a21
Add AddStarToIssueAndCommentAsync
ats124/backlog4net
src/Backlog4net.Test/StarMethodsTest.cs
src/Backlog4net.Test/StarMethodsTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Backlog4net.Test { using Api; using Api.Option; using Backlog4net.Internal.Json; using Backlog4net.Internal.Json.Activities; using Conf; using Newtonsoft.Json; using TestConfig; [TestClass] public class StarMethodsTest { private static BacklogClient client; private static GeneralConfig generalConfig; private static string projectKey; private static long projectId; private static User ownUser; [ClassInitialize] public static async Task SetupClient(TestContext context) { generalConfig = GeneralConfig.Instance.Value; var conf = new BacklogJpConfigure(generalConfig.SpaceKey); conf.ApiKey = generalConfig.ApiKey; client = new BacklogClientFactory(conf).NewClient(); var users = await client.GetUsersAsync(); projectKey = generalConfig.ProjectKey; var project = await client.GetProjectAsync(projectKey); projectId = project.Id; ownUser = await client.GetMyselfAsync(); } [TestMethod] public async Task AddStarToIssueAndCommentAsync() { var issueTypes = await client.GetIssueTypesAsync(projectId); var issue = await client.CreateIssueAsync(new CreateIssueParams(projectId, "StarTestIssue", issueTypes.First().Id, IssuePriorityType.High)); await client.AddStarToIssueAsync(issue.Id); var issueComment = await client.AddIssueCommentAsync(new AddIssueCommentParams(issue.Id, "Comment")); await client.AddStarToCommentAsync(issueComment.Id); await client.DeleteIssueAsync(issue.Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Backlog4net.Test { using Api; using Api.Option; using Backlog4net.Internal.Json; using Backlog4net.Internal.Json.Activities; using Conf; using Newtonsoft.Json; using TestConfig; [TestClass] public class StarMethodsTest { private static BacklogClient client; private static GeneralConfig generalConfig; private static string projectKey; private static long projectId; private static User ownUser; [ClassInitialize] public static async Task SetupClient(TestContext context) { generalConfig = GeneralConfig.Instance.Value; var conf = new BacklogJpConfigure(generalConfig.SpaceKey); conf.ApiKey = generalConfig.ApiKey; client = new BacklogClientFactory(conf).NewClient(); var users = await client.GetUsersAsync(); projectKey = generalConfig.ProjectKey; var project = await client.GetProjectAsync(projectKey); projectId = project.Id; ownUser = await client.GetMyselfAsync(); } } }
mit
C#
b1d0409f9901b5da4f3e25bd50f82f6c9e55c91c
Clean up ModMonoCmd
murador/xsp,stormleoxia/xsp,murador/xsp,murador/xsp,stormleoxia/xsp,arthot/xsp,stormleoxia/xsp,arthot/xsp,murador/xsp,stormleoxia/xsp,arthot/xsp,arthot/xsp
src/Mono.WebServer.Apache/ModMonoCmd.cs
src/Mono.WebServer.Apache/ModMonoCmd.cs
// // Mono.WebServer.ModMonoCmd // // Authors: // Daniel Lopez Ridruejo // Gonzalo Paniagua Javier // // Copyright (c) 2002 Daniel Lopez Ridruejo. // (c) 2002,2003 Ximian, Inc. // All rights reserved. // (C) Copyright 2004-2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Mono.WebServer { enum ModMonoCmd { FIRST_COMMAND, SEND_FROM_MEMORY = 0, GET_SERVER_VARIABLES, SET_RESPONSE_HEADERS, GET_LOCAL_PORT, CLOSE, SHOULD_CLIENT_BLOCK, SETUP_CLIENT_BLOCK, GET_CLIENT_BLOCK, SET_STATUS, DECLINE_REQUEST, NOT_FOUND, IS_CONNECTED, SEND_FILE, SET_CONFIGURATION, LAST_COMMAND } }
// // Mono.WebServer.ModMonoCmd // // Authors: // Daniel Lopez Ridruejo // Gonzalo Paniagua Javier // // Copyright (c) 2002 Daniel Lopez Ridruejo. // (c) 2002,2003 Ximian, Inc. // All rights reserved. // (C) Copyright 2004-2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Mono.WebServer { enum ModMonoCmd { FIRST_COMMAND, SEND_FROM_MEMORY = 0, GET_SERVER_VARIABLES, SET_RESPONSE_HEADERS, GET_LOCAL_PORT, CLOSE, SHOULD_CLIENT_BLOCK, SETUP_CLIENT_BLOCK, GET_CLIENT_BLOCK, SET_STATUS, DECLINE_REQUEST, NOT_FOUND, IS_CONNECTED, SEND_FILE, SET_CONFIGURATION, LAST_COMMAND } }
mit
C#
284dd8f365a350a00dfd304ab756f285cb4261a6
Simplify filter.
zacbrown/hiddentreasure-etw-demo
hiddentreasure-etw-demo/PowerShellMethodExecution.cs
hiddentreasure-etw-demo/PowerShellMethodExecution.cs
// Copyright (c) Zac Brown. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class PowerShellMethodExecution { public static void Run() { // For a more thorough example of how to implement this detection, // have a look at https://github.com/zacbrown/PowerShellMethodAuditor var filter = new EventFilter(Filter .EventIdIs(7937) .And(UnicodeString.Contains("Payload", "Started")) .And(UnicodeString.Contains("ContextInfo", "Command Type = Function"))); filter.OnEvent += (IEventRecord r) => { var method = r.GetUnicodeString("ContextInfo"); Console.WriteLine($"Method executed:\n{method}"); }; var provider = new Provider("Microsoft-Windows-PowerShell"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); // Setup Ctrl-C to call trace.Stop(); Helpers.SetupCtrlC(trace); // This call is blocking. The thread that calls UserTrace.Start() // is donating itself to the ETW subsystem to pump events off // of the buffer. trace.Start(); } } }
// Copyright (c) Zac Brown. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class PowerShellMethodExecution { public static void Run() { // For a more thorough example of how to implement this detection, // have a look at https://github.com/zacbrown/PowerShellMethodAuditor var filter = new EventFilter(Filter .EventIdIs(7937) .And(UnicodeString.Contains("Payload", "Started")) .And(UnicodeString.Contains("ContextInfo", "Command Type = Function")) .And(UnicodeString.Contains("ContextInfo", "Command Name = prompt").op_LogicalNot()) .And(UnicodeString.Contains("ContextInfo", "Command Name = PSConsoleHostReadline").op_LogicalNot())); filter.OnEvent += (IEventRecord r) => { var method = r.GetUnicodeString("ContextInfo"); Console.WriteLine($"Method executed:\n{method}"); }; var provider = new Provider("Microsoft-Windows-PowerShell"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); // Setup Ctrl-C to call trace.Stop(); Helpers.SetupCtrlC(trace); // This call is blocking. The thread that calls UserTrace.Start() // is donating itself to the ETW subsystem to pump events off // of the buffer. trace.Start(); } } }
mit
C#
3e7a2363d520c7f0c10c8a7be2c8845a3c1b36b6
Fix one parameter in the EthernetDevice.cs functions
shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg
trunk/src/bindings/EthernetDevice.cs
trunk/src/bindings/EthernetDevice.cs
using System; using System.Runtime.InteropServices; namespace TAPCfg { public class EthernetDevice : IDisposable { private const int MTU = 1522; private IntPtr handle; public EthernetDevice() { handle = tapcfg_init(); } public void Start() { tapcfg_start(handle); } public byte[] Read() { int length; byte[] buffer = new byte[MTU]; length = tapcfg_read(handle, buffer, buffer.Length); byte[] outbuf = new byte[length]; Array.Copy(buffer, 0, outbuf, 0, length); return outbuf; } public void Write(byte[] data) { byte[] buffer = new byte[MTU]; Array.Copy(data, 0, buffer, 0, data.Length); int ret = tapcfg_write(handle, buffer, data.Length); } public void Enabled(bool enabled) { if (enabled) tapcfg_iface_change_status(handle, 1); else tapcfg_iface_change_status(handle, 0); } public void Dispose() { this.Dispose(true); } protected virtual void Dispose(bool fromDisposeMethod) { tapcfg_stop(handle); tapcfg_destroy(handle); if (fromDisposeMethod) { GC.SuppressFinalize(this); } } private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start(); dev.Enabled(true); System.Threading.Thread.Sleep(100000); } [DllImport("libtapcfg")] private static extern IntPtr tapcfg_init(); [DllImport("libtapcfg")] private static extern void tapcfg_destroy(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_start(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern void tapcfg_stop(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_has_data(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_read(IntPtr tapcfg, byte[] buf, int count); [DllImport("libtapcfg")] private static extern int tapcfg_write(IntPtr tapcfg, byte[] buf, int count); [DllImport("libtapcfg")] private static extern string tapcfg_get_ifname(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_iface_get_status(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_iface_change_status(IntPtr tapcfg, int enabled); [DllImport("libtapcfg")] private static extern int tapcfg_iface_set_ipv4(IntPtr tapcfg, string addr, Uint8 netbits); [DllImport("libtapcfg")] private static extern int tapcfg_iface_set_ipv6(IntPtr tapcfg, string addr, Uint8 netbits); } }
using System; using System.Runtime.InteropServices; namespace TAPCfg { public class EthernetDevice : IDisposable { private const int MTU = 1522; private IntPtr handle; public EthernetDevice() { handle = tapcfg_init(); } public void Start() { tapcfg_start(handle); } public byte[] Read() { int length; byte[] buffer = new byte[MTU]; length = tapcfg_read(handle, buffer, buffer.Length); byte[] outbuf = new byte[length]; Array.Copy(buffer, 0, outbuf, 0, length); return outbuf; } public void Write(byte[] data) { byte[] buffer = new byte[MTU]; Array.Copy(data, 0, buffer, 0, data.Length); int ret = tapcfg_write(handle, buffer, data.Length); } public void Enabled(bool enabled) { if (enabled) tapcfg_iface_change_status(handle, 1); else tapcfg_iface_change_status(handle, 0); } public void Dispose() { this.Dispose(true); } protected virtual void Dispose(bool fromDisposeMethod) { tapcfg_stop(handle); tapcfg_destroy(handle); if (fromDisposeMethod) { GC.SuppressFinalize(this); } } private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start(); dev.Enabled(true); System.Threading.Thread.Sleep(100000); } [DllImport("libtapcfg")] private static extern IntPtr tapcfg_init(); [DllImport("libtapcfg")] private static extern void tapcfg_destroy(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_start(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern void tapcfg_stop(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_has_data(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_read(IntPtr tapcfg, byte[] buf, int count); [DllImport("libtapcfg")] private static extern int tapcfg_write(IntPtr tapcfg, byte[] buf, int count); [DllImport("libtapcfg")] private static extern string tapcfg_get_ifname(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_iface_get_status(IntPtr tapcfg); [DllImport("libtapcfg")] private static extern int tapcfg_iface_change_status(IntPtr tapcfg, int enabled); [DllImport("libtapcfg")] private static extern int tapcfg_iface_set_ipv4(IntPtr tapcfg, string addr, byte[] netbits); [DllImport("libtapcfg")] private static extern int tapcfg_iface_set_ipv6(IntPtr tapcfg, string addr, byte[] netbits); } }
lgpl-2.1
C#
4a67b885a84cf58e2aad601ffbb53b9febc6b0f1
fix badge center icon links
ucdavis/Badges,ucdavis/Badges
Badges/Views/Badge/Index.cshtml
Badges/Views/Badge/Index.cshtml
@model dynamic @{ ViewBag.Title = "Badge Center"; } <h2>Badge center</h2> <ul class="nav menu row"> <li class="col-md-4"><a href="/Badge/Create"><i class="icon-beaker icon-3x"></i>@Html.ActionLink("Design a badge", "Create")</a></li> <li class="col-md-4"><a href="/Badge/Browse"><i class="icon-star icon-3x"></i>@Html.ActionLink("Earn a badge", "Browse")</a></li> <li class="col-md-4"><a href="/Badge/MyBadges"><i class="icon-trophy icon-3x"></i>@Html.ActionLink("My badges", "MyBadges")</a></li> </ul>
@model dynamic @{ ViewBag.Title = "Badge Center"; } <h2>Badge center</h2> <ul class="nav menu row"> <li class="col-md-4"><a href="Create"><i class="icon-beaker icon-3x"></i>@Html.ActionLink("Design a badge", "Create")</a></li> <li class="col-md-4"><a href="Browse"><i class="icon-star icon-3x"></i>@Html.ActionLink("Earn a badge", "Browse")</a></li> <li class="col-md-4"><a href="MyBadges"><i class="icon-trophy icon-3x"></i>@Html.ActionLink("My badges", "MyBadges")</a></li> </ul>
mpl-2.0
C#
ac78bcffef6651b9ca03b5b3c4ea5c2ef77321e7
Fix build warning in SharedLibrary.cs
cshung/clrmd,cshung/clrmd,Microsoft/clrmd,Microsoft/clrmd
src/TestTargets/Shared/SharedLibrary.cs
src/TestTargets/Shared/SharedLibrary.cs
using System; #pragma warning disable CS0169 #pragma warning disable 0414 public class Foo { int i = 42; string s = "string"; bool b = true; float f = 4.2f; double d = 8.4; object o = new object(); Struct st = new Struct(); public string FooString = "Foo string"; public void Bar() { } public void Baz() { } public int Baz(int i) { return i; } public T5 GenericBar<T1, T2, T3, T4, T5>(GenericClass<T1, T2, T3, T4, T5> a) { return a.Invoke(default(T1), default(T2), default(T3), default(T4)); } } public struct Struct { int j; } public class GenericClass<T1, T2, T3, T4, T5> { public T5 Invoke(T1 a, T2 b, T3 te, T4 t4) { return default(T5); } }
using System; #pragma warning disable 0414 public class Foo { int i = 42; string s = "string"; bool b = true; float f = 4.2f; double d = 8.4; object o = new object(); Struct st = new Struct(); public string FooString = "Foo string"; public void Bar() { } public void Baz() { } public int Baz(int i) { return i; } public T5 GenericBar<T1, T2, T3, T4, T5>(GenericClass<T1, T2, T3, T4, T5> a) { return a.Invoke(default(T1), default(T2), default(T3), default(T4)); } } public struct Struct { int j; } public class GenericClass<T1, T2, T3, T4, T5> { public T5 Invoke(T1 a, T2 b, T3 te, T4 t4) { return default(T5); } }
mit
C#
7e242bd18c361607a44ec307165820d39687761c
Add help output
jennings/DbfCmd
DbfCmd/Program.cs
DbfCmd/Program.cs
//------------------------------------------------------------------------------------ // <copyright file="Program.cs" company="The DbfCmd Project"> // Copyright 2011 Various Contributors. Licensed under the Apache License, Version 2.0. // </copyright> //------------------------------------------------------------------------------------ namespace DbfCmd { using System; using System.Collections.Generic; using System.Data.Odbc; using System.Data.OleDb; using System.IO; using System.Text; public class Program { public static void Main(string[] args) { if (args.Length < 2) { Program.DisplayHelp(); Environment.Exit(0); } var arguments = ArgumentParser.Parse(args); var runner = new QueryRunner(arguments.Directory, arguments.OutputCsv, arguments.OutputHeaders); string result = runner.Run(arguments.Query); Console.WriteLine(result); } private static void DisplayHelp() { Console.WriteLine("Usage: dbfcmd.exe [options] <path> <query>"); Console.WriteLine(""); Console.WriteLine("Options:"); Console.WriteLine(" -c Output as CSV"); Console.WriteLine(" -n Do not output headers"); } } }
//------------------------------------------------------------------------------------ // <copyright file="Program.cs" company="The DbfCmd Project"> // Copyright 2011 Various Contributors. Licensed under the Apache License, Version 2.0. // </copyright> //------------------------------------------------------------------------------------ namespace DbfCmd { using System; using System.Collections.Generic; using System.Data.Odbc; using System.Data.OleDb; using System.IO; using System.Text; public class Program { public static void Main(string[] args) { if (args.Length < 2) { Program.DisplayHelp(); Environment.Exit(0); } var arguments = ArgumentParser.Parse(args); var runner = new QueryRunner(arguments.Directory, arguments.OutputCsv, arguments.OutputHeaders); string result = runner.Run(arguments.Query); Console.WriteLine(result); } private static void DisplayHelp() { } } }
apache-2.0
C#
c13ccab64912639d4261afe7a2f015b593533533
Update Languages.cs
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Client/Localization/Base/Languages.cs
Client/Localization/Base/Languages.cs
namespace LunaClient.Localization { public enum Languages { English, Russian, German } }
namespace LunaClient.Localization { public enum Languages { English, Russian } }
mit
C#
d1eede448bcfda3335c18fbaf2a1ae3ad5a3bb22
Fix "Popup" action "Text", "Title" default values
danielchalmers/DesktopWidgets
DesktopWidgets/Actions/PopupAction.cs
DesktopWidgets/Actions/PopupAction.cs
using System.ComponentModel; using System.Windows; namespace DesktopWidgets.Actions { internal class PopupAction : ActionBase { [DisplayName("Text")] public string Text { get; set; } = ""; [DisplayName("Title")] public string Title { get; set; } = ""; [DisplayName("Image")] public MessageBoxImage Image { get; set; } public override void ExecuteAction() { base.ExecuteAction(); MessageBox.Show(Text, Title, MessageBoxButton.OK, Image); } } }
using System.ComponentModel; using System.Windows; namespace DesktopWidgets.Actions { internal class PopupAction : ActionBase { [DisplayName("Text")] public string Text { get; set; } [DisplayName("Title")] public string Title { get; set; } [DisplayName("Image")] public MessageBoxImage Image { get; set; } public override void ExecuteAction() { base.ExecuteAction(); MessageBox.Show(Text, Title, MessageBoxButton.OK, Image); } } }
apache-2.0
C#
4f6a3a25bc4436d79a3d1b1bbc0d8ce576029d17
Remove redundant modifiers on ReverseComparer
fsateler/MoreLINQ,morelinq/MoreLINQ,fsateler/MoreLINQ,ddpruitt/morelinq,morelinq/MoreLINQ,ddpruitt/morelinq
MoreLinq/ReverseComparer.cs
MoreLinq/ReverseComparer.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2016 Felipe Sateler. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System.Collections.Generic; /// <summary> /// A <see cref="IComparer{T}"/> that compares in reverse order than the specified <see cref="IComparer{T}"/> /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> class ReverseComparer<T> : IComparer<T> { readonly IComparer<T> _underlying; public ReverseComparer(IComparer<T> underlying) { if (underlying == null) underlying = Comparer<T>.Default; _underlying = underlying; } public int Compare(T x, T y) { int res = _underlying.Compare(x, y); if (res > 0) { return -1; } else if (res < 0) { return 1; } else { return 0; } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2016 Felipe Sateler. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// A <see cref="IComparer{T}"/> that compares in reverse order than the specified <see cref="IComparer{T}"/> /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> internal class ReverseComparer<T> : IComparer<T> { private readonly IComparer<T> _underlying; public ReverseComparer(IComparer<T> underlying) { if (underlying == null) underlying = Comparer<T>.Default; _underlying = underlying; } public int Compare(T x, T y) { int res = _underlying.Compare(x, y); if (res > 0) { return -1; } else if (res < 0) { return 1; } else { return 0; } } } }
apache-2.0
C#
c5b10b05976365d942740470912f94ce7c7019ac
Remove unnecessary comments
fredatgithub/WinFormTemplate
WinFormTemplate/FormMain.cs
WinFormTemplate/FormMain.cs
using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using WinFormTemplate.Properties; namespace WinFormTemplate { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void QuitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBoxApplication aboutBoxApplication = new AboutBoxApplication(); aboutBoxApplication.ShowDialog(); } private void DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); Text += string.Format(" V{0}.{1}.{2}.{3}", fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart); } private void FormMain_Load(object sender, EventArgs e) { DisplayTitle(); GetWindowValue(); } private void GetWindowValue() { Width = Settings.Default.WindowWidth; Height = Settings.Default.WindowHeight; Top = Settings.Default.WindowTop < 0 ? 0 : Settings.Default.WindowTop; Left = Settings.Default.WindowLeft < 0 ? 0 : Settings.Default.WindowLeft; } private void SaveWindowValue() { Settings.Default.WindowHeight = Height; Settings.Default.WindowWidth = Width; Settings.Default.WindowLeft = Left; Settings.Default.WindowTop = Top; Settings.Default.Save(); } private void FormMainFormClosing(object sender, FormClosingEventArgs e) { SaveWindowValue(); } } }
using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using WinFormTemplate.Properties; namespace WinFormTemplate { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void QuitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBoxApplication aboutBoxApplication = new AboutBoxApplication(); aboutBoxApplication.ShowDialog(); } private void DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); Text += string.Format(" V{0}.{1}.{2}.{3}", fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart); } private void FormMain_Load(object sender, EventArgs e) { DisplayTitle(); GetWindowValue(); } private void GetWindowValue() { // Set this if you want a minimum width //Width = Settings.Default.WindowWidth < 395 ? 395 : Settings.Default.WindowWidth; Width = Settings.Default.WindowWidth; // Set this if you want a minimum Height // Height = Settings.Default.WindowHeight < 180 ? 180 : Settings.Default.WindowHeight; Height = Settings.Default.WindowHeight; Top = Settings.Default.WindowTop < 0 ? 0 : Settings.Default.WindowTop; Left = Settings.Default.WindowLeft < 0 ? 0 : Settings.Default.WindowLeft; } private void SaveWindowValue() { Settings.Default.WindowHeight = Height; Settings.Default.WindowWidth = Width; Settings.Default.WindowLeft = Left; Settings.Default.WindowTop = Top; Settings.Default.Save(); } private void FormMainFormClosing(object sender, FormClosingEventArgs e) { SaveWindowValue(); } } }
mit
C#
ccf9771a0664d1cc7f379e40bad924a77dab4989
Remove MIT license header
fredatgithub/WinFormTemplate
WinFormTemplate/Language.cs
WinFormTemplate/Language.cs
namespace WinFormTemplate { public enum Language { French, English } }
/* The MIT License(MIT) Copyright(c) 2015 Freddy Juhel 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. */ namespace WinFormTemplate { public enum Language { French, English } }
mit
C#
ed2e876236242fafb15accdd8642400eb9cde63c
fix property accessibility
depp/morning-ritual
MorningRitual/Assets/Scripts/GameManager.cs
MorningRitual/Assets/Scripts/GameManager.cs
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { private static GameManager instanceValue; public GameObject initialRoom; /// <summary> /// Get the global GameManager instance. /// </summary> public static GameManager Instance { get { if (!instanceValue) { var objs = FindObjectsOfType<GameManager>(); Debug.Assert(objs.Length == 1); instanceValue = objs[0]; } return instanceValue; } } public delegate void Action(); public event Action ScoreDidChange; private int scoreValue; public int Score { get { return this.scoreValue; } private set { if (value != this.scoreValue) { this.scoreValue = value; this.ScoreDidChange.Invoke(); } } } // Use this for initialization void Start () { this.Score = 0; } // Update is called once per frame void Update () { } void OnDestroy() { if (this == instanceValue) { instanceValue = null; } } }
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { private static GameManager instanceValue; public GameObject initialRoom; /// <summary> /// Get the global GameManager instance. /// </summary> public static GameManager Instance { get { if (!instanceValue) { var objs = FindObjectsOfType<GameManager>(); Debug.Assert(objs.Length == 1); instanceValue = objs[0]; } return instanceValue; } } public delegate void Action(); public event Action ScoreDidChange; private int scoreValue; public int Score { get { return this.scoreValue; } set { if (value != this.scoreValue) { this.scoreValue = value; this.ScoreDidChange.Invoke(); } } } // Use this for initialization void Start () { this.Score = 0; } // Update is called once per frame void Update () { } void OnDestroy() { if (this == instanceValue) { instanceValue = null; } } }
mit
C#
70927007c5c7c96856caa5b1b093b8894d0f886e
Remove unused 'using' on InternalErrorException.cs
nieltg/ReadSharp.Core
NReadability.Core/InternalErrorException.cs
NReadability.Core/InternalErrorException.cs
/* * NReadability * http://code.google.com/p/nreadability/ * * Copyright 2010 Marek Stój * http://immortal.pl/ * * 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 ReadSharp.Ports.NReadability { /// <summary> /// An exception that is thrown when an internal error occurrs in the application. /// Internal error in the application means that there is a bug in the application. /// </summary> public class InternalErrorException : Exception { #region Constructor(s) /// <summary> /// Initializes a new instance of the InternalErrorException class with a specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public InternalErrorException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the InternalErrorException class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public InternalErrorException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the InternalErrorException class. /// </summary> public InternalErrorException() { } #endregion } }
/* * NReadability * http://code.google.com/p/nreadability/ * * Copyright 2010 Marek Stój * http://immortal.pl/ * * 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.Runtime.Serialization; namespace ReadSharp.Ports.NReadability { /// <summary> /// An exception that is thrown when an internal error occurrs in the application. /// Internal error in the application means that there is a bug in the application. /// </summary> public class InternalErrorException : Exception { #region Constructor(s) /// <summary> /// Initializes a new instance of the InternalErrorException class with a specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public InternalErrorException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the InternalErrorException class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public InternalErrorException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the InternalErrorException class. /// </summary> public InternalErrorException() { } #endregion } }
mit
C#