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
9ba17b4a0e2f20ee491e40f4ed32124af2d527a6
Create ProductShipping.cs
daniela1991/hack4europecontest
ProductShipping.cs
ProductShipping.cs
using System; namespace Cdiscount.OpenApi.ProxyClient.Contract.Common { /// <summary> /// Product shipping information /// </summary> public class ProductShipping { /// <summary> /// Shipping carrier name /// </summary> public string Name { get; set; } /// <summary> /// Shipping delay to display /// </summary> public string DelayToDisplay { get; set; } /// <summary> /// Shipping price (in euros) /// </summary> public decimal Price { get; set; } /// <summary> /// Maximum delivery date /// </summary> public DateTime MaxDeliveryDate { get; set; } /// <summary> /// Minimum delivery date /// </summary> public DateTime MinDeliveryDate { get; set; } } }
mit
C#
75083967298e41fe876621ef4c527dca50500d30
Add missing file to repository
nunit/nunit-console,nunit/nunit-console,nunit/nunit-console
NUnitConsole/src/nunit.engine/Services/InternalTraceService.cs
NUnitConsole/src/nunit.engine/Services/InternalTraceService.cs
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Text; using NUnit.Engine.Internal; namespace NUnit.Engine.Services { public interface ITraceService : IService { Logger GetLogger(string name); void Log(InternalTraceLevel level, string message, string category); void Log(InternalTraceLevel level, string message, string category, Exception ex); } public class InternalTraceService : ITraceService { private readonly static string TIME_FMT = "HH:mm:ss.fff"; private static bool initialized; private InternalTraceWriter writer; public InternalTraceLevel Level; public InternalTraceService(InternalTraceLevel level) { this.Level = level; } public void Initialize(string logName, InternalTraceLevel level) { if (!initialized) { Level = level; if (writer == null && Level > InternalTraceLevel.Off) { writer = new InternalTraceWriter(logName); writer.WriteLine("InternalTrace: Initializing at level " + Level.ToString()); } initialized = true; } } public Logger GetLogger(string name) { return new Logger(this, name); } public Logger GetLogger(Type type) { return new Logger(this, type.FullName); } public void Log(InternalTraceLevel level, string message, string category) { Log(level, message, category, null); } public void Log(InternalTraceLevel level, string message, string category, Exception ex) { if (writer != null) { writer.WriteLine("{0} {1,-5} [{2,2}] {3}: {4}", DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), System.Threading.Thread.CurrentThread.ManagedThreadId, category, message); if (ex != null) writer.WriteLine(ex.ToString()); } } #region IService Members private ServiceContext services; public ServiceContext ServiceContext { get { return services; } set { services = value; } } public void InitializeService() { } public void UnloadService() { } #endregion } }
mit
C#
3ae280fdb102eba587050a753f64d531232f1031
Define System.IO.StreamWriter
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
stdlib/system-io/StreamWriter.cs
stdlib/system-io/StreamWriter.cs
using System.Text; namespace System.IO { public class StreamWriter : TextWriter { public StreamWriter(Stream stream) : this(stream, Encoding.UTF8) { } public StreamWriter(Stream stream, Encoding encoding) { this.BaseStream = stream; this.codec = encoding; this.encoder = encoding.GetEncoder(); } private Encoding codec; private Encoder encoder; /// <inheritdoc/> public override Encoding Encoding => codec; /// <summary> /// Gets the backing stream for this text writer. /// </summary> /// <returns>The backing stream.</returns> public Stream BaseStream { get; private set; } /// <inheritdoc/> public override void Write(char value) { Write(new char[] { value }, 0, 1); } /// <inheritdoc/> public override void Write(char[] buffer, int index, int count) { int numOfBytes = encoder.GetByteCount(buffer, index, count, false); var bytes = new byte[numOfBytes]; numOfBytes = encoder.GetBytes(buffer, index, count, bytes, 0, false); BaseStream.Write(bytes, 0, numOfBytes); } /// <inheritdoc/> protected override void Dispose(bool disposing) { BaseStream.Dispose(); } /// <inheritdoc/> public override void Flush() { BaseStream.Flush(); } } }
mit
C#
62e02403975c538305adce7a59d8296ce7157573
Create Variable.cs
irtezasyed007/CSC523-Game-Project
Algorithms/Variable.cs
Algorithms/Variable.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSC_523_Game { class Variable { private char var; private bool truthValue; public Variable(char c) { var = c; this.truthValue = true; } public void setValue(bool truthValue) { this.truthValue = truthValue; } public bool getTruthValue() { return this.truthValue; } public char getVariable() { return this.var; } public void setAsComplement() { this.truthValue = !this.truthValue; } } }
mit
C#
c7320b264e116ff54f0bdaa5299d6b27305f9305
Add Batch class
goshippo/shippo-csharp-client
Shippo/Batch.cs
Shippo/Batch.cs
using System; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Batch : ShippoId { [JsonProperty (PropertyName = "object_status")] public object ObjectStatus { get; set; } [JsonProperty (PropertyName = "object_created")] public object ObjectCreated { get; set; } [JsonProperty (PropertyName = "object_updated")] public object ObjectUpdated { get; set; } [JsonProperty (PropertyName = "object_owner")] public object ObjectOwner { get; set; } [JsonProperty (PropertyName = "default_carrier_account")] public object DefaultCarrierAccount { get; set; } [JsonProperty (PropertyName = "default_servicelevel_token")] public object DefaultServicelevelToken { get; set; } [JsonProperty (PropertyName = "label_filetype")] public object LabelFiletype { get; set; } [JsonProperty (PropertyName = "metadata")] public object Metadata { get; set; } [JsonProperty (PropertyName = "batch_shipments")] public object BatchShipments { get; set; } [JsonProperty (PropertyName = "label_url")] public object LabelUrl { get; set; } [JsonProperty (PropertyName = "object_results")] public object ObjectResults { get; set; } } }
apache-2.0
C#
af62c107b126e1c82457af08f601246382b5343d
Add ignored BackupSchedule file.
Watts-Energy/Watts.Azure
Watts.Azure.Common/Backup/BackupSchedule.cs
Watts.Azure.Common/Backup/BackupSchedule.cs
namespace Watts.Azure.Common.Backup { using System; public class BackupSchedule { /// <summary> /// The frequency with which to switch the table target. /// </summary> public TimeSpan SwitchTargetStorageFrequency { get; set; } /// <summary> /// The frequency with which to perform incremental backups to the current target. /// </summary> public TimeSpan IncrementalLoadFrequency { get; set; } /// <summary> /// The time to keep the backup. /// </summary> public TimeSpan RetentionTimeSpan { get; set; } } }
mit
C#
160718e333143b7b199162ba45b9ba254fc5b91c
Add HighResolutionTimer
unosquare/swan
src/Unosquare.Swan/Components/HighResolutionTimer.cs
src/Unosquare.Swan/Components/HighResolutionTimer.cs
namespace Unosquare.Swan.Components { using System; using System.Diagnostics; /// <summary> /// Provides access to a high-resolution, time measuring device. /// </summary> /// <seealso cref="Stopwatch" /> public class HighResolutionTimer : Stopwatch { /// <summary> /// Initializes a new instance of the <see cref="HighResolutionTimer"/> class. /// </summary> /// <exception cref="NotSupportedException">High-resolution timer not available.</exception> public HighResolutionTimer() { if (!IsHighResolution) throw new NotSupportedException("High-resolution timer not available"); } /// <summary> /// Gets the number of microseconds per timer tick. /// </summary> public static double MicrosecondsPerTick { get; } = 1000000d / Frequency; /// <summary> /// Gets the elapsed microseconds. /// </summary> public long ElapsedMicroseconds => (long)(ElapsedTicks * MicrosecondsPerTick); } }
mit
C#
e1f9e3807ff6cc13b144af94e949617f5ed2a09e
Add DebuggerDisplay attr to Local
Arthur2e5/dnlib,modulexcite/dnlib,ZixiangBoy/dnlib,yck1509/dnlib,0xd4d/dnlib,picrap/dnlib,kiootic/dnlib,ilkerhalil/dnlib,jorik041/dnlib
src/DotNet/Emit/Local.cs
src/DotNet/Emit/Local.cs
using System.Diagnostics; namespace dot10.DotNet.Emit { /// <summary> /// A method local /// </summary> [DebuggerDisplay("{typeSig}")] public sealed class Local { ITypeSig typeSig; /// <summary> /// Gets/sets the type of the local /// </summary> public ITypeSig Type { get { return typeSig; } set { typeSig = value; } } /// <summary> /// Constructor /// </summary> /// <param name="typeSig">The type</param> public Local(ITypeSig typeSig) { this.typeSig = typeSig; } } }
namespace dot10.DotNet.Emit { /// <summary> /// A method local /// </summary> public sealed class Local { ITypeSig typeSig; /// <summary> /// Gets/sets the type of the local /// </summary> public ITypeSig Type { get { return typeSig; } set { typeSig = value; } } /// <summary> /// Constructor /// </summary> /// <param name="typeSig">The type</param> public Local(ITypeSig typeSig) { this.typeSig = typeSig; } } }
mit
C#
c1977b650b56b5ed8c9b5c5dc9d7013b8da47747
Add utility class (mapped from Java SDK)
stoiveyp/alexa-skills-dotnet,timheuer/alexa-skills-dotnet
Alexa.NET/Request/SkillRequestUtility.cs
Alexa.NET/Request/SkillRequestUtility.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Alexa.NET.Request.Type; namespace Alexa.NET.Request { public static class SkillRequestUtility { public static string GetIntentName(this SkillRequest request) { return request.Request is IntentRequest intentRequest ? intentRequest.Intent.Name : string.Empty; } public static string GetAccountLinkAccessToken(this SkillRequest request) { return request?.Context?.System?.User?.AccessToken; } public static string GetApiAccessToken(this SkillRequest request) { return request?.Context?.System?.ApiAccessToken; } public static string GetDeviceId(this SkillRequest request) { return request?.Context?.System?.Device?.DeviceID; } public static string GetDialogState(this SkillRequest request) { return request.Request is IntentRequest intentRequest ? intentRequest.DialogState : string.Empty; } public static Slot GetSlot(this SkillRequest request, string slotName) { return request.Request is IntentRequest intentRequest && intentRequest.Intent.Slots.ContainsKey(slotName) ? intentRequest.Intent.Slots[slotName] : null; } public static string GetSlotValue(this SkillRequest request, string slotName) { return GetSlot(request, slotName)?.Value; } public static Dictionary<string,object> GetSupportedInterfaces(this SkillRequest request) { return request?.Context?.System?.Device?.SupportedInterfaces; } public static bool? IsNewSession(this SkillRequest request) { return request?.Session?.New; } public static string GetUserId(this SkillRequest request) { return request?.Session?.User?.UserId; } } }
mit
C#
4aaec4ad61bbbfe56d18cd01269b5cf88df56e4b
update parse proxy with async methods
jobeland/DistributedNetworkTrainingStorage
StorageAPI/StorageAPI/Proxies/Parse/ParseProxy.cs
StorageAPI/StorageAPI/Proxies/Parse/ParseProxy.cs
using System.Collections.Generic; using System.Threading.Tasks; using ArtificialNeuralNetwork; using ArtificialNeuralNetwork.Factories; using ArtificialNeuralNetwork.Genes; using NeuralNetwork.GeneticAlgorithm; using Newtonsoft.Json; using Parse; namespace StorageAPI.Proxies.Parse { public class ParseProxy : IStorageProxy { private readonly string _networkVersion; public ParseProxy(string networkVersion, string appId, string dotNetKey) { _networkVersion = networkVersion; ParseClient.Initialize(appId, dotNetKey); } public async Task<ITrainingSession> GetBestSessionAsync() { var result = await ParseCloud.CallFunctionAsync<ParseObject>("bestNetwork", new Dictionary<string, object> { { "networkVersion", _networkVersion } }); var networkGenes = JsonConvert.DeserializeObject<NeuralNetworkGene>((string)result["jsonNetwork"]); var network = NeuralNetworkFactory.GetInstance().Create(networkGenes); var session = new FakeTrainingSession(network, (double)result["eval"]); return session; } public void StoreNetwork(INeuralNetwork network, double eval) { var networkParseFormat = new ParseObject(_networkVersion); networkParseFormat["jsonNetwork"] = JsonConvert.SerializeObject(network.GetGenes()); networkParseFormat["eval"] = eval; networkParseFormat.SaveAsync().Wait(); } public async Task StoreNetworkAsync(INeuralNetwork network, double eval) { var networkParseFormat = new ParseObject(_networkVersion); networkParseFormat["jsonNetwork"] = JsonConvert.SerializeObject(network.GetGenes()); networkParseFormat["eval"] = eval; await networkParseFormat.SaveAsync(); } public ITrainingSession GetBestSession() { var task = ParseCloud.CallFunctionAsync<ParseObject>("bestNetwork", new Dictionary<string, object> { { "networkVersion", _networkVersion } }); task.Wait(); var result = task.Result; var networkGenes = JsonConvert.DeserializeObject<NeuralNetworkGene>((string)result["jsonNetwork"]); var network = NeuralNetworkFactory.GetInstance().Create(networkGenes); var session = new FakeTrainingSession(network, (double)result["eval"]); return session; } } }
mit
C#
11e8868cd9f9b41c2fa8b1d36b1f124adb5c4ba6
Tweak TryGetHeaderName test
krytarowski/corefx,wtgodbe/corefx,rahku/corefx,richlander/corefx,wtgodbe/corefx,weltkante/corefx,ravimeda/corefx,benpye/corefx,nbarbettini/corefx,cydhaselton/corefx,alphonsekurian/corefx,stephenmichaelf/corefx,the-dwyer/corefx,Petermarcu/corefx,rubo/corefx,shimingsg/corefx,mmitche/corefx,nbarbettini/corefx,zhenlan/corefx,jhendrixMSFT/corefx,gkhanna79/corefx,benpye/corefx,alphonsekurian/corefx,JosephTremoulet/corefx,kkurni/corefx,axelheer/corefx,Petermarcu/corefx,dsplaisted/corefx,cartermp/corefx,ViktorHofer/corefx,mmitche/corefx,shahid-pk/corefx,elijah6/corefx,khdang/corefx,iamjasonp/corefx,stone-li/corefx,YoupHulsebos/corefx,twsouthwick/corefx,mokchhya/corefx,YoupHulsebos/corefx,weltkante/corefx,dotnet-bot/corefx,alexperovich/corefx,parjong/corefx,jcme/corefx,rjxby/corefx,benpye/corefx,rjxby/corefx,MaggieTsang/corefx,jlin177/corefx,rjxby/corefx,mazong1123/corefx,manu-silicon/corefx,JosephTremoulet/corefx,billwert/corefx,Chrisboh/corefx,yizhang82/corefx,billwert/corefx,ravimeda/corefx,stephenmichaelf/corefx,seanshpark/corefx,ericstj/corefx,richlander/corefx,parjong/corefx,cydhaselton/corefx,ptoonen/corefx,shahid-pk/corefx,JosephTremoulet/corefx,shimingsg/corefx,shahid-pk/corefx,manu-silicon/corefx,nbarbettini/corefx,lggomez/corefx,marksmeltzer/corefx,JosephTremoulet/corefx,nchikanov/corefx,stone-li/corefx,the-dwyer/corefx,billwert/corefx,Jiayili1/corefx,weltkante/corefx,tijoytom/corefx,mokchhya/corefx,Jiayili1/corefx,parjong/corefx,mazong1123/corefx,ellismg/corefx,stone-li/corefx,marksmeltzer/corefx,wtgodbe/corefx,Ermiar/corefx,ericstj/corefx,cartermp/corefx,dotnet-bot/corefx,seanshpark/corefx,pallavit/corefx,ravimeda/corefx,adamralph/corefx,jlin177/corefx,manu-silicon/corefx,Priya91/corefx-1,Ermiar/corefx,iamjasonp/corefx,krk/corefx,dhoehna/corefx,mokchhya/corefx,SGuyGe/corefx,benjamin-bader/corefx,DnlHarvey/corefx,DnlHarvey/corefx,ellismg/corefx,zhenlan/corefx,parjong/corefx,ericstj/corefx,tijoytom/corefx,Chrisboh/corefx,marksmeltzer/corefx,alexperovich/corefx,stone-li/corefx,elijah6/corefx,jlin177/corefx,gkhanna79/corefx,mokchhya/corefx,lggomez/corefx,jlin177/corefx,mmitche/corefx,axelheer/corefx,stephenmichaelf/corefx,rubo/corefx,krytarowski/corefx,ellismg/corefx,krytarowski/corefx,mmitche/corefx,Priya91/corefx-1,wtgodbe/corefx,nchikanov/corefx,nbarbettini/corefx,mazong1123/corefx,ellismg/corefx,MaggieTsang/corefx,rjxby/corefx,ptoonen/corefx,khdang/corefx,rjxby/corefx,pallavit/corefx,yizhang82/corefx,Ermiar/corefx,Jiayili1/corefx,nchikanov/corefx,manu-silicon/corefx,axelheer/corefx,ravimeda/corefx,weltkante/corefx,fgreinacher/corefx,fgreinacher/corefx,ericstj/corefx,Petermarcu/corefx,ravimeda/corefx,yizhang82/corefx,billwert/corefx,twsouthwick/corefx,alphonsekurian/corefx,tstringer/corefx,mazong1123/corefx,richlander/corefx,ptoonen/corefx,zhenlan/corefx,MaggieTsang/corefx,iamjasonp/corefx,jhendrixMSFT/corefx,Petermarcu/corefx,Priya91/corefx-1,alexperovich/corefx,krk/corefx,ViktorHofer/corefx,dhoehna/corefx,benjamin-bader/corefx,krk/corefx,krytarowski/corefx,dotnet-bot/corefx,MaggieTsang/corefx,tstringer/corefx,jcme/corefx,jhendrixMSFT/corefx,YoupHulsebos/corefx,khdang/corefx,billwert/corefx,iamjasonp/corefx,wtgodbe/corefx,lggomez/corefx,wtgodbe/corefx,alexperovich/corefx,rubo/corefx,nchikanov/corefx,benpye/corefx,nbarbettini/corefx,yizhang82/corefx,Priya91/corefx-1,alexperovich/corefx,tijoytom/corefx,khdang/corefx,stone-li/corefx,marksmeltzer/corefx,pallavit/corefx,tstringer/corefx,krytarowski/corefx,mazong1123/corefx,twsouthwick/corefx,the-dwyer/corefx,stephenmichaelf/corefx,ravimeda/corefx,dotnet-bot/corefx,dhoehna/corefx,kkurni/corefx,krk/corefx,rahku/corefx,dotnet-bot/corefx,rjxby/corefx,the-dwyer/corefx,jhendrixMSFT/corefx,seanshpark/corefx,manu-silicon/corefx,stephenmichaelf/corefx,manu-silicon/corefx,nbarbettini/corefx,janhenke/corefx,the-dwyer/corefx,yizhang82/corefx,shmao/corefx,shmao/corefx,dhoehna/corefx,DnlHarvey/corefx,cydhaselton/corefx,lggomez/corefx,kkurni/corefx,zhenlan/corefx,YoupHulsebos/corefx,jhendrixMSFT/corefx,SGuyGe/corefx,gkhanna79/corefx,Priya91/corefx-1,rahku/corefx,ellismg/corefx,Priya91/corefx-1,pallavit/corefx,mmitche/corefx,ViktorHofer/corefx,krytarowski/corefx,fgreinacher/corefx,mmitche/corefx,SGuyGe/corefx,Petermarcu/corefx,krk/corefx,twsouthwick/corefx,janhenke/corefx,ericstj/corefx,mokchhya/corefx,seanshpark/corefx,ptoonen/corefx,Jiayili1/corefx,tstringer/corefx,iamjasonp/corefx,shahid-pk/corefx,Ermiar/corefx,parjong/corefx,cydhaselton/corefx,marksmeltzer/corefx,richlander/corefx,alphonsekurian/corefx,jhendrixMSFT/corefx,tijoytom/corefx,ellismg/corefx,parjong/corefx,stephenmichaelf/corefx,seanshpark/corefx,benjamin-bader/corefx,jlin177/corefx,ViktorHofer/corefx,kkurni/corefx,billwert/corefx,MaggieTsang/corefx,iamjasonp/corefx,richlander/corefx,parjong/corefx,Chrisboh/corefx,BrennanConroy/corefx,ravimeda/corefx,jcme/corefx,manu-silicon/corefx,ptoonen/corefx,ericstj/corefx,twsouthwick/corefx,nbarbettini/corefx,rubo/corefx,SGuyGe/corefx,BrennanConroy/corefx,Jiayili1/corefx,axelheer/corefx,cartermp/corefx,zhenlan/corefx,Ermiar/corefx,shahid-pk/corefx,weltkante/corefx,lggomez/corefx,shmao/corefx,ViktorHofer/corefx,axelheer/corefx,shmao/corefx,nchikanov/corefx,Petermarcu/corefx,janhenke/corefx,khdang/corefx,yizhang82/corefx,benpye/corefx,mazong1123/corefx,MaggieTsang/corefx,Petermarcu/corefx,pallavit/corefx,seanshpark/corefx,gkhanna79/corefx,cartermp/corefx,richlander/corefx,ericstj/corefx,wtgodbe/corefx,rubo/corefx,cartermp/corefx,shimingsg/corefx,Jiayili1/corefx,zhenlan/corefx,mokchhya/corefx,zhenlan/corefx,elijah6/corefx,alphonsekurian/corefx,krytarowski/corefx,shimingsg/corefx,twsouthwick/corefx,Chrisboh/corefx,benjamin-bader/corefx,jcme/corefx,elijah6/corefx,DnlHarvey/corefx,tijoytom/corefx,mazong1123/corefx,Jiayili1/corefx,Chrisboh/corefx,JosephTremoulet/corefx,shmao/corefx,rahku/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,cydhaselton/corefx,cydhaselton/corefx,weltkante/corefx,DnlHarvey/corefx,YoupHulsebos/corefx,twsouthwick/corefx,marksmeltzer/corefx,marksmeltzer/corefx,alexperovich/corefx,shmao/corefx,alphonsekurian/corefx,gkhanna79/corefx,MaggieTsang/corefx,jhendrixMSFT/corefx,weltkante/corefx,adamralph/corefx,lggomez/corefx,dhoehna/corefx,elijah6/corefx,krk/corefx,ViktorHofer/corefx,DnlHarvey/corefx,dotnet-bot/corefx,Ermiar/corefx,seanshpark/corefx,benpye/corefx,richlander/corefx,JosephTremoulet/corefx,jlin177/corefx,janhenke/corefx,dotnet-bot/corefx,lggomez/corefx,dhoehna/corefx,cartermp/corefx,shimingsg/corefx,alphonsekurian/corefx,krk/corefx,dsplaisted/corefx,gkhanna79/corefx,kkurni/corefx,nchikanov/corefx,the-dwyer/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,dsplaisted/corefx,tstringer/corefx,tijoytom/corefx,pallavit/corefx,gkhanna79/corefx,tstringer/corefx,JosephTremoulet/corefx,SGuyGe/corefx,ViktorHofer/corefx,jcme/corefx,alexperovich/corefx,shimingsg/corefx,elijah6/corefx,tijoytom/corefx,stone-li/corefx,janhenke/corefx,shahid-pk/corefx,cydhaselton/corefx,SGuyGe/corefx,mmitche/corefx,ptoonen/corefx,stone-li/corefx,fgreinacher/corefx,yizhang82/corefx,the-dwyer/corefx,benjamin-bader/corefx,kkurni/corefx,shimingsg/corefx,adamralph/corefx,axelheer/corefx,rahku/corefx,benjamin-bader/corefx,nchikanov/corefx,ptoonen/corefx,elijah6/corefx,jlin177/corefx,jcme/corefx,rahku/corefx,iamjasonp/corefx,Chrisboh/corefx,BrennanConroy/corefx,shmao/corefx,rjxby/corefx,Ermiar/corefx,khdang/corefx,dhoehna/corefx,janhenke/corefx,billwert/corefx,rahku/corefx
src/Common/tests/Tests/System/Net/HttpKnownHeaderNamesTests.cs
src/Common/tests/Tests/System/Net/HttpKnownHeaderNamesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Xunit; namespace Tests.System.Net { public class HttpKnownHeaderNamesTests { [Theory] [InlineData("")] [InlineData("this should not be found")] public void TryGetHeaderName_UnknownStrings_NotFound(string shouldNotBeFound) { char[] key = shouldNotBeFound.ToCharArray(); string name; Assert.False(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name)); Assert.Null(name); } [Theory] [MemberData("HttpKnownHeaderNamesPublicStringConstants")] public void TryGetHeaderName_AllHttpKnownHeaderNamesPublicStringConstants_Found(string constant) { char[] key = constant.ToCharArray(); string name1; Assert.True(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name1)); Assert.NotNull(name1); Assert.Equal(constant, name1); string name2; Assert.True(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name2)); Assert.NotNull(name2); Assert.Equal(constant, name2); Assert.Same(name1, name2); } public static IEnumerable<object[]> HttpKnownHeaderNamesPublicStringConstants { get { string[] constants = typeof(HttpKnownHeaderNames) .GetTypeInfo() .DeclaredFields .Where(f => f.IsLiteral && f.IsStatic && f.IsPublic && f.FieldType == typeof(string)) .Select(f => (string)f.GetValue(null)) .ToArray(); Assert.NotEmpty(constants); Assert.DoesNotContain(constants, c => string.IsNullOrEmpty(c)); return constants.Select(c => new object[] { c }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Xunit; namespace Tests.System.Net { public class HttpKnownHeaderNamesTests { [Theory] [InlineData("")] [InlineData("this should not be found")] public void TryGetHeaderName_UnknownStrings_NotFound(string shouldNotBeFound) { char[] key = shouldNotBeFound.ToCharArray(); string name; Assert.False(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name)); Assert.Null(name); } [Theory] [MemberData("HttpKnownHeaderNamesPublicStringConstants")] public void TryGetHeaderName_AllHttpKnownHeaderNamesPublicStringConstants_Found(string constant) { char[] key = constant.ToCharArray(); string name; Assert.True(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name)); Assert.NotNull(name); Assert.Equal(constant, name); } public static IEnumerable<object[]> HttpKnownHeaderNamesPublicStringConstants { get { string[] constants = typeof(HttpKnownHeaderNames) .GetTypeInfo() .DeclaredFields .Where(f => f.IsStatic && f.IsPublic && f.FieldType == typeof(string)) .Select(f => (string)f.GetValue(null)) .ToArray(); Assert.NotEmpty(constants); Assert.DoesNotContain(constants, c => string.IsNullOrEmpty(c)); return constants.Select(c => new object[] { c }); } } } }
mit
C#
db9ee60647f08ddb7b2a83bd1f7c52e5c34cb0aa
Add serviceable attribute to projects.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Session/Properties/AssemblyInfo.cs
src/Microsoft.AspNet.Session/Properties/AssemblyInfo.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; [assembly: AssemblyMetadata("Serviceable", "True")]
apache-2.0
C#
fdd8884d4bbe2d16af0aabfcb270ac80b0b3be54
Save the Prisoner
shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms
savePrisoner.cs
savePrisoner.cs
# File : savePrisoner.cs # Author : Shree Harsha Sridharamurthy # Author email : s.shreeharsha@gmail.com # Disclaimer : This program is solely created by Shree Harsha for academic purposes. # For use by concerned personnel only. Not to be copied in full or in part. # Program : Solution for hackerrank question posted here:https://www.hackerrank.com/contests/101hack35/challenges/save-the-prisoner # Details : /*A jail has N prisoners, and each prisoner has a unique id number, S, ranging from 1 to N. There are M sweets that must be distributed to the prisoners. The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending S), and then, starting with some random S, distribute one candy at a time to each sequentially numbered prisoner until all M candies are distributed. For example, if the jailer picks prisoner S=2, then his distribution order would be (2,3,4,5,…,n−1,n,1,2,3,4,…) until all MM sweets are distributed. But wait—there's a catch—the very last sweet is poisoned! Can you find and print the ID number of the last prisoner to receive a sweet so he can be warned? Input Format The first line contains an integer, T, denoting the number of test cases. The T subsequent lines each contain 3 space-separated integers: N (the number of prisoners), M (the number of sweets), and S (the prisoner ID), respectively. Constraints 1≤T≤1001≤T≤100 1≤N≤1091≤N≤109 1≤M≤1091≤M≤109 1≤S≤1091≤S≤109 Output Format For each test case, print the ID number of the prisoner who receives the poisoned sweet on a new line. Sample Input 1 5 2 1 Sample Output 2 Explanation There are N=5 prisoners and M=2 sweets. Distribution starts at ID number S=1, so prisoner 1 gets the first sweet and prisoner 2 gets the second (last) sweet. Thus, we must warn prisoner 2 about the poison, so we print 2 on a new line. */ using System; using System.Collections.Generic; using System.IO; class Solution { static void Main(String[] args) { int T = Convert.ToInt32(Console.ReadLine()); //loop the number of test cases for(int x=0;x<T;x++){ var str = Console.ReadLine(); string[] strNums = str.Split(' '); //new integer array to hold the numbers int[] intNums = new int[strNums.Length]; for(int k = 0; k < strNums.Length; k++){ intNums[k] = Convert.ToInt32(strNums[k]); } //only three numbers as per the requirement so assigning directly int N = intNums[0]; int M = intNums[1]; int S = intNums[2]; //main logic to obtain the solution S = (S + M) % N; int W = S - 1;//value obtained from previous step is higher by one so reducing it //return the number (W) to warn the prisoner, if 0, it is the maximum number Console.WriteLine(W==0?N:W); } } }
mit
C#
41af99edae401623e56a3bc639fb11047b306dcd
Solve Salary with Bonus in c#
deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground
solutions/uri/1009/1009.cs
solutions/uri/1009/1009.cs
using System; class Solution { static void Main() { double b, c; _ = Console.ReadLine(); b = Convert.ToDouble(Console.ReadLine()); c = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("TOTAL = R$ {0:F2}", b + c * 0.15); } }
mit
C#
b31f36328bd5954f5ea9a9db537d59c113ba8a6b
Create Triggers_Collision_2_Destroy.cs
Tech-Curriculums/101-GameDesign-2D-GameDesign-With-Unity
AngryHipsters/Triggers_Collision_2_Destroy.cs
AngryHipsters/Triggers_Collision_2_Destroy.cs
using UnityEngine; using System.Collections; public class Triggers_Collision_2_Destroy : MonoBehaviour { void OnTriggerEnter2D (Collider2D other) { if (other.gameObject.tag == "Player") { Destroy(this.gameObject); audio.Play(); } } }
mit
C#
17d923b1f173a2b13293bfacf56399a3ea9453e7
Add API service to handle save and load of API keys
n01d/Welcome-Kiosk
ReceptionKiosk/Services/APISettingsService.cs
ReceptionKiosk/Services/APISettingsService.cs
using System; using System.Threading.Tasks; using ReceptionKiosk.Helpers; using Windows.Storage; using Windows.UI.Xaml; namespace ReceptionKiosk.Services { public class APISettingsService { private string faceAPI; private string bingAPI; public APISettingsService() { LoadAPIKeysFromSettingsAsync(); } public string FaceAPI { get { return faceAPI; } set { faceAPI = value; SaveAPIKeysInSettingsAsync("FaceAPI", faceAPI); } } public string BingAPI { get { return bingAPI; } set { bingAPI = value; SaveAPIKeysInSettingsAsync("BingAPI", bingAPI); } } private async void LoadAPIKeysFromSettingsAsync() { BingAPI = await ApplicationData.Current.LocalSettings.ReadAsync<string>("FaceAPI"); FaceAPI = await ApplicationData.Current.LocalSettings.ReadAsync<string>("BingAPI"); } private static async Task SaveAPIKeysInSettingsAsync(string SettingsKey, string APIKeyValue) { await ApplicationData.Current.LocalSettings.SaveAsync<string>(SettingsKey, APIKeyValue); } } }
mit
C#
d99910fe6c37c12110f1522f991e2274bb424507
Add tests for new provider base class
ocoanet/moq4,Moq/moq4
Moq.Tests/LookupOrFallbackDefaultValueProviderFixture.cs
Moq.Tests/LookupOrFallbackDefaultValueProviderFixture.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace Moq.Tests { public class LookupOrFallbackDefaultValueProviderFixture { [Theory] [InlineData(typeof(int), default(int))] // plain value type [InlineData(typeof(float), default(float))] // plain value type [InlineData(typeof(int?), null)] // nullable [InlineData(typeof(int[]), default(int[]))] // emptyable [InlineData(typeof(IEnumerable<>), null)] // emptyable [InlineData(typeof(string), default(string))] // primitive reference type [InlineData(typeof(Exception), default(Exception))] // reference type public void Produces_default_when_no_factory_registered(Type type, object expected) { var provider = new Provider(); var actual = provider.GetDefaultValue(type); Assert.Equal(expected, actual); } [Theory] [InlineData(typeof(int), 42)] public void Falls_back_to_default_generation_strategy_when_no_handler_available(Type type, object fallbackValue) { var provider = new Provider((t, _) => t == type ? fallbackValue : throw new NotSupportedException()); provider.Deregister(type); var actual = provider.GetDefaultValue(type); Assert.Equal(fallbackValue, actual); } [Fact] public void Can_register_factory_for_specific_type() { var provider = new Provider(); provider.Register(typeof(Exception), (_, __) => new InvalidOperationException()); var actual = provider.GetDefaultValue(typeof(Exception)); Assert.NotNull(actual); Assert.IsType<InvalidOperationException>(actual); } [Fact] public void Can_register_factory_for_generic_type() { var provider = new Provider(); provider.Register(typeof(IEnumerable<>), (type, __) => { var elementType = type.GetGenericArguments()[0]; return Array.CreateInstance(elementType, 0); }); var actual = provider.GetDefaultValue(typeof(IEnumerable<int>)); Assert.NotNull(actual); Assert.IsType<int[]>(actual); } [Fact] public void Can_register_factory_for_array_type() { var provider = new Provider(); provider.Register(typeof(Array), (type, __) => { var elementType = type.GetElementType(); return Array.CreateInstance(elementType, 0); }); var actual = provider.GetDefaultValue(typeof(int[])); Assert.NotNull(actual); Assert.IsType<int[]>(actual); } [Fact] public void Produces_completed_Task() { var provider = new Provider(); var actual = (Task)provider.GetDefaultValue(typeof(Task)); Assert.True(actual.IsCompleted); } [Fact] public void Handling_of_Task_can_be_disabled() { var provider = new Provider(); provider.Deregister(typeof(Task)); var actual = provider.GetDefaultValue(typeof(Task)); Assert.Null(actual); } [Fact] public void Produces_completed_generic_Task() { const int expected = 42; var provider = new Provider(); provider.Register(typeof(int), (_, __) => expected); var actual = (Task<int>)provider.GetDefaultValue(typeof(Task<int>)); Assert.True(actual.IsCompleted); Assert.Equal(42, actual.Result); } [Fact] public void Handling_of_generic_Task_can_be_disabled() { var provider = new Provider(); provider.Deregister(typeof(Task<>)); var actual = provider.GetDefaultValue(typeof(Task<int>)); Assert.Null(actual); } [Fact] public void Produces_completed_ValueTask() { const int expectedResult = 42; var provider = new Provider(); provider.Register(typeof(int), (_, __) => expectedResult); var actual = (ValueTask<int>)provider.GetDefaultValue(typeof(ValueTask<int>)); Assert.True(actual.IsCompleted); Assert.Equal(42, actual.Result); } [Fact] public void Handling_of_ValueTask_can_be_disabled() { // If deregistration of ValueTask<> handling really works, the fallback strategy will produce // `default(ValueTask<int>)`, which equals a completed task containing 0 as result. So this test // needs to look different from the `Task<>` equivalent above. // We check for successful disabling of `ValueTask<>` handling indirectly, namely by // setting up a specific default value for `int` first, then we can verify that this value // does *not* get wrapped in a value task when we ask for `ValueTask<int>` const int unexpected = 42; var provider = new Provider(); provider.Register(typeof(int), (_, __) => unexpected); provider.Deregister(typeof(ValueTask<>)); var actual = (ValueTask<int>)provider.GetDefaultValue(typeof(ValueTask<int>)); Assert.Equal(default(ValueTask<int>), actual); Assert.NotEqual(unexpected, actual.Result); } /// <summary> /// Subclass of <see cref="LookupOrFallbackDefaultValueProvider"/> used as a test surrogate. /// </summary> private sealed class Provider : LookupOrFallbackDefaultValueProvider { private Mock<object> mock; private Func<Type, Mock, object> fallback; public Provider(Func<Type, Mock, object> fallback = null) { this.mock = new Mock<object>(); this.fallback = fallback; } public object GetDefaultValue(Type type) { return base.GetDefaultValue(type, mock); } new public void Deregister(Type factoryKey) { base.Deregister(factoryKey); } new public void Register(Type factoryKey, Func<Type, Mock, object> factory) { base.Register(factoryKey, factory); } protected override object GetFallbackDefaultValue(Type type, Mock mock) { return this.fallback?.Invoke(type, mock) ?? base.GetFallbackDefaultValue(type, mock); } } } }
bsd-3-clause
C#
a7177bccbc7c772ccd5c42eba0fb5ac11bce92af
Add ReflectionHelper class
copygirl/EntitySystem
src/Utility/ReflectionHelper.cs
src/Utility/ReflectionHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace EntitySystem.Utility { public static class ReflectionHelper { static readonly Dictionary<Type, string> _friendlyNameLookup = new Dictionary<Type, string>() { { typeof(void), "void" }, { typeof(object), "object" }, { typeof(sbyte), "sbyte" }, { typeof(byte), "byte" }, { typeof(int), "int" }, { typeof(uint), "uint" }, { typeof(short), "short" }, { typeof(ushort), "ushort" }, { typeof(long), "long" }, { typeof(ulong), "ulong" }, { typeof(float), "float" }, { typeof(double), "double" }, { typeof(decimal), "decimal" }, { typeof(bool), "bool" }, { typeof(char), "char" }, { typeof(string), "string" }, }; public static string GetFriendlyName(this Type type) { ThrowIf.Argument.IsNull(type, nameof(type)); var typeInfo = type.GetTypeInfo(); string name; if (_friendlyNameLookup.TryGetValue(type, out name)) return name; if (type.IsArray) return new StringBuilder() .Append(type.GetElementType().GetFriendlyName()) .Append('[') .Append(new string(',', type.GetArrayRank() - 1)) .Append(']') .ToString(); if (typeInfo.IsGenericType) return new StringBuilder() .Append(type.Name.Substring(0, type.Name.LastIndexOf('`'))) .Append('<') .AppendAll(typeInfo.GenericTypeArguments.Select(GetFriendlyName), ",") .Append('>') .ToString(); return type.Name; } } }
mit
C#
34532b96828cdc5f9c26913d79f4ace0507ede57
Add missing PartsDb base class
jnwatts/cs320_project2_group11,jnwatts/cs320_project2_group11
Model/partsdb.cs
Model/partsdb.cs
using System; using System.Data; using System.Collections.Generic; public delegate void ErrorHandler(string message, Exception exception); public delegate void PartTypesHandler(List<PartType> partTypes); public delegate void PartsHandler(PartCollection part); public delegate void PartHandler(Part part); public abstract class PartsDb { public string Username { get; set; } public string Password { get; set; } public string Hostname { get; set; } public string Database { get; set; } public abstract void GetPartTypes(PartTypesHandler partTypeHandler, ErrorHandler errorHandler); public abstract void GetPart(string Part_num, PartHandler partHandler, ErrorHandler errorHandler); public abstract void GetParts(PartType partType, PartsHandler partsHandler, ErrorHandler errorHandler); //TODO: This should be based off a new part. The *controller* should figure out how to make the new part, the DB should only dutifully insert it. public abstract void NewPart(PartType partType, ErrorHandler errorHandler); public abstract void UpdatePart(Part part, ErrorHandler errorHandler); }
apache-2.0
C#
f2b624018b36c286a1e992f3cbfc70fe8f1170c4
Test for async graph updates from gui block/connector
Skoth/KSPCommEngr
CommEngrTest/CommBlockTests.cs
CommEngrTest/CommBlockTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using KSPCommEngr; namespace CommEngrTest { [TestClass] public class CommBlockTests { [TestMethod] public void UpdateGraphOnDragStop() { Graph graph = new Graph(new int[,] { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }); Graph expectedGraph = new Graph(new int[,] { { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0 } }); // User Drag and Drop Event CollectionAssert.AreEqual(expectedGraph.nodes, graph.nodes); } } }
mit
C#
9b641e3227a8481026fe9fc19ba93cde73faa079
Create problem005.cs
mvdiener/project_euler,mvdiener/project_euler
CSharp/problem005.cs
CSharp/problem005.cs
//2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. //What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? using System; using System.Collections.Generic; namespace Problem005 { class MainClass { public static void Main() { Console.WriteLine(FindLowestCommonMultiple(20)); } public static int FindLowestCommonMultiple(int num) { Dictionary<int, int> allFactors = new Dictionary<int, int>(); for (int i = 2; i <= num; i++) { Dictionary<int, int> singleNumberFactors = new Dictionary<int, int>(); singleNumberFactors = PrimeFactors(i, singleNumberFactors); allFactors = GroupFactors(allFactors, singleNumberFactors); } int total = 1; foreach (var factor in allFactors) { total *= (int)(Math.Pow((double)factor.Key, (double)factor.Value)); } return total; } public static Dictionary<int, int> GroupFactors(Dictionary<int, int> allFactors, Dictionary<int, int> singleNumberFactors) { foreach (var factor in singleNumberFactors) { if (allFactors.ContainsKey(factor.Key)) { if (allFactors[factor.Key] < factor.Value) { allFactors[factor.Key] = factor.Value; } } else { allFactors[factor.Key] = factor.Value; } } return allFactors; } public static Dictionary<int, int> PrimeFactors(int number, Dictionary<int, int> factorGrouping) { for (int i = 2; i <= number; i++) { if (number % i == 0) { if (factorGrouping.ContainsKey(i)) { factorGrouping[i] += 1; } else { factorGrouping[i] = 1; } number = number / i; PrimeFactors(number, factorGrouping); break; } } return factorGrouping; } } }
mit
C#
5c621585b75fe245b15f848597c6b01f04051730
Add StringExtensions.GetMD5Hash
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Utilities/String.GetMD5Hash.cs
source/Nuke.Common/Utilities/String.GetMD5Hash.cs
// Copyright 2018 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Nuke.Common.Utilities { public static partial class StringExtensions { public static string GetMD5Hash(this string str) { using (var algorithm = MD5.Create()) { var hash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(str)); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } }
mit
C#
93fd5c44d46d3bba69d0eb49091d1b3624070dcc
Implement Shell Sort
cschen1205/cs-algorithms,cschen1205/cs-algorithms
Algorithms/Sorting/ShellSort.cs
Algorithms/Sorting/ShellSort.cs
using System; using Algorithms.Utils; namespace Algorithms.Sorting { public class ShellSort { public static void Sort<T>(T[] a, Comparison<T> compare) { var n = a.Length; var h = 1; while (h < n / 3) { h = 3 * h + 1; } var step = h; while (step > 0) { for (var i = step; i < n; i++) { for (var j = i; j >= step; j -= step) { if (SortUtil.IsLessThan(a[j], a[j - step], compare)) { SortUtil.Exchange(a, j, j - step); } else { break; } } } step--; } } } }
mit
C#
621480af0214f2e4e86199a0f667b70d431c895b
Add simple (non-automated) test
peppy/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,DrabWeb/osu,peppy/osu,johnneijzen/osu,DrabWeb/osu,naoey/osu,NeoAdonis/osu,NeoAdonis/osu,naoey/osu,naoey/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,ppy/osu,johnneijzen/osu
osu.Game.Tests/Visual/TestCaseDrawableDate.cs
osu.Game.Tests/Visual/TestCaseDrawableDate.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual { public class TestCaseDrawableDate : OsuTestCase { public TestCaseDrawableDate() { Child = new FillFlowContainer { Direction = FillDirection.Vertical, AutoSizeAxes = Axes.Both, Origin = Anchor.Centre, Anchor = Anchor.Centre, Children = new Drawable[] { new PokeyDrawableDate(DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(60))), new PokeyDrawableDate(DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(55))), new PokeyDrawableDate(DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(50))), new PokeyDrawableDate(DateTimeOffset.Now), new PokeyDrawableDate(DateTimeOffset.Now.Add(TimeSpan.FromSeconds(60))), new PokeyDrawableDate(DateTimeOffset.Now.Add(TimeSpan.FromSeconds(65))), new PokeyDrawableDate(DateTimeOffset.Now.Add(TimeSpan.FromSeconds(70))), } }; } private class PokeyDrawableDate : CompositeDrawable { public PokeyDrawableDate(DateTimeOffset date) { const float box_size = 10; DrawableDate drawableDate; Box flash; AutoSizeAxes = Axes.Both; InternalChildren = new Drawable[] { flash = new Box { Colour = Color4.Yellow, Size = new Vector2(box_size), Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Alpha = 0 }, drawableDate = new DrawableDate(date) { X = box_size + 2, } }; drawableDate.Current.ValueChanged += v => flash.FadeOutFromOne(500); } } } }
mit
C#
937e76334fccb09dadb6e9147201727cea52be19
Use Task for back-run in .Net Core
Forward2015/Download,Forward2015/Download,Forward2015/Download,Forward2015/Download
DotNetCore/TaskHelper.cs
DotNetCore/TaskHelper.cs
public class TaskHelper{ public static BeginTask(){ Task.Factory.StartNew(()=>{ //... }); } }
mit
C#
a653b061d6576255c8992f82d74a19ae48f399cd
add TerrainTreeReplacer
UnityCommunity/UnityLibrary
Assets/Scripts/Tools/TerrainTreeReplacer.cs
Assets/Scripts/Tools/TerrainTreeReplacer.cs
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class TerrainTreeReplacer : EditorWindow { private const string RootObjectName = "TREES_CONVERTED"; [MenuItem("Window/Tools/Terrain Tree Replacer")] public static void ShowWindow() { EditorWindow.GetWindow(typeof(TerrainTreeReplacer)); } private Terrain terrain; private bool disableDrawTreesAndFoliage = false; private int treeDivisions = 0; private bool DivideTreesIntoGroups { get { return treeDivisions > 0; } } void OnGUI() { GUILayout.Label("Replace Terrain Trees with Objects", EditorStyles.boldLabel); terrain = EditorGUILayout.ObjectField("Terrain:", terrain, typeof(Terrain), true) as Terrain; disableDrawTreesAndFoliage = EditorGUILayout.ToggleLeft("Disable Drawing Trees and Foliage", disableDrawTreesAndFoliage); GUILayout.Label("Tree Division groups: " + treeDivisions); treeDivisions = (int)GUILayout.HorizontalSlider(treeDivisions, 0, 10); if (GUILayout.Button("Replace Terrain trees to Objects!")) Replace(); if (GUILayout.Button("Clear generated trees!")) Clear(); } public void Replace() { if (terrain == null) { Debug.LogError("Please Assign Terrain"); return; } Clear(); GameObject treeParent = new GameObject(RootObjectName); List<List<Transform>> treegroups = new List<List<Transform>>(); if (DivideTreesIntoGroups) { for (int i = 0; i < treeDivisions; i++) { treegroups.Add(new List<Transform>()); for (int j = 0; j < treeDivisions; j++) { GameObject treeGroup = new GameObject("TreeGroup_" + i + "_" + j); treeGroup.transform.parent = treeParent.transform; treegroups[i].Add(treeGroup.transform); } } } TerrainData terrainData = terrain.terrainData; float xDiv = terrainData.size.x / (float)treeDivisions; float zDiv = terrainData.size.z / (float)treeDivisions; foreach (TreeInstance tree in terrainData.treeInstances) { GameObject treePrefab = terrainData.treePrototypes[tree.prototypeIndex].prefab; Vector3 position = Vector3.Scale(tree.position, terrainData.size); int xGroup = (int)(position.x / xDiv); int zGroup = (int)(position.z / zDiv); position += terrain.transform.position; Vector2 lookRotationVector = new Vector2(Mathf.Cos(tree.rotation - Mathf.PI), Mathf.Sin(tree.rotation - Mathf.PI)); Quaternion rotation = Quaternion.LookRotation(new Vector3(lookRotationVector.x, 0, lookRotationVector.y), Vector3.up); Vector3 scale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale); GameObject spawnedTree = Instantiate(treePrefab, position, rotation) as GameObject; spawnedTree.name = treePrefab.name; spawnedTree.transform.localScale = scale; if (DivideTreesIntoGroups) spawnedTree.transform.SetParent(treegroups[xGroup][zGroup]); else spawnedTree.transform.SetParent(treeParent.transform); } if (disableDrawTreesAndFoliage) terrain.drawTreesAndFoliage = false; } public void Clear() { DestroyImmediate(GameObject.Find(RootObjectName)); } }
mit
C#
7f9aa33891732aad8ae2df29590fbca6afe5a030
Create Problem50.cs
fireheadmx/ProjectEuler,fireheadmx/ProjectEuler
Problems/Problem50.cs
Problems/Problem50.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler.Problems { class Problem50 { private long upper; private Sieve s; public Problem50() { upper = 1000000; //upper = 1000; s = new Sieve(upper); } public void Run() { long maxPrime = 953; int maxCount = 21; int maxJ = 0; for (int i =(int)(s.primeList.Count*0.9); i < s.primeList.Count; i++) // Prime being checked { long currentPrime = s.primeList[i]; for (int j = 0; j < i - 1; j++) // Point from where to start adding { long sum = 0; int count = 0; for (int k = j; k < i - 1; k++) // Add consecutive Primes { if (i - k < maxCount) { // Skip if there are less primes remaining than the highest count break; } sum += s.primeList[k]; count++; if (sum == currentPrime) { if (count > maxCount) { maxCount = count; maxPrime = currentPrime; maxJ = j; } break; } else if (sum > currentPrime) { break; } } } } Console.WriteLine(maxPrime.ToString() + ": " + maxCount.ToString() + " (" + s.primeList[maxJ].ToString() + "..." + s.primeList[maxJ + maxCount] + ")"); } } }
mit
C#
3b6bbea22864b6af5de4578766f8692fba0fa7a4
Create Rope.cs
Onastick/Unity2D
Rope.cs
Rope.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEditor; public class Rope : MonoBehaviour { Rigidbody2D[] rigidbodies; JointMotor2D motor; JointAngleLimits2D limits; Vector2 anchorDistance; public Sprite SpriteImage; public Material Material; public int RopeLength; public string SortingLayer = "Default"; [Header("Rigidbody2D")] public bool DecrementMassValue; public double DecrementValue; public double Mass = 1; public float LinearDrag = 0; public float AngularDrag = 0.005F; public float GravityScale = 1; public bool FixedAngle; public bool isKinematic; public RigidbodyInterpolation2D Interpolate = RigidbodyInterpolation2D.None; public RigidbodySleepMode2D SleepingMode = RigidbodySleepMode2D.StartAsleep; public CollisionDetectionMode2D CollisionDetection = CollisionDetectionMode2D.None; [Header("Hinge2D")] public bool EnableCollision; public Rigidbody2D BaseRigidBody; public bool UseAutoAnchor = true; public float anchorOffset; public Vector2 Anchor; public Vector2 ConnectedAnchor; public bool UseMotor; public float MotorSpeed; public float MaximumMotorForce; public bool UseLimit = true; public float LowerAngle = 45; public float UpperAngle = -45; public void GenerateRope() { if(this.gameObject.GetComponent<HingeJoint2D>() == null){ this.gameObject.AddComponent<HingeJoint2D>(); } BaseRigidBody = this.GetComponent<Rigidbody2D>(); Vector3 distance = new Vector3(0,0,0); for(int n = 0; n < RopeLength; n++) { GameObject RopeObject = new GameObject (SpriteImage.name, typeof(SpriteRenderer), typeof(Rigidbody2D), typeof(HingeJoint2D)) as GameObject; SpriteRenderer Rope = RopeObject.GetComponent<SpriteRenderer>(); Rope.sprite = SpriteImage; Rope.sortingLayerName = SortingLayer; Rope.material = Material; if(n==0){ RopeObject.transform.SetParent (this.transform); RopeObject.transform.localPosition = Vector3.zero; } else { //Use this code if you wish to have ladder parenting for all new objects. Anchors may not set properly. //RopeObject.transform.SetParent (this.gameObject.GetComponentsInChildren<SpriteRenderer>().ElementAt(n).transform); //distance.y = -DistanceBetweenRopePiece; RopeObject.transform.SetParent (this.transform); distance.y = -(Rope.bounds.size.y * n); RopeObject.transform.localPosition = distance; } RopeObject.name = SpriteImage.name + " " + n; } Debug.Log ("Rope generated!"); } public void ApplyRigidbody2D() { int n = 0; var bodies = gameObject.GetComponentsInChildren<Rigidbody2D>(true); foreach(var rigidbody in bodies) { if(n!=0){ #region "Update Rigidbody2D Components" rigidbody.mass = (float)Mass; rigidbody.drag = LinearDrag; rigidbody.angularDrag = AngularDrag; rigidbody.gravityScale = GravityScale; rigidbody.fixedAngle = FixedAngle; rigidbody.isKinematic = isKinematic; rigidbody.interpolation = Interpolate; rigidbody.sleepMode = SleepingMode; rigidbody.collisionDetectionMode = CollisionDetection; #endregion if(DecrementMassValue){ Mass -= DecrementValue; } } else{ rigidbody.fixedAngle = true; rigidbody.isKinematic = true; } n++; } Debug.Log ("Rigidbody components updated."); } public void ApplyHinge2D() { rigidbodies = this.gameObject.GetComponentsInChildren<Rigidbody2D>(true); int n = 0; var hinges = this.gameObject.GetComponentsInChildren<HingeJoint2D>(true); foreach(var hinge in hinges) { hinge.enableCollision = EnableCollision; if(!UseAutoAnchor){ hinge.anchor = Anchor; hinge.connectedAnchor = ConnectedAnchor; } #region Update Hinge2D Components" motor.motorSpeed = MotorSpeed; motor.maxMotorTorque = MaximumMotorForce; hinge.motor = motor; hinge.useMotor = UseMotor; limits.min = LowerAngle; limits.max = UpperAngle; hinge.limits = limits; hinge.useLimits = UseLimit; #endregion if(n!=0){ hinge.connectedBody = rigidbodies[n-1]; } else hinge.connectedBody = null; n++; } if(UseAutoAnchor){ AutoAnchor(); } Debug.Log ("Hinge2D components updated."); } private void AutoAnchor(){ int n = 0; var hinges = this.gameObject.GetComponentsInChildren<HingeJoint2D>(true); foreach(var hinge in hinges) { anchorDistance.y = this.gameObject.GetComponentInChildren<SpriteRenderer>().sprite.bounds.size.y/2 - anchorOffset; if(n==0){ Debug.Log ("Base anchor skipped."); } if(n==1){ hinge.anchor = anchorDistance; hinge.connectedAnchor = anchorDistance; } if(n>=2){ hinge.anchor = anchorDistance; anchorDistance.y = -anchorDistance.y; hinge.connectedAnchor = anchorDistance; } n++; } } }
cc0-1.0
C#
288b0c7f2c90a0039573b95c88d7390f58741e80
Create plikcs.cs
wroclawZETO/DokumentyPacjenci
plikcs.cs
plikcs.cs
int x = 1;
mit
C#
f52b7ae2f6fc86d545dedb493f8e6c6783e397fb
Create dice.cs
orwa1902/code-exemples,orwa1902/code-exemples,orwa1902/code-exemples,orwa1902/code-exemples,orwa1902/code-exemples
dice.cs
dice.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dice { class Dice { protected int sides; public int nbr; public int side { get {return sides;} set{if (sides <= 0){ side = 0; } else { side = value; } } } public void dice() { nbr = 0; } public int Roll() { Random rnd = new Random(); nbr = rnd.Next(1,7); switch(nbr) { case 1: return 1; break; case 2: return 2; break; case 3: return 3; break; case 4: return 4; break; case 5: return 5; break; case 6: return 6; break; default: return 0; break; } } public static void Main(string[] args) { Dice d = new Dice(); d.sides = 6; Console.WriteLine("number is {0}", d.Roll()); } } }
apache-2.0
C#
0fd850b9123cb64627e6e0a1a59264b7f01e426e
Add Q205
txchen/localleet
csharp/Q205_IsomorphicStrings.cs
csharp/Q205_IsomorphicStrings.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; // Given two strings s and t, determine if they are isomorphic. // // Two strings are isomorphic if the characters in s can be replaced to get t. // // All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. // // For example, // Given "egg", "add", return true. // // Given "foo", "bar", return false. // // Given "paper", "title", return true. // https://leetcode.com/problems/isomorphic-strings/ namespace LocalLeet { public class Q205 { public bool IsIsomorphic(string s, string t) { Dictionary<char, char> dict1 = new Dictionary<char, char>(); Dictionary<char, char> dict2 = new Dictionary<char, char>(); for (int i = 0; i < s.Length; i++) { if (!dict1.ContainsKey(s[i])) { dict1[s[i]] = t[i]; } else if (dict1[s[i]] != t[i]) { return false; } if (!dict2.ContainsKey(t[i])) { dict2[t[i]] = s[i]; } else if (dict2[t[i]] != s[i]) { return false; } } return true; } private string Unescape(string txt) { if (string.IsNullOrEmpty(txt)) { return txt; } StringBuilder retval = new StringBuilder(txt.Length); for (int ix = 0; ix < txt.Length; ) { int jx = txt.IndexOf('\\', ix); if (jx < 0 || jx == txt.Length - 1) jx = txt.Length; retval.Append(txt, ix, jx - ix); if (jx >= txt.Length) break; switch (txt[jx + 1]) { case 'n': retval.Append('\n'); break; // Line feed case 'r': retval.Append('\r'); break; // Carriage return case 't': retval.Append('\t'); break; // Tab case '\\': retval.Append('\\'); break; // Don't escape case '"': retval.Append('"'); break; default: // Unrecognized, copy as-is retval.Append('\\').Append(txt[jx + 1]); break; } ix = jx + 2; } return retval.ToString(); } [Fact] public void Q205_IsomorphicStrings() { TestHelper.Run(input => IsIsomorphic(Unescape(input[0].Deserialize()), Unescape(input[1].Deserialize())).ToString().ToLower()); } } }
mit
C#
0aaab95aff574b4f7331d78b963e286b5ebb45bf
add B2LifecycleRule
NebulousConcept/b2-csharp-client
b2-csharp-client/B2.Client/Rest/B2LifecycleRule.cs
b2-csharp-client/B2.Client/Rest/B2LifecycleRule.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; namespace B2.Client.Rest { /// <summary> /// A lifecycle rule controlling the behavior of files uploaded to a bucket. /// </summary> [DataContract] public sealed class B2LifecycleRule { /// <summary> /// Predefined rule for keeping only the most recent version of a file. /// </summary> public static readonly B2LifecycleRule OnlyLastVersion = new B2LifecycleRule(string.Empty, null, 1); /// <summary> /// The prefix determining which files this rule applies to. /// </summary> [DataMember(Name = "fileNamePrefix", IsRequired = true)] public string FilenamePrefix { get; } /// <summary> /// The number of days after being uploading that a file should be hidden. /// </summary> [DataMember(Name = "daysFromUploadingToHiding")] public ulong? DaysFromUploadingToHiding { get; } /// <summary> /// The number of days after being hidden that a file should be deleted. /// </summary> [DataMember(Name = "daysFromHidingToDeleting")] public ulong? DaysFromHidingToDeleting { get; } /// <summary> /// Create a new <see cref="B2LifecycleRule"/>. /// </summary> /// <param name="FilenamePrefix">The filename prefix.</param> /// <param name="DaysFromUploadingToHiding">The number of days until hiding.</param> /// <param name="DaysFromHidingToDeleting">The number of days until deleting.</param> /// <exception cref="ArgumentException">If both durations are null, or if either is 0.</exception> [SuppressMessage("ReSharper", "InconsistentNaming")] public B2LifecycleRule(string FilenamePrefix, ulong? DaysFromUploadingToHiding, ulong? DaysFromHidingToDeleting) { if (DaysFromHidingToDeleting == null && DaysFromUploadingToHiding == null) { //should this be an ArgumentNullException instead? throw new ArgumentException("Cannot specify null for both duration options"); } if (DaysFromHidingToDeleting == 0) { throw new ArgumentException($"{nameof(DaysFromHidingToDeleting)} cannot be 0"); } if (DaysFromUploadingToHiding == 0) { throw new ArgumentException($"{nameof(DaysFromUploadingToHiding)} cannot be 0"); } this.FilenamePrefix = FilenamePrefix.ThrowIfNull(nameof(FilenamePrefix)); this.DaysFromUploadingToHiding = DaysFromUploadingToHiding; this.DaysFromHidingToDeleting = DaysFromHidingToDeleting; } } }
mit
C#
7f6bd571e9688ddef9f75016f205cf1346db46d5
add Enumeration to domain models
Abhith/Code.Library,Abhith/Code.Library
src/Code.Library/Domain/Models/Enumeration.cs
src/Code.Library/Domain/Models/Enumeration.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Code.Library.Domain.Models { public abstract class Enumeration : IComparable { protected Enumeration(int id, string name) { Id = id; Name = name; } public int Id { get; private set; } public string Name { get; private set; } public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) { var absoluteDifference = Math.Abs(firstValue.Id - secondValue.Id); return absoluteDifference; } public static T FromDisplayName<T>(string displayName) where T : Enumeration { var matchingItem = Parse<T, string>(displayName, "display name", item => item.Name == displayName); return matchingItem; } public static T FromValue<T>(int value) where T : Enumeration { var matchingItem = Parse<T, int>(value, "value", item => item.Id == value); return matchingItem; } public static IEnumerable<T> GetAll<T>() where T : Enumeration { var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); return fields.Select(f => f.GetValue(null)).Cast<T>(); } public int CompareTo(object other) => Id.CompareTo(((Enumeration)other).Id); public override bool Equals(object obj) { var otherValue = obj as Enumeration; if (otherValue == null) return false; var typeMatches = GetType().Equals(obj.GetType()); var valueMatches = Id.Equals(otherValue.Id); return typeMatches && valueMatches; } public override int GetHashCode() => Id.GetHashCode(); public override string ToString() => Name; private static T Parse<T, K>(K value, string description, Func<T, bool> predicate) where T : Enumeration { var matchingItem = GetAll<T>().FirstOrDefault(predicate); if (matchingItem == null) throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}"); return matchingItem; } } }
apache-2.0
C#
fabf2aa642ae0ff4b8a58a1b58866290806a1933
add basic Geohash tests
ssg/SimpleBase,ssg/SimpleBase32,ssg/SimpleBase
test/Base32/GeohashTest.cs
test/Base32/GeohashTest.cs
using NUnit.Framework; using SimpleBase; using System; using System.Collections.Generic; using System.Text; namespace SimpleBaseTest.Base32Test { [TestFixture] class GeohashTest { [Test] public void Decode_SmokeTest() { const string input = "ezs42"; var result = Base32.Geohash.Decode(input); var expected = new byte[] { 0b01101111, 0b11110000, 0b01000001 }; Assert.AreEqual(expected, result.ToArray()); } [Test] public void Encode_SmokeTest() { const string expected = "ezs42"; var input = new byte[] { 0b01101111, 0b11110000, 0b01000001 }; var result = Base32.Geohash.Encode(input); Assert.AreEqual(expected, result); } } }
apache-2.0
C#
a765f2502daa9760786e9c20baf688ddcb8a4a27
Add simple test case for FullscreenOverlay
smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,ZLima12/osu,peppy/osu,2yangk23/osu,ZLima12/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu
osu.Game.Tests/Visual/Online/TestCaseFullscreenOverlay.cs
osu.Game.Tests/Visual/Online/TestCaseFullscreenOverlay.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Overlays; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Online { [TestFixture] public class TestCaseFullscreenOverlay : OsuTestCase { private FullscreenOverlay overlay; protected override void LoadComplete() { base.LoadComplete(); Add(overlay = new TestFullscreenOverlay()); AddStep(@"toggle", overlay.ToggleVisibility); } private class TestFullscreenOverlay : FullscreenOverlay { public TestFullscreenOverlay() { Children = new Drawable[] { new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, }; } } } }
mit
C#
8bc5ff07d215dfdd54a3ba00af6f960a8111568c
Check we don't reference DesignTime assemblies
github/VisualStudio,github/VisualStudio,github/VisualStudio
test/GitHub.VisualStudio.UnitTests/GitHubAssemblyTests.cs
test/GitHub.VisualStudio.UnitTests/GitHubAssemblyTests.cs
using System.IO; using System.Reflection; using NUnit.Framework; public class GitHubAssemblyTests { [Theory] public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile) { var asm = Assembly.LoadFrom(assemblyFile); foreach (var referencedAssembly in asm.GetReferencedAssemblies()) { Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"), "DesignTime assemblies should be embedded not referenced"); } } [DatapointSource] string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll"); string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location); }
mit
C#
0ae0c9bd8b4f82c01b7bf9bb599783f7ed015a2b
Add RequestVerification helper methods
stoiveyp/alexa-skills-dotnet,timheuer/alexa-skills-dotnet
Alexa.NET/Request/RequestVerification.cs
Alexa.NET/Request/RequestVerification.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Alexa.NET.Request { public class RequestVerification { public static async Task<bool> Verify(string encodedSignature, Uri certificatePath, string body) { if (!VerifyCertificateUrl(certificatePath)) { return false; } var certificate = await GetCertificate(certificatePath); if (!ValidSigningCertificate(certificate) || !VerifyChain(certificate)) { return false; } if (!AssertHashMatch(certificate, encodedSignature, body)) { return false; } return true; } public static bool AssertHashMatch(X509Certificate2 certificate, string encodedSignature, string body) { var signature = Convert.FromBase64String(encodedSignature); var rsa = certificate.GetRSAPublicKey(); return rsa.VerifyData(Encoding.UTF8.GetBytes(body), signature,HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); } public static async Task<X509Certificate2> GetCertificate(Uri certificatePath) { var response = await new HttpClient().GetAsync(certificatePath); var bytes = await response.Content.ReadAsByteArrayAsync(); return new X509Certificate2(bytes); } public static bool VerifyChain(X509Certificate2 certificate) { //https://stackoverflow.com/questions/24618798/automated-downloading-of-x509-certificatePath-chain-from-remote-host X509Chain certificateChain = new X509Chain(); //If you do not provide revokation information, use the following line. certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; return certificateChain.Build(certificate); } private static bool ValidSigningCertificate(X509Certificate2 certificate) { return DateTime.Now < certificate.NotAfter && DateTime.Now > certificate.NotBefore && certificate.GetNameInfo(X509NameType.SimpleName, false) == "echo-api.amazon.com"; } public static bool VerifyCertificateUrl(Uri certificate) { return certificate.Scheme == "https" && certificate.Host == "s3.amazonaws.com" && certificate.LocalPath.StartsWith("/echo.api") && certificate.IsDefaultPort; } } }
mit
C#
8618d9ea0d21ea9f67d9f2f3751c3b7cda08f614
Implement GrowToFitContainer
ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Graphics/Containers/GrowToFitContainer.cs
osu.Game/Graphics/Containers/GrowToFitContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that grows in size to fit its child and retains its size when its child shrinks /// </summary> public class GrowToFitContainer : Container { protected override void Update() { base.Update(); Height = Math.Max(Child.Height, Height); Width = Math.Max(Child.Width, Width); } } }
mit
C#
dbac9aff0ae7a3747d13de327b321b2ffc4f9e5f
Add missing model file.
robinsedlaczek/ModelR
WaveDev.ModelR.Shared/Models/TransformationInfoModel.cs
WaveDev.ModelR.Shared/Models/TransformationInfoModel.cs
namespace WaveDev.ModelR.Shared.Models { public class TransformationInfoModel { public float TranslateX { get; set; } public float TranslateY { get; set; } public float TranslateZ { get; set; } public float RotateX { get; set; } public float RotateY { get; set; } public float RotateZ { get; set; } public float ScaleX { get; set; } public float ScaleY { get; set; } public float ScaleZ { get; set; } } }
mit
C#
297b4d0f3e3b3e14d1c2a2a28d147d533ec7cba7
Add GetAllTiersQuery.cs
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.Contract/Queries/GetAllTiersQuery.cs
NinjaHive.Contract/Queries/GetAllTiersQuery.cs
using NinjaHive.Contract.Models; using NinjaHive.Core; namespace NinjaHive.Contract.Queries { public class GetAllTiersQuery : IQuery<TierModel[]> { } }
apache-2.0
C#
a9fea0c53306ba16808c8d584fa1c772be45cdd7
Create PerHttpRequestLifetimeManager.cs
rudini/UnityLifetimeManager
PerHttpRequestLifetimeManager.cs
PerHttpRequestLifetimeManager.cs
namespace Unity.LifetimeManager { using System; using System.Web; using Microsoft.Practices.Unity; /// <summary> /// Implements a Unity LifetimeManager to manage the lifecycle of a stateless http request. /// </summary> /// <remarks>This LifetimeManager disposes the resolved type after the http request has been ended. /// This LifetimeManager is not thread safe.</remarks> public class PerHttpRequestLifetimeManager : LifetimeManager { private readonly Guid key = Guid.NewGuid(); public override void RemoveValue() { var obj = this.GetValue(); HttpContext.Current.Items.Remove(obj); var disposable = obj as IDisposable; if (disposable != null) { disposable.Dispose(); } } public override object GetValue() { return HttpContext.Current.Items[this.key]; } public override void SetValue(object newValue) { HttpContext.Current.Items[this.key] = newValue; HttpContext.Current.AddOnRequestCompleted(delegate { this.RemoveValue(); }); } } }
apache-2.0
C#
00a1fdfd7ab43ccfe0c292409aee161b4025039b
add package class
tsolarin/dotnet-globals,tsolarin/dotnet-globals
src/DotNet.Executor.Core/Package.cs
src/DotNet.Executor.Core/Package.cs
namespace DotNet.Executor.Core { using System.IO; class Package { public DirectoryInfo Directory { get; set; } public string EntryAssemblyFileName { get; set; } } }
mit
C#
8b9b9dcd433675bffdfdae4689a6310f2ed376d6
Create AssemblyInfo.cs
keith-hall/Extensions,keith-hall/Extensions
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("Extensions")] [assembly: AssemblyDescription("Keith Hall's Extensions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Keith Hall")] [assembly: AssemblyProduct("Extensions")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3d1e0a56-5a64-4b45-ab64-2a811a4ec1e1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
f4e7509168a86c04faf2e22eee93fd8a8975af9b
Add SingletonMonoBehaviour.cs
felladrin/unity-scripts,felladrin/unity3d-scripts
SingletonMonoBehaviour.cs
SingletonMonoBehaviour.cs
using UnityEngine; public class SingletonMonoBehaviour<T> : MonoBehaviour where T : Component { public bool dontDestroyOnLoad; private static T instance; public static T Instance { get { if (instance != null) return instance; instance = FindObjectOfType<T>(); return instance != null ? instance : new GameObject {name = typeof(T).Name}.AddComponent<T>(); } } public virtual void Awake() { if (instance != null) { Destroy(gameObject); return; } instance = this as T; if (dontDestroyOnLoad) { DontDestroyOnLoad(gameObject); } } }
mit
C#
a1e32fda3f2681161866bb2a84fb7ab2129d12c9
Clean up file.
swaroop-sridhar/roslyn,a-ctor/roslyn,AlekseyTs/roslyn,dotnet/roslyn,AnthonyDGreen/roslyn,cston/roslyn,KevinH-MS/roslyn,gafter/roslyn,srivatsn/roslyn,akrisiun/roslyn,jasonmalinowski/roslyn,mattscheffer/roslyn,yeaicc/roslyn,gafter/roslyn,jkotas/roslyn,xasx/roslyn,ErikSchierboom/roslyn,CaptainHayashi/roslyn,amcasey/roslyn,dpoeschl/roslyn,jmarolf/roslyn,KevinRansom/roslyn,xasx/roslyn,TyOverby/roslyn,Hosch250/roslyn,sharwell/roslyn,DustinCampbell/roslyn,MattWindsor91/roslyn,panopticoncentral/roslyn,weltkante/roslyn,a-ctor/roslyn,sharwell/roslyn,tannergooding/roslyn,vslsnap/roslyn,agocke/roslyn,TyOverby/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,MattWindsor91/roslyn,davkean/roslyn,nguerrera/roslyn,tvand7093/roslyn,bkoelman/roslyn,eriawan/roslyn,heejaechang/roslyn,gafter/roslyn,mattscheffer/roslyn,jasonmalinowski/roslyn,aelij/roslyn,yeaicc/roslyn,drognanar/roslyn,OmarTawfik/roslyn,lorcanmooney/roslyn,AArnott/roslyn,cston/roslyn,kelltrick/roslyn,xoofx/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,vslsnap/roslyn,jkotas/roslyn,mmitche/roslyn,bkoelman/roslyn,AArnott/roslyn,VSadov/roslyn,OmarTawfik/roslyn,physhi/roslyn,brettfo/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,bbarry/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jcouv/roslyn,tmat/roslyn,sharwell/roslyn,agocke/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,kelltrick/roslyn,shyamnamboodiripad/roslyn,pdelvo/roslyn,panopticoncentral/roslyn,jamesqo/roslyn,CyrusNajmabadi/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AnthonyDGreen/roslyn,jeffanders/roslyn,jcouv/roslyn,bbarry/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,paulvanbrenk/roslyn,mattwar/roslyn,pdelvo/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,MattWindsor91/roslyn,dotnet/roslyn,genlu/roslyn,jmarolf/roslyn,tmat/roslyn,diryboy/roslyn,TyOverby/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,mattwar/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,heejaechang/roslyn,zooba/roslyn,bartdesmet/roslyn,AnthonyDGreen/roslyn,mmitche/roslyn,zooba/roslyn,dpoeschl/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,davkean/roslyn,aelij/roslyn,reaction1989/roslyn,genlu/roslyn,tmeschter/roslyn,xoofx/roslyn,jamesqo/roslyn,pdelvo/roslyn,Giftednewt/roslyn,khyperia/roslyn,wvdd007/roslyn,abock/roslyn,MichalStrehovsky/roslyn,akrisiun/roslyn,panopticoncentral/roslyn,a-ctor/roslyn,CaptainHayashi/roslyn,heejaechang/roslyn,drognanar/roslyn,weltkante/roslyn,bkoelman/roslyn,mavasani/roslyn,aelij/roslyn,KirillOsenkov/roslyn,VSadov/roslyn,mattwar/roslyn,nguerrera/roslyn,paulvanbrenk/roslyn,robinsedlaczek/roslyn,tannergooding/roslyn,agocke/roslyn,xoofx/roslyn,khyperia/roslyn,Hosch250/roslyn,physhi/roslyn,cston/roslyn,orthoxerox/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,CaptainHayashi/roslyn,orthoxerox/roslyn,davkean/roslyn,genlu/roslyn,KevinRansom/roslyn,khyperia/roslyn,jcouv/roslyn,brettfo/roslyn,abock/roslyn,jeffanders/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,VSadov/roslyn,jamesqo/roslyn,amcasey/roslyn,yeaicc/roslyn,bbarry/roslyn,drognanar/roslyn,zooba/roslyn,AmadeusW/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,kelltrick/roslyn,Giftednewt/roslyn,CyrusNajmabadi/roslyn,dpoeschl/roslyn,tvand7093/roslyn,KevinRansom/roslyn,physhi/roslyn,Giftednewt/roslyn,MichalStrehovsky/roslyn,vslsnap/roslyn,tannergooding/roslyn,orthoxerox/roslyn,AmadeusW/roslyn,stephentoub/roslyn,srivatsn/roslyn,AlekseyTs/roslyn,jeffanders/roslyn,abock/roslyn,tmeschter/roslyn,stephentoub/roslyn,MattWindsor91/roslyn,eriawan/roslyn,Hosch250/roslyn,KevinH-MS/roslyn,akrisiun/roslyn,mavasani/roslyn,tvand7093/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,KevinH-MS/roslyn,mattscheffer/roslyn,nguerrera/roslyn,lorcanmooney/roslyn,xasx/roslyn,robinsedlaczek/roslyn,paulvanbrenk/roslyn,eriawan/roslyn,diryboy/roslyn,jkotas/roslyn,tmat/roslyn,amcasey/roslyn,robinsedlaczek/roslyn,OmarTawfik/roslyn,AArnott/roslyn,srivatsn/roslyn,reaction1989/roslyn,mavasani/roslyn,lorcanmooney/roslyn,DustinCampbell/roslyn
src/Features/Core/Portable/Structure/BlockTypes.cs
src/Features/Core/Portable/Structure/BlockTypes.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. namespace Microsoft.CodeAnalysis.Structure { internal static class BlockTypes { // Basic types. public const string Nonstructural = nameof(Nonstructural); // Trivia public const string Comment = nameof(Comment); public const string PreprocessorRegion = nameof(PreprocessorRegion); // Top level declarations. public const string Imports = nameof(Imports); public const string Namespace = nameof(Namespace); public const string Class = nameof(Class); public const string Enum = nameof(Enum); public const string Interface = nameof(Interface); public const string Module = nameof(Module); public const string Structure = nameof(Structure); // Type level declarations. public const string Accessor = nameof(Accessor); public const string Constructor = nameof(Constructor); public const string Destructor = nameof(Destructor); public const string Event = nameof(Event); public const string Indexer = nameof(Indexer); public const string Method = nameof(Method); public const string Operator = nameof(Operator); public const string Property = nameof(Property); // Statements public const string Case = nameof(Case); public const string Conditional = nameof(Conditional); public const string LocalFunction = nameof(LocalFunction); public const string Lock = nameof(Lock); public const string Loop = nameof(Loop); public const string Standalone = nameof(Standalone); public const string Switch = nameof(Switch); public const string TryCatchFinally = nameof(TryCatchFinally); public const string Using = nameof(Using); public const string With = nameof(With); // Expressions public const string AnonymousMethod = nameof(AnonymousMethod); public const string Xml = nameof(Xml); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Structure { internal static class BlockTypes { // Basic types. public const string Nonstructural = nameof(Nonstructural); // Trivia public const string Comment = nameof(Comment); // public const string Region = nameof(Region); public const string PreprocessorRegion = nameof(PreprocessorRegion); // Top level declarations. public const string Imports = nameof(Imports); public const string Namespace = nameof(Namespace); public const string Class = nameof(Class); public const string Enum = nameof(Enum); public const string Interface = nameof(Interface); public const string Module = nameof(Module); public const string Structure = nameof(Structure); // Type level declarations. public const string Accessor = nameof(Accessor); public const string Constructor = nameof(Constructor); public const string Destructor = nameof(Destructor); public const string Event = nameof(Event); public const string Indexer = nameof(Indexer); public const string Method = nameof(Method); public const string Operator = nameof(Operator); public const string Property = nameof(Property); // Statements public const string Case = nameof(Case); public const string Conditional = nameof(Conditional); public const string LocalFunction = nameof(LocalFunction); public const string Lock = nameof(Lock); public const string Loop = nameof(Loop); public const string Standalone = nameof(Standalone); public const string Switch = nameof(Switch); public const string TryCatchFinally = nameof(TryCatchFinally); public const string Using = nameof(Using); public const string With = nameof(With); // Expressions public const string AnonymousMethod = nameof(AnonymousMethod); public const string Xml = nameof(Xml); // public const string Other = nameof(Other); } }
mit
C#
d5d1fbcf00d79683efcd14a96c9a896c8039b8bb
Create new CelestialBody from asteroid data
DMagic1/DMModuleScienceAnimateGeneric
Source/AsteroidScience.cs
Source/AsteroidScience.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace DMModuleScienceAnimateGeneric { public class AsteroidScience { protected DMModuleScienceAnimateGeneric ModSci = FlightGlobals.ActiveVessel.FindPartModulesImplementing<DMModuleScienceAnimateGeneric>().First(); //Let's make us some asteroid science //First construct a new celestial body from an asteroid public CelestialBody AsteroidBody = null; public CelestialBody Asteroid() { AsteroidBody = new CelestialBody(); AsteroidBody.bodyName = "Asteroid P2X-459"; AsteroidBody.use_The_InName = false; asteroidValues(AsteroidBody); return AsteroidBody; } public void asteroidValues(CelestialBody body) { //Find out how to vary based on asteroid size body.scienceValues.LandedDataValue = 10f; body.scienceValues.InSpaceLowDataValue = 4f; } public ExperimentSituations asteroidSituation() { if (asteroidGrappled()) return ExperimentSituations.SrfLanded; else if (asteroidNear()) return ExperimentSituations.InSpaceLow; else return ModSci.getSituation(); } //Are we attached to the asteroid public bool asteroidGrappled() { if (FlightGlobals.ActiveVessel.FindPartModulesImplementing<ModuleAsteroid>().Count >= 1) return true; else return false; } //Are we near the asteroid - need to figure this out public bool asteroidNear() { return false; } } }
bsd-2-clause
C#
bf1533fff3a36ee3b3efd7703ef96fa3e6f60dcb
Create AssemblyInfo.cs
AlexKoshulyan/NSDateToEpochTime
NSDateToEpochTime/Properties/AssemblyInfo.cs
NSDateToEpochTime/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("NSDateToEpochTime")] [assembly: AssemblyDescription("Convert NSDate To Epoch Time")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alex Koshulian")] [assembly: AssemblyProduct("NSDateToEpochTime")] [assembly: AssemblyCopyright("Alex Koshulian © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("86676ecb-73c3-4f67-93b0-5d792f6ef2cf")] // 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#
8cf1d8e579fb7ce65365f8aaa40ba39006b0b005
fix content nav links
napramirez/boxstarter,fhchina/boxstarter,modulexcite/boxstarter,cam1985/boxstarter,fhchina/boxstarter,cam1985/boxstarter,mwrock/boxstarter,napramirez/boxstarter,smaglio81/boxstarter,dhilgarth/boxstarter,tbyehl/boxstarter,smaglio81/boxstarter,modulexcite/boxstarter,fhchina/boxstarter,dex1on/pub,napramirez/boxstarter,dex1on/pub,mwrock/boxstarter,dex1on/pub,tbyehl/boxstarter,tbyehl/boxstarter,modulexcite/boxstarter,dhilgarth/boxstarter,cam1985/boxstarter,dhilgarth/boxstarter,smaglio81/boxstarter
Web/_ContentLayout.cshtml
Web/_ContentLayout.cshtml
@using System.Security.Policy @{ Layout = "~/_SiteLayout.cshtml"; var absPath = Request.Url.AbsolutePath; var thisPage = absPath.ToLower().Substring(absPath.LastIndexOf('/') + 1); PageData[thisPage + "Style"] = "active"; PageData["Documentation"] = "active"; } @section styles { @RenderSection("styles", required: false) } <div class="row"> <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation"> <div class="list-group"> <a href="WhyBoxstarter" class="list-group-item @PageData["whyBoxstarterStyle"]">Why Boxstarter?</a> <a href="WebLauncher" class="list-group-item @PageData["weblauncherStyle"]">Launch from the web</a> <a href="InstallBoxstarter" class="list-group-item @PageData["installboxstarterStyle"]">Installing Boxstarter</a> <a href="UsingBoxstarter" class="list-group-item @PageData["usingboxstarterStyle"]">Using Boxstarter Commands</a> <a href="UnderstandingPackages" class="list-group-item @PageData["understandingpackagesStyle"]">Understanding Packages</a> <a href="CreatingPackages" class="list-group-item @PageData["creatingpackagesStyle"]">Creating Packages</a> <a href="PublishingPackages" class="list-group-item @PageData["publishingpackagesStyle"]">Publishing Packages</a> <a href="InstallingPackages" class="list-group-item @PageData["installingpackagesStyle"]">Installing Packages</a> <a href="VMIntegration" class="list-group-item @PageData["VMIntegrationStyle"]">Installing packages on a Virtual Machine</a> <a href="TestingPackages" class="list-group-item @PageData["testingpackagesStyle"]">Testing Packages and Build Server Integration</a> <a href="WinConfig" class="list-group-item @PageData["winconfigStyle"]">Boxstarter WinConfig Features</a> <a href="BoxstarterResources" class="list-group-item @PageData["boxstarterresourcesStyle"]">More Boxstarter Resources</a> </div> </div> <div class="col-xs-6 col-md-9" role="main"> <div class="media"> <a class="pull-right" href="#"> <img class="media-object" src="~/images/boxlogo_sm.png"/> </a> <div class="media-body"> @RenderSection("headerBody") </div> </div> @RenderBody() </div> </div>
@using System.Security.Policy @{ Layout = "~/_SiteLayout.cshtml"; var absPath = Request.Url.AbsolutePath; var thisPage = absPath.ToLower().Substring(absPath.LastIndexOf('/') + 1); PageData[thisPage + "Style"] = "active"; PageData["Documentation"] = "active"; } @section styles { @RenderSection("styles", required: false) } <div class="row"> <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation"> <div class="list-group"> <a href="WhyBoxstarter" class="list-group-item @PageData["whyBoxstarterStyle"]">Why Boxstarter?</a> <a href="WebLauncher" class="list-group-item @PageData["weblauncherStyle"]">Launch from the web</a> <a href="InstallBoxstarter" class="list-group-item @PageData["installboxstarterStyle"]">Installing Boxstarter</a> <a href="UsingBoxstarter" class="list-group-item @PageData["usingboxstarterStyle"]">Using Boxstarter Commands</a> <a href="UnderstandingPackages" class="list-group-item @PageData["understandingpackagesStyle"]">Understanding Packages</a> <a href="CreatingPackages" class="list-group-item @PageData["creatingpackagesStyle"]">Creating Packages</a> <a href="PublishingPackages" class="list-group-item @PageData["publishingpackagesStyle"]">Publishing Packages</a> <a href="InstallingPackages" class="list-group-item @PageData["installingpackagesStyle"]">Installing Packages</a> <a href="VMIntegration" class="list-group-item @PageData["VMIntegrationStyle"]">Installing packages on a Virtual Machine</a> <a href="TestingPackages" class="list-group-item @PageData["testingpackagesStyle"]">Testing Packages and Build Server Integration</a> <a href="WinConfig" class="list-group-item @PageData["winconfigStyle"]">Boxstarter WinConfig Features</a> <a href="BoxstarterResources" class="list-group-item @PageData["boxstarterresourcesStyle"]">More Boxstarter Resources</a> </div> </div> <div class="col-md-9" role="main"> <div class="media"> <a class="pull-right" href="#"> <img class="media-object" src="~/images/boxlogo_sm.png"/> </a> <div class="media-body"> @RenderSection("headerBody") </div> </div> @RenderBody() </div> </div>
apache-2.0
C#
283492f308e984b81ab859cb65a75052d9654070
add WebApiSesionFactory
signumsoftware/framework,avifatal/framework,AlejandroCano/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework
Signum.React/Facades/WebApiSessionFactory.cs
Signum.React/Facades/WebApiSessionFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.WebHost; using System.Web.Routing; using System.Web.SessionState; using Signum.Utilities; namespace Signum.React { public class WebApiSesionFactory : ISessionFactory { static readonly ThreadVariable<HttpSessionState> overrideAspNetSessionVariable = Statics.ThreadVariable<HttpSessionState>("overrideASPNetSession"); //Usefull for Session_End http://stackoverflow.com/questions/464456/httpcontext-current-session-vs-global-asax-this-session public static IDisposable OverrideAspNetSession(HttpSessionState globalAsaxSession) { if (overrideAspNetSessionVariable.Value != null) throw new InvalidOperationException("overrideASPNetSession is already set"); overrideAspNetSessionVariable.Value = globalAsaxSession; return new Disposable(() => overrideAspNetSessionVariable.Value = null); } public SessionVariable<T> CreateVariable<T>(string name) { return new WebApiSessionVariable<T>(name); } public class WebApiSessionVariable<T> : SessionVariable<T> { public WebApiSessionVariable(string name) : base(name) { } public override Func<T> ValueFactory { get; set; } public override T Value { get { var session = HttpContext.Current?.Session; if (session == null) return default(T); object result = session[Name]; if (result != null) return (T)result; if (session.Keys.Cast<string>().Contains(Name)) return (T)result; return GetDefaulValue(); } set { (overrideAspNetSessionVariable.Value ?? HttpContext.Current.Session)[Name] = value; } } public override void Clean() { var session = overrideAspNetSessionVariable.Value ?? HttpContext.Current?.Session; session.Remove(Name); } } } // http://www.strathweb.com/2012/11/adding-session-support-to-asp-net-web-api/ public class SessionControllerHandler : HttpControllerHandler, IRequiresSessionState { public SessionControllerHandler(RouteData routeData) : base(routeData) { } } public class SessionRouteHandler : IRouteHandler { IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { return new SessionControllerHandler(requestContext.RouteData); } } }
mit
C#
ead0062e0985c432ffc7b57a15c3508c26226c72
Add test for BinarySearcher class
aalhour/C-Sharp-Algorithms
UnitTest/AlgorithmsTests/BinarySearcherTest.cs
UnitTest/AlgorithmsTests/BinarySearcherTest.cs
using System.Collections.Generic; using Xunit; using Algorithms.Search; namespace UnitTest.AlgorithmsTests { public static class BinarySearcherTest { [Fact] public static void MergeSortTest() { //a list of int IList<int> list = new List<int> {9, 3, 7, 1, 6, 10}; IList<int> sortedList = BinarySearcher.MergeSort<int>(list); IList<int> expectedList = new List<int> { 1, 3, 6, 7, 9, 10 }; Assert.Equal(expectedList, sortedList); //a list of strings IList<string> animals = new List<string> {"lion", "cat", "tiger", "bee"}; IList<string> sortedAnimals = BinarySearcher.MergeSort<string>(animals); IList<string> expectedAnimals = new List<string> {"bee", "cat", "lion", "tiger"}; Assert.Equal(expectedAnimals, sortedAnimals); } [Fact] public static void BinarySearchTest() { //list of ints IList<int> list = new List<int> { 9, 3, 7, 1, 6, 10 }; IList<int> sortedList = BinarySearcher.MergeSort<int>(list); int itemIndex = BinarySearcher.BinarySearch<int>(list, 6); int expectedIndex = sortedList.IndexOf(6); Assert.Equal(expectedIndex, itemIndex); //list of strings IList<string> animals = new List<string> {"lion", "cat", "tiger", "bee", "sparrow"}; IList<string> sortedAnimals = BinarySearcher.MergeSort<string>(animals); int actualIndex = BinarySearcher.BinarySearch<string>(animals, "cat"); int expectedAnimalIndex = sortedAnimals.IndexOf("cat"); Assert.Equal(expectedAnimalIndex, actualIndex); } [Fact] public static void NullCollectionExceptionTest() { IList<int> list = null; Assert.Throws<System.NullReferenceException>(() => BinarySearcher.BinarySearch<int>(list,0)); } } }
mit
C#
0ecbc5945f3a93914756d42baf459bc2a9cd14c9
Adjust transform to look better
ZLima12/osu,smoogipooo/osu,UselessToucan/osu,DrabWeb/osu,naoey/osu,DrabWeb/osu,peppy/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,naoey/osu,DrabWeb/osu,ppy/osu,johnneijzen/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,naoey/osu,NeoAdonis/osu,2yangk23/osu,peppy/osu,ppy/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu
osu.Game/Graphics/Containers/ShakeContainer.cs
osu.Game/Graphics/Containers/ShakeContainer.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { public class ShakeContainer : Container { public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // 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.Graphics.Containers { public class ShakeContainer : Container { public void Shake() { const int shake_amount = 8; const int shake_duration = 20; this.MoveToX(shake_amount, shake_duration).Then() .MoveToX(-shake_amount, shake_duration).Then() .MoveToX(shake_amount, shake_duration).Then() .MoveToX(-shake_amount, shake_duration).Then() .MoveToX(shake_amount, shake_duration).Then() .MoveToX(0, shake_duration); } } }
mit
C#
478ba08b80cb4d2730fb5808f8f91c781c167ecc
Create PacBuilder.cs
imba-tjd/CSharp-Code-Repository
单个文件的程序/PacBuilder.cs
单个文件的程序/PacBuilder.cs
using System; using System.IO; using System.Collections.Generic; class PacBuilder { const string BLACKLISTPATH = "blacklist.txt"; const string WHITELISTPATH = "whitelist.txt"; const string FINDPROXY = @" var proxy = '__PROXY__'; var direct = 'DIRECT;'; var hop = Object.hasOwnProperty; function FindProxyForURL(url, host) { if(hop.call(whitelist, host)) return direct; var suffix; var pos = host.lastIndexOf('.'); pos = host.lastIndexOf('.', pos - 1); while(1) { if (pos <= 0) { if (hop.call(blacklist, host)) return proxy; else return direct; } suffix = host.substring(pos + 1); if (hop.call(blacklist, suffix)) return proxy; pos = host.lastIndexOf('.', pos - 1); } }"; const string FINDPROXYMINIFY = "var proxy='__PROXY__',direct='DIRECT;',hop=Object.hasOwnProperty;function FindProxyForURL(r,t){if(hop.call(whitelist,t))return direct;var l,i=t.lastIndexOf('.');for(i=t.lastIndexOf('.',i-1);;){if(i<=0)return hop.call(blacklist,t)?proxy:direct;if(l=t.substring(i+1),hop.call(blacklist,l))return proxy;i=t.lastIndexOf('.',i-1)}}"; static void Main() { try { string[] userBlackList = File.ReadAllLines(BLACKLISTPATH); string[] userWhiteList = File.ReadAllLines(WHITELISTPATH); string blackList = "blacklist = " + GetStringiObj(userBlackList); string whiteList = "whitelist = " + GetStringiObj(userWhiteList); if (File.Exists("pac.txt")) File.Copy("pac.txt", "pac.txt.bak", true); File.WriteAllText("pac.txt", blackList + whiteList + FINDPROXYMINIFY); } catch (Exception ex) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); Console.ForegroundColor = color; Console.ReadKey(); } } static string GetStringiObj(IEnumerable<string> list) => "JSON.parse('{" + string.Join(",", ObjItemfy(list)) + "}');\n"; static string ObjItemfy(string str) => string.Format("\"{0}\":null", str.IndexOf("//") is var i && i != -1 ? str.Substring(0, i).TrimEnd() : str); static IEnumerable<string> ObjItemfy(IEnumerable<string> strs) { foreach (var str in strs) if (str.Trim() is var s && s != string.Empty && !s.StartsWith("//")) yield return ObjItemfy(s); } }
mit
C#
08bb5cbcbff6e1b42fa1715224aa989cd308b073
Introduce model to store path of stable osu!
UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,ppy/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,ppy/osu
osu.Game.Tournament/Models/StableInfo.cs
osu.Game.Tournament/Models/StableInfo.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; namespace osu.Game.Tournament.Models { /// <summary> /// Holds the complete data required to operate the tournament system. /// </summary> [Serializable] public class StableInfo { public Bindable<string> StablePath = new Bindable<string>(string.Empty); } }
mit
C#
2624949152b59186dacc9943e4310741ba47178b
add language domain model
mzrimsek/resume-site-api
Core/Models/LanguageDomainModel.cs
Core/Models/LanguageDomainModel.cs
namespace Core.Models { public class LanguageDomainModel { public int Id { get; set; } public string Name { get; set; } public int Rating { get; set; } } }
mit
C#
e3bdb16fd648e1a16d1432c8f61cd142c2107ad6
add Upgrade_20220204_UpdateNugets
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20220204_UpdateNugets.cs
Signum.Upgrade/Upgrades/Upgrade_20220204_UpdateNugets.cs
namespace Signum.Upgrade.Upgrades; class Upgrade_20220204_UpdateNugets : CodeUpgradeBase { public override string Description => "Update Nugets"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"*.csproj", file => { file.UpdateNugetReference("Microsoft.Identity.Client", "4.40.0"); file.UpdateNugetReference("Selenium.WebDriver.ChromeDriver", "98.0.4758.8000"); }); } }
mit
C#
77361347482de79a9a65a64bb7ecf1ec86c8556e
Add the support for autoscale SCPI command
tparviainen/oscilloscope
SCPI/AUTOSCALE.cs
SCPI/AUTOSCALE.cs
using System; using System.Collections.Generic; using System.Text; namespace SCPI { public class AUTOSCALE : ICommand { public string Description => "The oscilloscope will automatically adjust the vertical scale, horizontal timebase, and trigger mode according to the input signal to realize optimum waveform display"; public string Command(params string[] parameters) => ":AUToscale"; public string HelpMessage() => nameof(AUTOSCALE); public bool Parse(byte[] data) => true; } }
mit
C#
8e34cc2c5f9942122f0f14616a8d7379d386c615
Allow even more button customisation.
RedNesto/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,RedNesto/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,default0/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,Tom94/osu-framework,default0/osu-framework,ZLima12/osu-framework,naoey/osu-framework,naoey/osu-framework
osu.Framework/Graphics/UserInterface/Button.cs
osu.Framework/Graphics/UserInterface/Button.cs
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Input; using OpenTK.Graphics; using osu.Framework.Allocation; namespace osu.Framework.Graphics.UserInterface { public class Button : ClickableContainer { public string Text { get { return SpriteText?.Text; } set { if (SpriteText != null) SpriteText.Text = value; } } public new Color4 Colour { get { return Background.Colour; } set { Background.Colour = value; } } protected Box Background; protected SpriteText SpriteText; public Button() { Children = new Drawable[] { Background = new Box { RelativeSizeAxes = Axes.Both, }, SpriteText = CreateText(), }; } protected virtual SpriteText CreateText() => new SpriteText { Depth = -1, Origin = Anchor.Centre, Anchor = Anchor.Centre, }; protected override bool OnClick(InputState state) { var flash = new Box { RelativeSizeAxes = Axes.Both }; Add(flash); flash.Colour = Background.Colour; flash.BlendingMode = BlendingMode.Additive; flash.Alpha = 0.3f; flash.FadeOutFromOne(200); flash.Expire(); return base.OnClick(state); } } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Input; using OpenTK.Graphics; using osu.Framework.Allocation; namespace osu.Framework.Graphics.UserInterface { public class Button : ClickableContainer { public string Text { get { return SpriteText?.Text; } set { if (SpriteText != null) SpriteText.Text = value; } } public new Color4 Colour { get { return Background.Colour; } set { Background.Colour = value; } } protected Box Background; protected SpriteText SpriteText; public Button() { Children = new Drawable[] { Background = new Box { RelativeSizeAxes = Axes.Both, }, SpriteText = new SpriteText { Depth = -1, Origin = Anchor.Centre, Anchor = Anchor.Centre, } }; } protected override bool OnClick(InputState state) { var flash = new Box { RelativeSizeAxes = Axes.Both }; Add(flash); flash.Colour = Background.Colour; flash.BlendingMode = BlendingMode.Additive; flash.Alpha = 0.3f; flash.FadeOutFromOne(200); flash.Expire(); return base.OnClick(state); } } }
mit
C#
323afcc1402b0db7844d54a91d1ee4a70cebfc69
Add `PcscConnection` class
Archie-Yang/PcscDotNet
src/PcscDotNet/PcscConnection.cs
src/PcscDotNet/PcscConnection.cs
namespace PcscDotNet { public class PcscConnection { public PcscContext Context { get; private set; } public IPcscProvider Provider { get; private set; } public string ReaderName { get; private set; } public PcscConnection(PcscContext context, string readerName) { Provider = (Context = context).Provider; ReaderName = readerName; } } }
mit
C#
1e297a1a3799a9123b83bddef4fe5d69db5b0408
Add PdfWriterExtensions
Codinlab/PDF-SDK
src/DocumentFormat.Pdf/Extensions/PdfWriterExtensions.cs
src/DocumentFormat.Pdf/Extensions/PdfWriterExtensions.cs
using DocumentFormat.Pdf.IO; using System; using System.Collections.Generic; using System.Text; namespace DocumentFormat.Pdf.Extensions { /// <summary> /// <see cref="PdfWriter"/> extension methods. /// </summary> public static class PdfWriterExtensions { /// <summary> /// Writes a comment to the PDF stream. /// </summary> /// <param name="writer">The <see cref="PdfWriter"/> to use.</param> /// <param name="comment">The comment to write.</param> public static void WriteComment(this PdfWriter writer, string comment) { if (writer == null) throw new ArgumentNullException(nameof(writer)); var lines = comment.Split(new char[] { Chars.CR, Chars.LF }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { writer.Write('%'); writer.WriteLine(line); } } } }
mit
C#
0450333cc139db37e68f2ab75dbf4850fa17e3d0
Fix for applying properties.
cube-soft/Cube.Core,cube-soft/Cube.Core
Triggers/UpdateSourcesAction.cs
Triggers/UpdateSourcesAction.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, 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.Windows; using System.Windows.Interactivity; namespace Cube.Xui.Triggers { /* --------------------------------------------------------------------- */ /// /// UpdateSources /// /// <summary> /// UpdateSources を実行する事を表すメッセージです。 /// </summary> /// /* --------------------------------------------------------------------- */ public class UpdateSourcesMessage { } /* --------------------------------------------------------------------- */ /// /// UpdateSourcesTrigger /// /// <summary> /// Messenger オブジェクト経由で UpdateSources を実行するための /// Trigger クラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ public class UpdateSourcesTrigger : MessengerTrigger<UpdateSourcesMessage> { } /* --------------------------------------------------------------------- */ /// /// UpdateSourcesAction /// /// <summary> /// UpdateSources を実行する TriggerAction です。 /// </summary> /// /* --------------------------------------------------------------------- */ public class UpdateSourcesAction : TriggerAction<DependencyObject> { /* ----------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// 処理を実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ protected override void Invoke(object notused) { if (AssociatedObject is Window w) w.BindingGroup.UpdateSources(); } } }
apache-2.0
C#
1f5e15807658a72e6b2bc4d40dd4eb439d512984
Create Tetris.cs
dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey
C#/Uni-Ruse/Internet-Programming/Exercise2/Tetris.cs
C#/Uni-Ruse/Internet-Programming/Exercise2/Tetris.cs
using System; namespace InternetProgramming { class Program { static BaseFigure[] figures = new BaseFigure[10]; static Random rand = new Random(); const int COLOR_MIN_VALUE = 7; const int COLOR_MAX_VALUE = 15; const int X_MIN_VALUE = 10; const int X_MAX_VALUE = 70; const int Y_MIN_VALUE = 0; const int Y_MAX_VALUE = 20; enum FigureType { //IFigure, //JFigure, //LFigure, OFigure, //ZFigure, //TFigure, //SFigure } static BaseFigure getRandomFigure(bool top = false) { int randomColor = rand.Next(COLOR_MIN_VALUE, COLOR_MAX_VALUE + 1); int randomX = rand.Next(X_MIN_VALUE, X_MAX_VALUE + 1); int y; if (top == false) { y = rand.Next(Y_MIN_VALUE, Y_MAX_VALUE + 1); } else { y = 1; } Array figureTypes = Enum.GetValues( typeof(FigureType) ); FigureType randomFigure = (FigureType) figureTypes.GetValue( rand.Next(figureTypes.Length) ); switch (randomFigure) { case (FigureType.OFigure): return new OFigure(randomColor, randomX, y); default: return null; } } static void Main(string[] args) { BaseFigure o = getRandomFigure(); o.drawFigure(); Console.ReadKey(); } } abstract class BaseFigure { protected int color; protected int x; public int Y { get; set; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public int X { get { return x; } set { if (value <= 0) { throw new ArgumentNullException("X", "x must be greater than 0"); } x = value; } } public BaseFigure(int color, int x, int y) { this.color = color; this.x = x; this.Y = y; } abstract public void drawFigure(); } class OFigure : BaseFigure { public OFigure(int color, int x, int y) : base(color, x, y) { } public override void drawFigure() { Console.ForegroundColor = (ConsoleColor) getColor(); Console.BackgroundColor = (ConsoleColor) getColor(); Console.CursorLeft = X; Console.CursorTop = Y; Console.Write("*"); Console.CursorLeft = X + 1; Console.CursorTop = Y; Console.Write("*"); Console.CursorLeft = X; Console.CursorTop = Y + 1; Console.Write("*"); Console.CursorLeft = X + 1; Console.CursorTop = Y + 1; Console.Write("*"); } } }
mit
C#
512b84d2108fcf23285abdf36a549fc666d7a8cc
Create custom authorize attribute
MarioZisov/Baskerville,MarioZisov/Baskerville,MarioZisov/Baskerville
BaskervilleWebsite/Baskerville.App/Attributes/CustomAuthorizeAttribute.cs
BaskervilleWebsite/Baskerville.App/Attributes/CustomAuthorizeAttribute.cs
using System.Linq; using System.Web.Mvc; using System.Web.Routing; namespace Baskerville.App.Attributes { public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { area = "admin", controller = "account", action = "login" })); } else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { filterContext.Result = new ViewResult { ViewName = "~/Areas/Admin/Views/Main/Index.cshtml" }; } else { base.HandleUnauthorizedRequest(filterContext); } } } }
apache-2.0
C#
c20c8ce4fe6e27166937a4bf1763746822827150
Create Button.cs
Eversm4nn/Project
GTE/GTE/GTE/GTE/Button.cs
GTE/GTE/GTE/GTE/Button.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace GTE { public class Button { #region FIELDS public Texture2D texture; public Vector2 position; public Rectangle rectangle; public Vector2 size; Color color = new Color(255, 255, 255); public bool overlay; public bool isClicked; #endregion #region CONSTRUCTOR public Button(Texture2D texture, GraphicsDevice graphics) { this.texture = texture; size = new Vector2(graphics.Viewport.Width / 8, graphics.Viewport.Height / 10); } #endregion #region METHODS public void setPosition(Vector2 newPosition) { this.position = newPosition; } public void Update(MouseState mouse) { rectangle = new Rectangle((int)position.X, (int)position.Y, (int)size.X, (int)size.Y); Rectangle mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1); if (mouseRectangle.Intersects(rectangle)) { if (mouse.LeftButton == ButtonState.Pressed) isClicked = true; if (color.A == 255) overlay = false; if (color.A == 0) overlay = true; if (overlay) color.A += 3; else color.A -= 3; } else if (color.A < 255) { color.A += 3; isClicked = false; } } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, rectangle, color); } #endregion } }
unlicense
C#
b1b4d08bf2a9dafaffc5c5eaed8435cbc1e7a1eb
Create HaiTun_.cs
daobude/-
HaiTun_.cs
HaiTun_.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("LSharp海豚防封")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LSharp海豚防封")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("30bbd284-2bda-402a-aa5e-0d243f67a810")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
isc
C#
95a7c821fdb441994388728812eea9a36ce34ffa
add v1 tracer interface so we can break out tracing (#523)
geffzhang/Ocelot,TomPallister/Ocelot,geffzhang/Ocelot,TomPallister/Ocelot
src/Ocelot/Logging/ITracer.cs
src/Ocelot/Logging/ITracer.cs
namespace Ocelot.Logging { using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; public interface ITracer { void Event(HttpContext httpContext, string @event); Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken, Action<string> addTraceIdToRepo, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> baseSendAsync); } }
mit
C#
aef6c5504b96d5ecf6ae43ea11e91efe317a0f19
Add ConfigSectionAttribute
RockFramework/RockLib.Configuration
RockLib.Configuration.ObjectFactory/ConfigSectionAttribute.cs
RockLib.Configuration.ObjectFactory/ConfigSectionAttribute.cs
using System; namespace RockLib.Configuration.ObjectFactory { /// <summary> /// Associates the path to a configuration section with a target type. The contents /// of such a configuration section should declare an object of the target type. /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class ConfigSectionAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="ConfigSectionAttribute"/> class, /// associating the specified path to a configuration section with the specified type. /// The contents of such a configuration section should declare an object of the target type. /// </summary> /// <param name="path"> /// The path to a target configuration section. The contents of such a configuration /// section should declare an object of the type of the <paramref name="type"/> parameter. /// </param> /// <param name="type"> /// The type of object that should be able to be created using a configuration section /// specified by the <paramref name="path"/> parameter. /// </param> public ConfigSectionAttribute(string path, Type type) { Path = path ?? throw new ArgumentNullException(nameof(path)); Type = type ?? throw new ArgumentNullException(nameof(type)); } /// <summary> /// Gets the path to a target configuration section. The contents of such a configuration /// section should declare an object of the type of the <see cref="Type"/> property. /// </summary> public string Path { get; } /// <summary> /// Gets the type of object that should be able to be created using a configuration section /// specified by the <see cref="Path"/> property. /// </summary> public Type Type { get; } } }
mit
C#
945e230466f58e4ce64969e89f15b4b08b0d26ae
Create XMLData.cs
alchemz/Unity_Read_XML_With_CSharp
XMLData.cs
XMLData.cs
public class XMLData{ public int pageNum; public string CharText, dialogueText; public XMLData(int page, string character, string dialogue) { pageNum=page; charText=character; dialogueText=dialogue; } }
mit
C#
9da9edf2eb2d0af1b39abe73726daf019e9337de
Create GrabDesktop.cs
UnityCommunity/UnityLibrary
Scripts/Helpers/Screenshot/GrabDesktop.cs
Scripts/Helpers/Screenshot/GrabDesktop.cs
using UnityEngine; using System.Collections; using System.Drawing; using Screen = System.Windows.Forms.Screen; using Application = UnityEngine.Application; using System.Drawing.Imaging; // Drag windows desktop image using System.Drawing.dll // guide on using System.Drawing.dll in unity : http://answers.unity3d.com/answers/253571/view.html public class GrabDesktop : MonoBehaviour { void Start() { // screenshot source: http://stackoverflow.com/a/363008/5452781 //Create a new bitmap. var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); // Create a graphics object from the bitmap. var gfxScreenshot = System.Drawing.Graphics.FromImage(bmpScreenshot); // Take the screenshot from the upper left corner to the right bottom corner. gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); // Save the screenshot to the specified path that the user has chosen. bmpScreenshot.Save(Application.dataPath + "/Screenshot.png", ImageFormat.Png); } }
mit
C#
04033146ddc42f60e0fdd3ab1bf5de3aa0bc9f32
Create TemplateVariableParser for Unity templates
mubeeniqbal/unity-setup
project-resources/Assets/Editor/TemplateVariableParser.cs
project-resources/Assets/Editor/TemplateVariableParser.cs
/** * @file TemplateVariableParser.cs * @date 2014-12-16 20:01:34 UTC+05:00 * @author Mubeen Iqbal <mubeen.ace@gmail.com> * @license MIT <http://opensource.org/licenses/MIT> * * @description * Destination path: $PROJECT_HOME/Assets/Editor/TemplateVariableParser.cs * * $PROJECT_HOME is the directory where the Unity project is created. This script must be placed only inside a Unity * project in $PROJECT_HOME/Assets/Editor/ directory. Since this is a Unity editor script it needs to be inside the * "Editor" directory. * * By default Unity templates don't support many template variables. A few supported variables are: * * #NAME# * #SCRIPTNAME# * * And there might be others but very very few. * * The purpose of this script is to add support for more template variables to Unity templates. The script will replace * the script template variables with their corresponding values for every new script created by Unity based on Unity's * templates. That is, when you create a file from within Unity e.g. when you right-click in Unity's project browser and * create a C# script (right-click > Create > C# Script) the template variables in Unity's C# script template from which * Unity is going to create the new C# script will be replaced with their values in the newly created C# script. * * The added template variables are given in the "TemplateVariables" region in the code. Any number of template * variables can be added. * * The naming convention being followed for the template variables is: * * #<variable_name># * * variable_name * A string in uppercase using underscore as space separator. * * You can modify Unity templates by putting in the template variables in the template files. * * For example you can add comments to the C# template like so: * * // @author #AUTHOR# <#AUTHOR_EMAIL#> * // @date #DATE# * * and whenever you will create a C# script from within Unity it will have the comments like so: * * // @author Linus Torvalds <torvalds@kruuna.helsinki.fi> * // @date 1991-08-25 10:05:46 UTC+02:00 */ using UnityEngine; using UnityEditor; using System.Collections; // TODO(mubeeniqbal): Separate out configuration/values into a text file rather than providing values here in code. Use // an associative array/dictionary created by reading values from the text file and loop through that array to // configure/replace the template variables with their values. public class TemplateVariableParser : UnityEditor.AssetModificationProcessor { // public: public static void OnWillCreateAsset(string path) { #region TemplateVariables string DATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss UTCzzz"); string YEAR = System.DateTime.Now.ToString("yyyy"); string MONTH = System.DateTime.Now.ToString("MM"); string DAY = System.DateTime.Now.ToString("dd"); string TIME = System.DateTime.Now.ToString("HH:mm:ss"); string HOUR = System.DateTime.Now.ToString("HH"); string MINUTE = System.DateTime.Now.ToString("mm"); string SECOND = System.DateTime.Now.ToString("ss"); string UTC_OFFSET = System.DateTime.Now.ToString("zzz"); string AUTHOR = "FirstName LastName"; string AUTHOR_EMAIL = "author@email.com"; string PRODUCT = PlayerSettings.productName; string LICENSE = "[license_name]"; string LICENSE_URL = "http://license.url"; string COMPANY = PlayerSettings.companyName; string COMPANY_URL = "http://company.url"; string COMPANY_EMAIL = "company@email.com"; string DESCRIPTION = "[add_description_here]"; #endregion path = path.Replace(".meta", ""); int index = path.LastIndexOf("."); string file = path.Substring(index); if ((file != ".cs") && (file != ".js") && (file != ".boo")) { return; } index = Application.dataPath.LastIndexOf("Assets"); path = Application.dataPath.Substring(0, index) + path; file = System.IO.File.ReadAllText(path); file = file.Replace("#DATE#", DATE); file = file.Replace("#YEAR#", YEAR); file = file.Replace("#MONTH#", MONTH); file = file.Replace("#DAY#", DAY); file = file.Replace("#TIME#", TIME); file = file.Replace("#HOUR#", HOUR); file = file.Replace("#MINUTE#", MINUTE); file = file.Replace("#SECOND#", SECOND); file = file.Replace("#UTC_OFFSET#", UTC_OFFSET); file = file.Replace("#AUTHOR#", AUTHOR); file = file.Replace("#AUTHOR_EMAIL#", AUTHOR_EMAIL); file = file.Replace("#PRODUCT#", PRODUCT); file = file.Replace("#LICENSE#", LICENSE); file = file.Replace("#LICENSE_URL#", LICENSE_URL); file = file.Replace("#COMPANY#", COMPANY); file = file.Replace("#COMPANY_URL#", COMPANY_URL); file = file.Replace("#COMPANY_EMAIL#", COMPANY_EMAIL); file = file.Replace("#DESCRIPTION#", DESCRIPTION); System.IO.File.WriteAllText(path, file); AssetDatabase.Refresh(); } }
mit
C#
cbf86f107db4bcdf61159abbb305a22834c0271a
Fix typo: Arrary --> Array
joehmchan/elasticsearch-net,gayancc/elasticsearch-net,gayancc/elasticsearch-net,robrich/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,gayancc/elasticsearch-net,robertlyson/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,joehmchan/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,robrich/elasticsearch-net,joehmchan/elasticsearch-net
src/Nest/Domain/Property.cs
src/Nest/Domain/Property.cs
using System; using System.Linq.Expressions; namespace Nest.Resolvers { public static class Property { /// <summary> /// Create a strongly typed string representation of the path to a property /// <para>i.e p => p.Array.First().SubProperty.Field will return 'array.subProperty.field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyPathMarker Path<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyPathMarker.Create(path, boost); } /// <summary> /// Create a strongly typed string representation of the name to a property /// <para>i.e p => p.Array.First().SubProperty.Field will return 'field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyNameMarker Name<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyNameMarker.Create(path, boost); } } }
using System; using System.Linq.Expressions; namespace Nest.Resolvers { public static class Property { /// <summary> /// Create a strongly typed string representation of the path to a property /// <para>i.e p => p.Arrary.First().SubProperty.Field will return 'array.subProperty.field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyPathMarker Path<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyPathMarker.Create(path, boost); } /// <summary> /// Create a strongly typed string representation of the name to a property /// <para>i.e p => p.Arrary.First().SubProperty.Field will return 'field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyNameMarker Name<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyNameMarker.Create(path, boost); } } }
apache-2.0
C#
0ebf4a1eb4be72e840388139cac725d851f17a32
add basetest
vip32/eventfeedback,vip32/eventfeedback,vip32/eventfeedback,vip32/eventfeedback
Web.App.IntegrationTests/Views/BaseViewTests.cs
Web.App.IntegrationTests/Views/BaseViewTests.cs
using System; using Coypu; using Coypu.Drivers.Selenium; namespace Eventfeedback.Web.App.IntegrationTests.UI { public class BaseViewTests { public Settings Settings = new Settings(); public Views Views = new Views(); public void Do(Action<BrowserSession> action) { using (var browser = new BrowserSession(new SessionConfiguration { Driver = typeof(SeleniumWebDriver), Browser = Coypu.Drivers.Browser.Chrome, AppHost = Settings.AppHost, Port = Settings.Port, SSL = Settings.SSL })) { action(browser); } } } }
mit
C#
7dd677e2bb0e04088a1dbf4dbd81e1e2fcf095b3
Create Debug.cs
Gianxs/CitiesSkylineFavoriteCimsMod
Debug.cs
Debug.cs
using UnityEngine; using System; using System.Collections.Generic; using ColossalFramework; using ColossalFramework.UI; namespace FavoriteCims { public static class Debug { const string prefix = "FavoriteCimsMod: "; public static void Log(String message) { DebugOutputPanel.AddMessage(ColossalFramework.Plugins.PluginManager.MessageType.Message, prefix + message); } public static void Error(String message) { DebugOutputPanel.AddMessage(ColossalFramework.Plugins.PluginManager.MessageType.Error, prefix + message); } public static void Warning(String message) { DebugOutputPanel.AddMessage(ColossalFramework.Plugins.PluginManager.MessageType.Warning, prefix + message); } public static bool withoutflood = false; } public static class GuiDebug { public static void Log(String message) { UIPanel FullScrCont = UIView.Find<UIPanel> ("FullScreenContainer"); UILabel Label; if (FullScrCont != null) { if (FullScrCont.Find<UILabel> ("FavCimsDebugLabel") == null) { Label = FullScrCont.AddUIComponent<UILabel> (); Label.name = "FavCimsDebugLabel"; Label.width = 700; Label.height = 300; Label.relativePosition = new Vector3 (200, 20); //Label.wordWrap = true; } else { Label = FullScrCont.Find<UILabel> ("FavCimsDebugLabel"); } Label.text = message; } } public static void Destroy() { UIPanel FullScrCont = UIView.Find<UIPanel> ("FullScreenContainer"); if (FullScrCont.Find<UILabel> ("FavCimsDebugLabel") != null) GameObject.Destroy (FullScrCont.Find<UILabel> ("FavCimsDebugLabel").gameObject); } } public static class GameTime { public static string FavCimsDate(string format, string oldformat) { if (Singleton<SimulationManager>.exists) { string d = Singleton<SimulationManager>.instance.m_currentGameTime.Date.Day.ToString (); string m = Singleton<SimulationManager>.instance.m_currentGameTime.Date.Month.ToString (); string y = Singleton<SimulationManager>.instance.m_currentGameTime.Date.Year.ToString (); if(oldformat != "n/a") { string[] elements = oldformat.Split('/'); if(elements[0] != null && elements[1] != null && elements[2] != null) { return elements[1] + "/" + elements[0] + "/" + elements[2]; } return oldformat; }else if (format == "dd-mm-yyyy") { return d + "/" + m + "/" + y; } else { return m + "/" + d + "/" + y; } } return format; } public static string FavCimsTime() { string h = Singleton<SimulationManager>.instance.m_currentGameTime.Hour.ToString (); string m = Singleton<SimulationManager>.instance.m_currentGameTime.Minute.ToString (); if (h.Length == 1) { h = "0" + h; } if (m.Length == 1) { m = "0" + m; } return h + ":" + m; } } }
mit
C#
d44a6470cdb4c91212472564cd5170813400a6f8
Add missing file
paiden/Nett
Source/Nett/TomlConfig.Builder.cs
Source/Nett/TomlConfig.Builder.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Nett { public sealed partial class TomlConfig { public IFrom AddConversion() { return new From(this); } private class From : IFrom { private readonly TomlConfig config; public From(TomlConfig config) { Debug.Assert(config != null); this.config = config; } public Type FromType { get; private set; } ITo<T> IFrom.From<T>() { return new To<T>(this.config); } } private sealed class To<TFrom> : ITo<TFrom> { private readonly TomlConfig config; public To(TomlConfig config) { Debug.Assert(config != null); this.config = config; } IAs<TFrom, T> ITo<TFrom>.To<T>() { return new As<TFrom, T>(this.config); } } internal sealed class As<TFrom, TTo> : IAs<TFrom, TTo> { private readonly TomlConfig config; public As(TomlConfig config) { Debug.Assert(config != null); this.config = config; } TomlConfig IAs<TFrom, TTo>.As(Func<TFrom, TTo> convert) { var conv = new TomlConverter<TFrom, TTo>(convert); this.config.AddConverter(conv); return this.config; } } } public interface IFrom { ITo<T> From<T>(); } public interface ITo<TFrom> { IAs<TFrom, T> To<T>(); } public interface IAs<TFrom, TTo> { TomlConfig As(Func<TFrom, TTo> convert); } }
mit
C#
662a3cef9bf9f16b68f514730522d6bd5f78b88f
add pass through encoder that can specify its own name
IxMilia/Pdf,IxMilia/Pdf
src/IxMilia.Pdf/Encoders/CustomPassThroughEncoder.cs
src/IxMilia.Pdf/Encoders/CustomPassThroughEncoder.cs
namespace IxMilia.Pdf.Encoders { public class CustomPassThroughEncoder : IPdfEncoder { public string DisplayName { get; private set; } public CustomPassThroughEncoder(string displayName) { DisplayName = displayName; } public byte[] Encode(byte[] data) { return data; } } }
apache-2.0
C#
7bbe81631c7c53a74d2ebc0d57a32022c4ee8774
Create StringExtensions.cs
dpvreony/Dhgms.AspNetCoreContrib,dpvreony/Dhgms.AspNetCoreContrib,dpvreony/Dhgms.AspNetCoreContrib
src/Whipstaff.Runtime/Extensions/StringExtensions.cs
src/Whipstaff.Runtime/Extensions/StringExtensions.cs
// Copyright (c) 2020 DHGMS Solutions and Contributors. All rights reserved. // DHGMS Solutions and Contributors licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; namespace Dhgms.NetContrib.UnitTests.Features.Extensions { /// <summary> /// Extensions for String manipulation. /// </summary> public static class StringExtensions { /// <summary> /// Removes all instances of a string. /// </summary> /// <param name="instance">The string to work on.</param> /// <param name="value">The string to remove.</param> /// <param name="ignoreCase">Whether to ignore the case, or be case-sensitive.</param> /// <returns>Altered string.</returns> public static string Remove( this string instance, string value, bool ignoreCase = true) { return instance.Replace( value, string.Empty, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } }
apache-2.0
C#
8dfc02a85c2649246c9798c191e898f04f475fb6
Add IEasingFunction interface
EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Graphics/Transforms/IEasingFunction.cs
osu.Framework/Graphics/Transforms/IEasingFunction.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Graphics.Transforms { /// <summary> /// An interface for an easing function that is applied to <see cref="Transform{TValue}"/>s. /// </summary> public interface IEasingFunction { /// <summary> /// Applies the easing function to a time value. /// </summary> /// <param name="time">The time value to apply the easing to.</param> /// <returns>The eased time value.</returns> double ApplyEasing(double time); } }
mit
C#
ef613b322efb9263f7b806bf3ebbd2917d5b9dd8
Move JobStore cleanup to abstract class.
lukeryannetnz/quartznet-dynamodb,lukeryannetnz/quartznet-dynamodb
src/QuartzNET-DynamoDB.Tests/Integration/JobStore/JobStoreIntegrationTest.cs
src/QuartzNET-DynamoDB.Tests/Integration/JobStore/JobStoreIntegrationTest.cs
using System; namespace Quartz.DynamoDB.Tests.Integration.JobStore { /// <summary> /// Abstract class that provides common dynamo db cleanup for JobStore integration testing. /// </summary> public abstract class JobStoreIntegrationTest : IDisposable { protected DynamoDB.JobStore _sut; protected DynamoClientFactory _testFactory; #region IDisposable implementation bool _disposedValue = false; protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _testFactory.CleanUpDynamo(); if (_sut != null) { _sut.Dispose(); } } _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion } }
apache-2.0
C#
62a158706458624a17e4caf6c49fe219b99700e2
Introduce GitVersionFinder.ShouldGitHubFlowVersioningSchemeApply()
DanielRose/GitVersion,FireHost/GitVersion,Kantis/GitVersion,pascalberger/GitVersion,orjan/GitVersion,gep13/GitVersion,onovotny/GitVersion,dazinator/GitVersion,onovotny/GitVersion,ermshiperete/GitVersion,dpurge/GitVersion,ermshiperete/GitVersion,anobleperson/GitVersion,TomGillen/GitVersion,Philo/GitVersion,JakeGinnivan/GitVersion,DanielRose/GitVersion,pascalberger/GitVersion,anobleperson/GitVersion,onovotny/GitVersion,JakeGinnivan/GitVersion,GitTools/GitVersion,Philo/GitVersion,MarkZuber/GitVersion,GitTools/GitVersion,ParticularLabs/GitVersion,dazinator/GitVersion,asbjornu/GitVersion,GeertvanHorrik/GitVersion,GeertvanHorrik/GitVersion,RaphHaddad/GitVersion,orjan/GitVersion,dpurge/GitVersion,JakeGinnivan/GitVersion,openkas/GitVersion,distantcam/GitVersion,distantcam/GitVersion,ermshiperete/GitVersion,DanielRose/GitVersion,FireHost/GitVersion,alexhardwicke/GitVersion,Kantis/GitVersion,MarkZuber/GitVersion,dpurge/GitVersion,asbjornu/GitVersion,TomGillen/GitVersion,openkas/GitVersion,dpurge/GitVersion,ermshiperete/GitVersion,anobleperson/GitVersion,alexhardwicke/GitVersion,pascalberger/GitVersion,JakeGinnivan/GitVersion,gep13/GitVersion,RaphHaddad/GitVersion,Kantis/GitVersion,ParticularLabs/GitVersion
GitFlowVersion/GitVersionFinder.cs
GitFlowVersion/GitVersionFinder.cs
namespace GitFlowVersion { using System; using System.Linq; using LibGit2Sharp; public class GitVersionFinder { public VersionAndBranch FindVersion(GitVersionContext context) { EnsureMainTopologyConstraints(context); if (ShouldGitHubFlowVersioningSchemeApply(context.Repository)) { return new GitHubFlowVersionFinder().FindVersion(context); } return new GitFlowVersionFinder().FindVersion(context); } public static bool ShouldGitHubFlowVersioningSchemeApply(IRepository repo) { return repo.FindBranch("develop") == null; } void EnsureMainTopologyConstraints(GitVersionContext context) { EnsureLocalBranchExists(context.Repository, "master"); // TODO somehow enforce this? EnsureLocalBranchExists(context.Repository, "develop"); EnsureHeadIsNotDetached(context); } void EnsureHeadIsNotDetached(GitVersionContext context) { if (!context.CurrentBranch.CanonicalName.Equals("(no branch)", StringComparison.OrdinalIgnoreCase)) { return; } var message = string.Format("It looks like the branch being examined is a detached Head pointing to commit '{0}'. Without a proper branch name GitFlowVersion cannot determine the build version.", context.CurrentBranch.Tip.Id.ToString(7)); throw new ErrorException(message); } void EnsureLocalBranchExists(IRepository repository, string branchName) { if (repository.FindBranch(branchName) != null) { return; } var existingBranches = string.Format("'{0}'", string.Join("', '", repository.Branches.Select(x => x.CanonicalName))); throw new ErrorException(string.Format("This repository doesn't contain a branch named '{0}'. Please create one. Existing branches: {1}", branchName, existingBranches)); } } }
namespace GitFlowVersion { using System; using System.Linq; using LibGit2Sharp; public class GitVersionFinder { public VersionAndBranch FindVersion(GitVersionContext context) { EnsureMainTopologyConstraints(context); var hasDevelopBranch = context.Repository.FindBranch("develop") != null; if (hasDevelopBranch) { return new GitFlowVersionFinder().FindVersion(context); } return new GitHubFlowVersionFinder().FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) { EnsureLocalBranchExists(context.Repository, "master"); // TODO somehow enforce this? EnsureLocalBranchExists(context.Repository, "develop"); EnsureHeadIsNotDetached(context); } void EnsureHeadIsNotDetached(GitVersionContext context) { if (!context.CurrentBranch.CanonicalName.Equals("(no branch)", StringComparison.OrdinalIgnoreCase)) { return; } var message = string.Format("It looks like the branch being examined is a detached Head pointing to commit '{0}'. Without a proper branch name GitFlowVersion cannot determine the build version.", context.CurrentBranch.Tip.Id.ToString(7)); throw new ErrorException(message); } void EnsureLocalBranchExists(IRepository repository, string branchName) { if (repository.FindBranch(branchName) != null) { return; } var existingBranches = string.Format("'{0}'", string.Join("', '", repository.Branches.Select(x => x.CanonicalName))); throw new ErrorException(string.Format("This repository doesn't contain a branch named '{0}'. Please create one. Existing branches: {1}", branchName, existingBranches)); } } }
mit
C#
f723de2481cd53e7c502629dd25d91b3686ee850
Update scripts
CatenaLogic/AzureStorageSync
build.cake
build.cake
//======================================================= // DEFINE PARAMETERS //======================================================= // Define the required parameters var Parameters = new Dictionary<string, object>(); Parameters["SolutionName"] = "AzureStorageSync"; Parameters["Company"] = "CatenaLogic"; Parameters["RepositoryUrl"] = string.Format("https://github.com/{0}/{1}", GetBuildServerVariable("Company"), GetBuildServerVariable("SolutionName")); Parameters["StartYear"] = "2014"; Parameters["UseVisualStudioPrerelease"] = "true"; // Note: the rest of the variables should be coming from the build server, // see `/deployment/cake/*-variables.cake` for customization options // // If required, more variables can be overridden by specifying them via the // Parameters dictionary, but the build server variables will always override // them if defined by the build server. For example, to override the code // sign wild card, add this to build.cake // // Parameters["CodeSignWildcard"] = "Orc.EntityFramework"; //======================================================= // DEFINE COMPONENTS TO BUILD / PACKAGE //======================================================= Tools.Add(string.Format("{0}", GetBuildServerVariable("SolutionName"))); TestProjects.Add(string.Format("{0}.Tests", GetBuildServerVariable("SolutionName"))); //======================================================= // REQUIRED INITIALIZATION, DO NOT CHANGE //======================================================= // Now all variables are defined, include the tasks, that // script will take care of the rest of the magic #l "./deployment/cake/tasks.cake"
mit
C#
b0d167e18771f186d4b0960d64acf02b29e9d015
Add NSecKeyFormatter class
ektrah/nsec
src/Cryptography/Formatting/NSecKeyFormatter.cs
src/Cryptography/Formatting/NSecKeyFormatter.cs
using System; using System.Diagnostics; using static Interop.Libsodium; namespace NSec.Cryptography.Formatting { internal class NSecKeyFormatter { private readonly byte[] _magic; private readonly int _maxKeySize; private readonly int _minKeySize; public NSecKeyFormatter( int minKeySize, int maxKeySize, byte[] magic) { Debug.Assert(minKeySize >= 0); Debug.Assert(maxKeySize >= minKeySize); Debug.Assert(magic != null); _minKeySize = minKeySize; _maxKeySize = maxKeySize; _magic = magic; } public byte[] Export( SecureMemoryHandle keyHandle) { Debug.Assert(keyHandle != null); Debug.Assert(keyHandle.Length >= _minKeySize); Debug.Assert(keyHandle.Length <= _maxKeySize); byte[] blob = new byte[_magic.Length + sizeof(uint) + keyHandle.Length]; new ReadOnlySpan<byte>(_magic).CopyTo(blob); new Span<byte>(blob, _magic.Length).WriteLittleEndian((uint)keyHandle.Length); keyHandle.Export(new Span<byte>(blob, _magic.Length + sizeof(uint))); return blob; } public int GetBlobSize( int keySize) { return 8 + keySize; } public bool TryImport( ReadOnlySpan<byte> blob, out SecureMemoryHandle keyHandle, out byte[] publicKeyBytes) { int keySize = blob.Length - (_magic.Length + sizeof(uint)); if (keySize < _minKeySize || keySize > _maxKeySize || blob.Length < _magic.Length + sizeof(uint) || !blob.StartsWith(_magic) || blob.Slice(_magic.Length).ReadLittleEndian() != (uint)keySize) { keyHandle = null; publicKeyBytes = null; return false; } publicKeyBytes = null; SecureMemoryHandle.Alloc(keySize, out keyHandle); keyHandle.Import(blob.Slice(_magic.Length + sizeof(uint))); return true; } } }
mit
C#
df9f9c597a381867fcb04a41419cb6ded3434d22
Add the controller 'TrilhaController' to Fatec.Treinamento.Web/Controllers/ folder
fmassaretto/formacao-talentos,fmassaretto/formacao-talentos,fmassaretto/formacao-talentos
Fatec.Treinamento.Web/Controllers/TrilhaController.cs
Fatec.Treinamento.Web/Controllers/TrilhaController.cs
using Fatec.Treinamento.Data.Repositories; using Fatec.Treinamento.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Fatec.Treinamento.Web.Controllers { public class TrilhaController : Controller { // GET: Trilha public ActionResult Index() { var repo = new TrilhaRepository(); var lista = repo.Listar(); return View(lista); } public ActionResult Criar() { return View(); } [HttpPost] public ActionResult Criar(Trilha trilha) { using (var repo = new TrilhaRepository()) { var inserido = repo.Inserir(trilha); if (inserido.Id == 0) { ModelState.AddModelError("", "Erro"); } } return RedirectToAction("Index"); } } }
apache-2.0
C#
e5f75c014fbb52a6c39d61212b0020f610d1e631
Revert "Delete AndyLevy.cs"
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/AndyLevy.cs
src/Firehose.Web/Authors/AndyLevy.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AndyLevy : IAmACommunityMember { public string FirstName => "Andy"; public string LastName => "Levy"; public string ShortBioOrTagLine => "DBA & PowerShell fan in New York's Wine Region"; public string StateOrRegion => "New York"; public string EmailAddress => string.Empty; public string TwitterHandle => "alevyinroc"; public string GravatarHash => "6a2838f9f6d7e95c1124d4a301a1ae0d"; public string GitHubHandle => "andylevy"; public GeoPosition Position => new GeoPosition(42.8875, -77.281667); public Uri WebSite => new Uri("https://flxsql.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.flxsql.com/feed/"); } } public string FeedLanguageCode => "en"; } }
mit
C#
fac4ef5ffc39b149d74eeccce9171ba1ee1b55e7
add my NaturalNumber toy class i know about System.Numerics.BigInteger but choose to explore this to learn more about this
martinlindhe/Punku
punku/Math/NaturalNumber.cs
punku/Math/NaturalNumber.cs
/** * http://en.wikipedia.org/wiki/Natural_number * * NOTE http://msdn.microsoft.com/en-us/library/system.numerics.biginteger%28v=vs.100%29.aspx * System.Numerics.BigInteger also exists */ using System; // TODO unit tests for htis class namespace Punku { /** * Can represent a very large number */ public class NaturalNumber { public byte[] Digits; protected uint NumberBase; public NaturalNumber (string s, uint numberBase = 10) { if (numberBase != 10) throw new NotImplementedException ("only handles base-10 input"); NumberBase = numberBase; Digits = Parse (s); } /** * Parses a base-10 number represented in a string */ protected static byte[] Parse (string s) { var res = new byte[s.Length]; int idx = 0; foreach (char c in s) { if (c < '0' || c > '9') throw new FormatException (); res [idx++] = (byte)(c - '0'); } return res; } /** * Converts a natural number to a decimal */ public decimal ToDecimal () { decimal res = 0; // XXXX TODO throw exception if number is too large foreach (byte b in Digits) res = (res * NumberBase) + b; return res; } } }
mit
C#
e9c1bcaa791b0cb4cb45b748692a8317ec9fb753
Delete this file.
senfo/FrogBlogger,senfo/FrogBlogger
FrogBlogger.Web/Infrastructure/FrogBloggerControllerBase.cs
FrogBlogger.Web/Infrastructure/FrogBloggerControllerBase.cs
using System.Data.Objects; using System.Web.Mvc; namespace FrogBlogger.Web.Infrastructure { /// <summary> /// The base class for controllers in FrogBlogger /// </summary> public class FrogBloggerControllerBase : Controller { #region Fields /// <summary> /// The object context from which to query /// </summary> protected ObjectContext _context; #endregion #region Constructors /// <summary> /// Intializes a new instance of the FrogBloggerControllerBase class /// </summary> protected FrogBloggerControllerBase() { } /// <summary> /// Intializes a new instance of the FrogBloggerControllerBase class /// </summary> /// <param name="context">The context from which to query</param> protected FrogBloggerControllerBase(ObjectContext context) { _context = context; } #endregion } }
bsd-3-clause
C#
dd984fc6e91729855adbef1d70de2f6cf9e042b7
add releases tests
lvermeulen/BuildMaster.Net
test/BuildMaster.Net.Tests/Releases/BuildMasterClientShould.cs
test/BuildMaster.Net.Tests/Releases/BuildMasterClientShould.cs
using System.Threading.Tasks; using BuildMaster.Net.Releases.Models; using Xunit; // ReSharper disable CheckNamespace namespace BuildMaster.Net.Tests { public partial class BuildMasterClientShould { [Fact] public async Task GetReleasesAsync() { var results = await _client.GetReleasesAsync(new GetReleasesRequest()).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results); } [Fact] public async Task GetPackagesAsync() { var results = await _client.GetPackagesAsync(new GetPackagesRequest()).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results); } [Fact] public async Task GetDeploymentsAsync() { var request = new GetDeploymentsRequest { ApplicationId = 1, ReleaseNumber = "0.0.0" }; var results = await _client.GetDeploymentsAsync(request).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results); } } }
mit
C#
cf23e02ee4beb14a0dff90e94410ac6ff9cfe585
Add C# Rock-Paper-Scissors
Joimer/ConsoleGames,Joimer/ConsoleGames,Joimer/ConsoleGames,Joimer/ConsoleGames
rps/rps.cs
rps/rps.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleRps { class Rps { static string[] answers = new string[] { "rock", "paper", "scissors" }; static Dictionary<string, Dictionary<string, int>> results = new Dictionary<string, Dictionary<string, int>>() { {"rock", new Dictionary<string, int>() { { "rock", 0 }, { "paper", -1 }, { "scissors", 1 } }}, { "paper", new Dictionary<string, int>() { { "rock", 1 }, { "paper", 0 }, { "scissors", -1 } }}, { "scissors", new Dictionary<string, int>() { { "rock", -1 }, { "paper", 1 }, { "scissors", 0 } }} }; static Dictionary<int, string> resultTexts = new Dictionary<int, string>() { {-1, "You lose!"}, {0, "It's a tie!"}, {1, "You win!"} }; static int wins = 0; static int losses = 0; static bool isPlaying = true; static void Main(string[] args) { Console.WriteLine("Rock, paper, scissors; best of five!"); Console.WriteLine("Choose an action[rock, paper, scissors]"); Random rnd = new Random(); // Main game loop, to be broken only when game is finished. while (isPlaying) { String action = Console.ReadLine(); if (answers.Contains(action)) { int cpu = rnd.Next(0, 3); string cpuAction = answers[cpu]; Console.WriteLine("The CPU chose {0}", cpuAction); int result = results[action][cpuAction]; if (result == 1) { wins++; } else if (result == -1) { losses++; } Console.WriteLine(resultTexts[result] + " ({0} - {1})", wins, losses); if (wins > 2 || losses > 2) { if (wins > losses) { Console.WriteLine("You won the game!"); } else { Console.WriteLine("You lost the game..."); } isPlaying = false; } else { Console.WriteLine("Choose a new action."); } } else { Console.WriteLine("Wrong action!"); } } // Out of game loop, add a new ReadLine so the player can read the result. Console.ReadLine(); } } }
mit
C#
2495272ba0d9f1221da4fc91da9d0e3fd63205b4
Copy source code from KLibrary-Labs
sakapon/KLibrary.Linq
KLibrary4/Linq/Linq/Comparison.cs
KLibrary4/Linq/Linq/Comparison.cs
using System; using System.Collections.Generic; namespace KLibrary.Linq { public static class Comparison { public static IComparer<T> CreateComparer<T>(Func<T, T, int> compare) { return new DelegateComparer<T>(compare); } public static IEqualityComparer<T> CreateEqualityComparer<T>(Func<T, T, bool> equals) { return new DelegateEqualityComparer<T>(equals); } } class DelegateComparer<T> : Comparer<T> { Func<T, T, int> _compare; public DelegateComparer(Func<T, T, int> compare) { if (compare == null) throw new ArgumentNullException("compare"); _compare = compare; } public override int Compare(T x, T y) { return _compare(x, y); } } class DelegateEqualityComparer<T> : EqualityComparer<T> { Func<T, T, bool> _equals; public DelegateEqualityComparer(Func<T, T, bool> equals) { if (equals == null) throw new ArgumentNullException("equals"); _equals = equals; } public override bool Equals(T x, T y) { return _equals(x, y); } public override int GetHashCode(T obj) { return obj != null ? obj.GetHashCode() : 0; } } }
mit
C#
c11acf46d0cef8f6143b95952b5278165533475b
Update version to match IoT Connector viewer
javiddhankwala/samples,ms-iot/samples,javiddhankwala/samples,ms-iot/samples,rachitb777/samples,paulmon/samples,parameshbabu/samples,bfjelds/samples,jessekaplan/samples,bfjelds/samples,paulmon/samples,zhuridartem/samples,rachitb777/samples,paulmon/samples,jessekaplan/samples,parameshbabu/samples,bfjelds/samples,rachitb777/samples,javiddhankwala/samples,ms-iot/samples,javiddhankwala/samples,bfjelds/samples,zhuridartem/samples,rachitb777/samples,jessekaplan/samples,paulmon/samples,jordanrh1/samples,jordanrh1/samples,ms-iot/samples,jayhopeter/samples,ms-iot/samples,jayhopeter/samples,ms-iot/samples,derekameer/samples,jessekaplan/samples,ms-iot/samples,bfjelds/samples,bfjelds/samples,jayhopeter/samples,jayhopeter/samples,paulmon/samples,zhuridartem/samples,jayhopeter/samples,paulmon/samples,jayhopeter/samples,ms-iot/samples,paulmon/samples,jayhopeter/samples,jordanrh1/samples,derekameer/samples,parameshbabu/samples,derekameer/samples,parameshbabu/samples,ms-iot/samples,jessekaplan/samples,javiddhankwala/samples,derekameer/samples,parameshbabu/samples,zhuridartem/samples,rachitb777/samples,jessekaplan/samples,jordanrh1/samples,rachitb777/samples,rachitb777/samples,parameshbabu/samples,jessekaplan/samples,rachitb777/samples,jayhopeter/samples,paulmon/samples,derekameer/samples,zhuridartem/samples,jordanrh1/samples,jordanrh1/samples,jayhopeter/samples,jordanrh1/samples,ms-iot/samples,derekameer/samples,zhuridartem/samples,javiddhankwala/samples,bfjelds/samples,derekameer/samples,javiddhankwala/samples,jordanrh1/samples,bfjelds/samples,parameshbabu/samples,parameshbabu/samples,parameshbabu/samples,jessekaplan/samples,jessekaplan/samples,derekameer/samples,javiddhankwala/samples,javiddhankwala/samples,zhuridartem/samples,rachitb777/samples,jordanrh1/samples,rachitb777/samples,zhuridartem/samples,paulmon/samples,javiddhankwala/samples,zhuridartem/samples,derekameer/samples,derekameer/samples,bfjelds/samples,parameshbabu/samples,paulmon/samples,bfjelds/samples,jordanrh1/samples,jessekaplan/samples,jayhopeter/samples,zhuridartem/samples
IoTConnector/IoTConnectorClient/IoTConnectorClient/Constants.cs
IoTConnector/IoTConnectorClient/IoTConnectorClient/Constants.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IoTConnectorClient { static class Constants { public const string LOGIN_ERROR = "An error occurred. Please enter the correct credentials below"; public const string LOGIN_STD_MSG = "Please enter your credentials below"; public const string SENDING_AZURE = "Sending to Azure..."; public const string READY_AZURE = "Ready to send messages"; public const string ERROR_AZURE = "An error occurred. Please log out and log in with the correct credentials."; public const string LIST_HEADER = "<p id='start-list'>#msgList#</p>"; public const int PORT = 8001; public const string VERSION = "1.0"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IoTConnectorClient { static class Constants { public const string LOGIN_ERROR = "An error occurred. Please enter the correct credentials below"; public const string LOGIN_STD_MSG = "Please enter your credentials below"; public const string SENDING_AZURE = "Sending to Azure..."; public const string READY_AZURE = "Ready to send messages"; public const string ERROR_AZURE = "An error occurred. Please log out and log in with the correct credentials."; public const string LIST_HEADER = "<p id='start-list'>#msgList#</p>"; public const int PORT = 8001; public const string VERSION = "1.1"; } }
mit
C#
34fc740e1f72e6ec4b8f5865d0e2f008d2973a02
Implement testcase for room settings
ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,johnneijzen/osu,peppy/osu,peppy/osu-new,naoey/osu,ppy/osu,ppy/osu,DrabWeb/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,2yangk23/osu,EVAST9919/osu,johnneijzen/osu,DrabWeb/osu,smoogipoo/osu,naoey/osu,naoey/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu
osu.Game.Tests/Visual/TestCaseMatchSettingsOverlay.cs
osu.Game.Tests/Visual/TestCaseMatchSettingsOverlay.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Match.Components; namespace osu.Game.Tests.Visual { public class TestCaseMatchSettingsOverlay : OsuTestCase { public TestCaseMatchSettingsOverlay() { Child = new RoomSettingsOverlay(new Room()) { RelativeSizeAxes = Axes.Both, State = Visibility.Visible }; } } }
mit
C#
30e10c90d98ba6a085f183f3a2775cd4945099c7
add my exception file for users
ivayloivanof/Libbon_Tank_Game
TankGame/Exception/UserErrorException.cs
TankGame/Exception/UserErrorException.cs
namespace TankGame.Exception { using System; public class UserErrorException : Exception { public UserErrorException(string message) : base(message) { } } }
cc0-1.0
C#
9e855d147817abb02de926d77ef5a1bf5902b03b
fix static construtor exception analyzer when ctor body is null
robsonalves/code-cracker,f14n/code-cracker,giggio/code-cracker,carloscds/code-cracker,eriawan/code-cracker,thorgeirk11/code-cracker,eirielson/code-cracker,andrecarlucci/code-cracker,caioadz/code-cracker,gerryaobrien/code-cracker,modulexcite/code-cracker,dlsteuer/code-cracker,kindermannhubert/code-cracker,GuilhermeSa/code-cracker,carloscds/code-cracker,AlbertoMonteiro/code-cracker,baks/code-cracker,dmgandini/code-cracker,adraut/code-cracker,akamud/code-cracker,jwooley/code-cracker,code-cracker/code-cracker,thomaslevesque/code-cracker,ElemarJR/code-cracker,code-cracker/code-cracker,jhancock93/code-cracker
src/CodeCracker/StaticConstructorExceptionAnalyzer.cs
src/CodeCracker/StaticConstructorExceptionAnalyzer.cs
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticConstructorExceptionAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "CC0024"; internal const string Title = "Don't throw exception inside static constructors."; internal const string MessageFormat = "Don't throw exception inside static constructors."; internal const string Category = "Usage"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ConstructorDeclaration); } private void Analyzer(SyntaxNodeAnalysisContext context) { var ctor = (ConstructorDeclarationSyntax)context.Node; if (!ctor.Modifiers.Any(SyntaxKind.StaticKeyword)) return; if (ctor.Body == null) return; var @throw = ctor.Body.ChildNodes().OfType<ThrowStatementSyntax>().FirstOrDefault(); if (@throw == null) return; context.ReportDiagnostic(Diagnostic.Create(Rule, @throw.GetLocation(), ctor.Identifier.Text)); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticConstructorExceptionAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "CC0024"; internal const string Title = "Don't throw exception inside static constructors."; internal const string MessageFormat = "Don't throw exception inside static constructors."; internal const string Category = "Usage"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ConstructorDeclaration); } private void Analyzer(SyntaxNodeAnalysisContext context) { var ctor = (ConstructorDeclarationSyntax)context.Node; if (!ctor.Modifiers.Any(SyntaxKind.StaticKeyword)) return; var @throw = ctor.Body.ChildNodes().OfType<ThrowStatementSyntax>().FirstOrDefault(); if (@throw == null) return; context.ReportDiagnostic(Diagnostic.Create(Rule, @throw.GetLocation(), ctor.Identifier.Text)); } } }
apache-2.0
C#
bc4a87d2cde41d669fc577be70dd3a5493e1bca8
Create EngineCodes.cs
sqlkata/querybuilder
QueryBuilder/Compilers/EngineCodes.cs
QueryBuilder/Compilers/EngineCodes.cs
namespace SqlKata.Compilers { public static class EngineCodes { public const string Firebird = "firebird"; public const string Generic = "generic"; public const string MySql = "mysql"; public const string Oracle = "oracle"; public const string PostgreSql = "postgres"; public const string Sqlite = "sqlite"; public const string SqlServer = "sqlsrv"; } }
mit
C#
77874f7cb81eefb599e4ad5ee8ce29d685da1fcc
Add stub implementation of local
mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype
src/Glimpse.Server.Web/Broker/LocalBrokerPublisher.cs
src/Glimpse.Server.Web/Broker/LocalBrokerPublisher.cs
using System; namespace Glimpse.Server { public class LocalBrokerPublisher : IBrokerPublisher { public void PublishMessage(IMessage message) { // TODO: push straight to the bus } } }
mit
C#
39f219f4898c3b41770d2b501c51ad894c2d1a64
Add Lang error
CalladaAltr/Soul.Core,AnotherAltr/Soul.Core,CalladaAltr/Soul.Core,AnotherAltr/Soul.Core,CalladaAltr/Soul.Core,AnotherAltr/Soul.Core
Soul.Core/Types/ErrorDB.cs
Soul.Core/Types/ErrorDB.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Soul.Core.Types { public enum SoulError { SS1000, // Ожидаемый символ SS1001, // Ожидаемая лексема SS1002, // Ожидаемый ключ SS1003, // Ожидаемый признак конца строки SS1004, // Ожидаемое ключевое слово SS1005, // Ожидаемое имя класса\структуры\метода SS1006, // Ожидаемое имя сборки\файла SS1007, // Недопустимый символ SS1008, // Необъявленная структура\перечесление\ликсема SS1009, SS1010, SS1011, SS1012, SS1013, SS1014, SS1015, SS1016, SS1017, SS1018, SS1019, } }
mit
C#
9f3c845099e121b560d978b8b3e711b39bbc9ab5
Create Edit.cshtml
kelong/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4,CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4
Views/Comments/Edit.cshtml
Views/Comments/Edit.cshtml
@model RepositoryWithCaching.Models.Comment @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Comment</legend> @Html.HiddenFor(model => model.CommentID) <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Title, new { @class="form-control" }) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Text) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Text, new { @class="form-control" }) @Html.ValidationMessageFor(model => model.Text) </div> <div class="editor-label"> @Html.LabelFor(model => model.BlogID, "Blog") </div> <div class="editor-field"> @Html.DropDownList("BlogID", null, new { @class="form-control" }) @Html.ValidationMessageFor(model => model.BlogID) </div> <p> <input type="submit" class="btn btn-success" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index", null, new { @class="btn btn-success"}) </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
mit
C#
b29da45ab97f95fe7d4a96a2d165145eb6c87316
test with schema support
thinking-home/migrator,thinking-home/migrator
ThinkingHome.Migrator.Tests/Providers/WithSchema/OracleTransformationProviderSchemaTest.cs
ThinkingHome.Migrator.Tests/Providers/WithSchema/OracleTransformationProviderSchemaTest.cs
namespace ThinkingHome.Migrator.Tests.Providers.WithSchema { public class OracleTransformationProviderSchemaTest : OracleTransformationProviderTest { protected override string GetSchemaForCreateTables() { return "MOO"; } protected override string GetSchemaForCompare() { return "MOO"; } } }
mit
C#
360f8ce6787b62fbf6b119cb32235f121bcf7bb7
Create 08.Refactor-Volume-of-Pyramid.cs
StefanKoev/DataTypesAndVariables---Lab
08.Refactor-Volume-of-Pyramid.cs
08.Refactor-Volume-of-Pyramid.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08.Refactor_Volume_of_Pyramid { class Program { static void Main(string[] args) { Console.Write("Length: "); double lenght = double.Parse(Console.ReadLine()); Console.Write("Width: "); double width = double.Parse(Console.ReadLine()); Console.Write("Height: "); double height = double.Parse(Console.ReadLine()); double volume = (lenght * width * height) / 3; Console.WriteLine("Pyramid Volume: {0:f2}", volume); } } }
mit
C#
ed80ca618008e1edf112e9e2707a147730039bc7
Create Movement_Pacing.cs
Tech-Curriculums/101-GameDesign-2D-GameDesign-With-Unity
AngryHipsters/Movement_Pacing.cs
AngryHipsters/Movement_Pacing.cs
//This script causes a character to pace back and forth //each left and right walk's duration is controlled by `walkDuration` variable using UnityEngine; using System.Collections; public class Movement_Pacing : MonoBehaviour { float walkDuration = 3.0f; float timeLeft = 3.0f ; bool goright=true; // Update is called once per frame void Update () { Movement(); } void Movement() { if(timeLeft > 0 && goright) { transform.Translate(Vector2.right * 4f * Time.deltaTime); transform.eulerAngles = new Vector2(0,0); timeLeft -= Time.deltaTime; } else if(timeLeft <= 0 && goright) { timeLeft = -walkDuration; goright=false; } else if( timeLeft <=0 && !goright) { transform.Translate(-Vector2.right * 4f * Time.deltaTime); transform.eulerAngles = new Vector2(0,0); timeLeft += Time.deltaTime; } else if(timeLeft > 0 && !goright) { timeLeft = walkDuration; goright=true; } } }
mit
C#
057cce6305419b4753224684ce67aaa3a4a00fb7
Add message validator interface
Vtek/Bartender
Cheers.Cqrs/IMessageValidator.cs
Cheers.Cqrs/IMessageValidator.cs
using System; namespace Cheers.Cqrs { public interface IMessageValidator { } }
mit
C#
81f1e2ca207ed2c5fd4673dc640c2b4f711fcd8b
Add auto exit play mode on compile
LemonLube/Expanse,AikenParker/Expanse
StandaloneUtility/Editor/ExitPlayModeOnCompile.cs
StandaloneUtility/Editor/ExitPlayModeOnCompile.cs
using UnityEngine; using System.Collections; using UnityEditor; namespace Expanse { /// <summary> /// Exits play mode automatically when Unity performs code compilation. /// </summary> [InitializeOnLoad] public class ExitPlayModeOnCompile { private static ExitPlayModeOnCompile instance = null; static ExitPlayModeOnCompile() { instance = new ExitPlayModeOnCompile(); } private ExitPlayModeOnCompile() { EditorApplication.update += OnEditorUpdate; } ~ExitPlayModeOnCompile() { EditorApplication.update -= OnEditorUpdate; if (instance == this) instance = null; } private static void OnEditorUpdate() { if (EditorApplication.isPlaying && EditorApplication.isCompiling) { EditorApplication.isPlaying = false; } } } }
mit
C#