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
89d09d99db4c9331eb5a57d71ae720807dcebd74
Remove http stream test
hey-red/Mime
test/MimeTests/GuessMime.cs
test/MimeTests/GuessMime.cs
using HeyRed.Mime; using System.IO; using System.Net.Http; using Xunit; namespace MimeTests { public class GuessMime { public GuessMime() => MimeGuesser.MagicFilePath = ResourceUtils.GetMagicFilePath; [Fact] public void GuessMimeFromFilePath() { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromBuffer() { byte[] buffer = File.ReadAllBytes(ResourceUtils.GetFileFixture); string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(buffer); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromStream() { using (var stream = File.OpenRead(ResourceUtils.GetFileFixture)) { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(stream); Assert.Equal(expected, actual); } } [Fact] public void GuessMimeFromFileInfo() { string expected = "image/jpeg"; var fi = new FileInfo(ResourceUtils.GetFileFixture); string actual = fi.GuessMimeType(); Assert.Equal(expected, actual); } } }
using HeyRed.Mime; using System.IO; using System.Net.Http; using Xunit; namespace MimeTests { public class GuessMime { public GuessMime() => MimeGuesser.MagicFilePath = ResourceUtils.GetMagicFilePath; [Fact] public void GuessMimeFromFilePath() { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromBuffer() { byte[] buffer = File.ReadAllBytes(ResourceUtils.GetFileFixture); string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(buffer); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromStream() { using (var stream = File.OpenRead(ResourceUtils.GetFileFixture)) { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(stream); Assert.Equal(expected, actual); } } [Fact] public void GuessMimeFromFileInfo() { string expected = "image/jpeg"; var fi = new FileInfo(ResourceUtils.GetFileFixture); string actual = fi.GuessMimeType(); Assert.Equal(expected, actual); } [Fact] public async void GuessMimeFromHttpStream() { using (var client = new HttpClient()) { var uri = "https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"; using (var stream = await client.GetStreamAsync(uri)) { string expected = "image/png"; string actual = MimeGuesser.GuessMimeType(stream); Assert.Equal(expected, actual); } } } } }
mit
C#
a026d93b41e758203609e4f508322f8d39e3c2b5
Update GameManager.cs
Magneseus/3x-eh
Assets/scripts/GameManager.cs
Assets/scripts/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { // Maybe we want this to be a reference to a Map? public List<City> ListOfCities; public int DurationOfTurn = 7; private int CurrentTurnNumber; private int DaysTranspired; // Initialization // Use this for initialization void Start () { CurrentTurnNumber = 0; DaysTranspired = 0; } void EndTurnUpdate() { // Here we will update everything (basically just updating the cities) foreach (City c in ListOfCities) { c.TurnUpdate(DurationOfTurn); } CurrentTurnNumber += 1; DaysTranspired += DurationOfTurn; Debug.Log("Turn ended, " + DurationOfTurn + " days passed."); } //Updated per frame, use for UI. void Update() { if (Input.GetKeyDown(KeyCode.E)) { EndTurnUpdate(); } } //////////// Single Instance Assertion Stuff private static bool _isInstantiated = false; private void Awake() { // IF THIS FAILS, we've instantiated another GameManager somewhere!! Debug.Assert(!_isInstantiated); _isInstantiated = true; } private void OnDestroy() { _isInstantiated = false; } ///// End of Single Instance Assertion Stuff }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
7089d545bbf7c2dcd3aa949c1762de28883d28d4
add missing copyright message
furesoft/roslyn,bbarry/roslyn,jcouv/roslyn,ericfe-ms/roslyn,jeremymeng/roslyn,pdelvo/roslyn,swaroop-sridhar/roslyn,mirhagk/roslyn,reaction1989/roslyn,dpoeschl/roslyn,bartdesmet/roslyn,akrisiun/roslyn,doconnell565/roslyn,swaroop-sridhar/roslyn,supriyantomaftuh/roslyn,natidea/roslyn,bkoelman/roslyn,stjeong/roslyn,michalhosala/roslyn,aanshibudhiraja/Roslyn,sharadagrawal/Roslyn,devharis/roslyn,jbhensley/roslyn,stjeong/roslyn,KamalRathnayake/roslyn,thomaslevesque/roslyn,garryforreg/roslyn,jgglg/roslyn,khyperia/roslyn,jrharmon/roslyn,KirillOsenkov/roslyn,CaptainHayashi/roslyn,supriyantomaftuh/roslyn,orthoxerox/roslyn,nemec/roslyn,srivatsn/roslyn,tannergooding/roslyn,sharadagrawal/Roslyn,oberxon/roslyn,amcasey/roslyn,mattwar/roslyn,jeffanders/roslyn,paladique/roslyn,krishnarajbb/roslyn,tmeschter/roslyn,FICTURE7/roslyn,khellang/roslyn,akrisiun/roslyn,mirhagk/roslyn,jmarolf/roslyn,zooba/roslyn,Maxwe11/roslyn,AArnott/roslyn,MattWindsor91/roslyn,magicbing/roslyn,Pvlerick/roslyn,sharwell/roslyn,reaction1989/roslyn,mseamari/Stuff,jroggeman/roslyn,tang7526/roslyn,EricArndt/roslyn,MihaMarkic/roslyn-prank,MihaMarkic/roslyn-prank,panopticoncentral/roslyn,managed-commons/roslyn,v-codeel/roslyn,cston/roslyn,brettfo/roslyn,managed-commons/roslyn,tvand7093/roslyn,DinoV/roslyn,yeaicc/roslyn,mattscheffer/roslyn,akoeplinger/roslyn,orthoxerox/roslyn,jrharmon/roslyn,CyrusNajmabadi/roslyn,wschae/roslyn,jasonmalinowski/roslyn,mattscheffer/roslyn,Inverness/roslyn,jgglg/roslyn,MatthieuMEZIL/roslyn,lisong521/roslyn,VShangxiao/roslyn,shyamnamboodiripad/roslyn,jaredpar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jeremymeng/roslyn,paladique/roslyn,akrisiun/roslyn,moozzyk/roslyn,VPashkov/roslyn,natidea/roslyn,ManishJayaswal/roslyn,brettfo/roslyn,tsdl2013/roslyn,zmaruo/roslyn,dotnet/roslyn,YOTOV-LIMITED/roslyn,wschae/roslyn,KevinRansom/roslyn,rgani/roslyn,zmaruo/roslyn,srivatsn/roslyn,cybernet14/roslyn,enginekit/roslyn,AlekseyTs/roslyn,akoeplinger/roslyn,TyOverby/roslyn,zmaruo/roslyn,jaredpar/roslyn,OmarTawfik/roslyn,KevinRansom/roslyn,MattWindsor91/roslyn,natidea/roslyn,rchande/roslyn,huoxudong125/roslyn,ericfe-ms/roslyn,Giten2004/roslyn,VitalyTVA/roslyn,REALTOBIZ/roslyn,RipCurrent/roslyn,ilyes14/roslyn,HellBrick/roslyn,lorcanmooney/roslyn,KiloBravoLima/roslyn,aanshibudhiraja/Roslyn,genlu/roslyn,kelltrick/roslyn,ilyes14/roslyn,Hosch250/roslyn,tannergooding/roslyn,AnthonyDGreen/roslyn,kelltrick/roslyn,mseamari/Stuff,evilc0des/roslyn,v-codeel/roslyn,dsplaisted/roslyn,Shiney/roslyn,drognanar/roslyn,jkotas/roslyn,chenxizhang/roslyn,3F/roslyn,REALTOBIZ/roslyn,jcouv/roslyn,budcribar/roslyn,AnthonyDGreen/roslyn,heejaechang/roslyn,ManishJayaswal/roslyn,jamesqo/roslyn,gafter/roslyn,zooba/roslyn,jramsay/roslyn,droyad/roslyn,amcasey/roslyn,krishnarajbb/roslyn,AmadeusW/roslyn,jonatassaraiva/roslyn,robinsedlaczek/roslyn,a-ctor/roslyn,managed-commons/roslyn,OmniSharp/roslyn,AlexisArce/roslyn,davkean/roslyn,khyperia/roslyn,SeriaWei/roslyn,physhi/roslyn,doconnell565/roslyn,cston/roslyn,natgla/roslyn,aelij/roslyn,marksantos/roslyn,KamalRathnayake/roslyn,balajikris/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,cston/roslyn,grianggrai/roslyn,sharadagrawal/TestProject2,BugraC/roslyn,agocke/roslyn,KashishArora/Roslyn,SeriaWei/roslyn,MattWindsor91/roslyn,chenxizhang/roslyn,srivatsn/roslyn,eriawan/roslyn,oberxon/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,agocke/roslyn,ilyes14/roslyn,genlu/roslyn,jbhensley/roslyn,jramsay/roslyn,HellBrick/roslyn,stebet/roslyn,Pvlerick/roslyn,v-codeel/roslyn,poizan42/roslyn,DustinCampbell/roslyn,DinoV/roslyn,grianggrai/roslyn,AArnott/roslyn,vslsnap/roslyn,jmarolf/roslyn,robinsedlaczek/roslyn,enginekit/roslyn,enginekit/roslyn,jonatassaraiva/roslyn,3F/roslyn,garryforreg/roslyn,tmat/roslyn,a-ctor/roslyn,DustinCampbell/roslyn,droyad/roslyn,HellBrick/roslyn,MavenRain/roslyn,wvdd007/roslyn,KashishArora/Roslyn,budcribar/roslyn,russpowers/roslyn,dotnet/roslyn,TyOverby/roslyn,genlu/roslyn,tvand7093/roslyn,Giten2004/roslyn,VPashkov/roslyn,jonatassaraiva/roslyn,taylorjonl/roslyn,KirillOsenkov/roslyn,khellang/roslyn,kelltrick/roslyn,jrharmon/roslyn,leppie/roslyn,Maxwe11/roslyn,nagyistoce/roslyn,kuhlenh/roslyn,EricArndt/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,bkoelman/roslyn,yjfxfjch/roslyn,3F/roslyn,stephentoub/roslyn,huoxudong125/roslyn,davkean/roslyn,khyperia/roslyn,jamesqo/roslyn,mavasani/roslyn,AlexisArce/roslyn,xoofx/roslyn,weltkante/roslyn,kienct89/roslyn,sharadagrawal/TestProject2,antonssonj/roslyn,jkotas/roslyn,mmitche/roslyn,moozzyk/roslyn,Giftednewt/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,OmniSharp/roslyn,yjfxfjch/roslyn,mattwar/roslyn,vcsjones/roslyn,JakeGinnivan/roslyn,Pvlerick/roslyn,sharadagrawal/TestProject2,AlexisArce/roslyn,tmeschter/roslyn,leppie/roslyn,ErikSchierboom/roslyn,jeremymeng/roslyn,supriyantomaftuh/roslyn,ValentinRueda/roslyn,devharis/roslyn,Shiney/roslyn,FICTURE7/roslyn,jasonmalinowski/roslyn,aanshibudhiraja/Roslyn,jamesqo/roslyn,Giftednewt/roslyn,DanielRosenwasser/roslyn,jeffanders/roslyn,magicbing/roslyn,dpoeschl/roslyn,grianggrai/roslyn,dpen2000/roslyn,physhi/roslyn,moozzyk/roslyn,Hosch250/roslyn,drognanar/roslyn,jmarolf/roslyn,orthoxerox/roslyn,amcasey/roslyn,tmat/roslyn,evilc0des/roslyn,EricArndt/roslyn,DanielRosenwasser/roslyn,bartdesmet/roslyn,natgla/roslyn,evilc0des/roslyn,antonssonj/roslyn,rgani/roslyn,kienct89/roslyn,REALTOBIZ/roslyn,nguerrera/roslyn,jaredpar/roslyn,wschae/roslyn,stephentoub/roslyn,1234-/roslyn,basoundr/roslyn,mattscheffer/roslyn,DanielRosenwasser/roslyn,AmadeusW/roslyn,YOTOV-LIMITED/roslyn,MavenRain/roslyn,tvand7093/roslyn,JakeGinnivan/roslyn,robinsedlaczek/roslyn,ericfe-ms/roslyn,taylorjonl/roslyn,wvdd007/roslyn,dovzhikova/roslyn,thomaslevesque/roslyn,vslsnap/roslyn,VShangxiao/roslyn,abock/roslyn,brettfo/roslyn,ManishJayaswal/roslyn,antonssonj/roslyn,devharis/roslyn,leppie/roslyn,mseamari/Stuff,dpen2000/roslyn,a-ctor/roslyn,oocx/roslyn,ljw1004/roslyn,ljw1004/roslyn,jhendrixMSFT/roslyn,cybernet14/roslyn,KiloBravoLima/roslyn,furesoft/roslyn,dsplaisted/roslyn,wvdd007/roslyn,sharwell/roslyn,MichalStrehovsky/roslyn,tsdl2013/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,jhendrixMSFT/roslyn,VShangxiao/roslyn,FICTURE7/roslyn,AArnott/roslyn,stebet/roslyn,Maxwe11/roslyn,CaptainHayashi/roslyn,danielcweber/roslyn,tang7526/roslyn,natgla/roslyn,GuilhermeSa/roslyn,AlekseyTs/roslyn,jroggeman/roslyn,dsplaisted/roslyn,ahmedshuhel/roslyn,sharadagrawal/Roslyn,xoofx/roslyn,mgoertz-msft/roslyn,jgglg/roslyn,marksantos/roslyn,yeaicc/roslyn,furesoft/roslyn,lorcanmooney/roslyn,aelij/roslyn,khellang/roslyn,KevinH-MS/roslyn,kuhlenh/roslyn,JakeGinnivan/roslyn,michalhosala/roslyn,vcsjones/roslyn,CyrusNajmabadi/roslyn,akoeplinger/roslyn,hanu412/roslyn,droyad/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,jbhensley/roslyn,ahmedshuhel/roslyn,jroggeman/roslyn,ValentinRueda/roslyn,nemec/roslyn,stebet/roslyn,gafter/roslyn,KashishArora/Roslyn,marksantos/roslyn,BugraC/roslyn,KevinH-MS/roslyn,bbarry/roslyn,diryboy/roslyn,jramsay/roslyn,KamalRathnayake/roslyn,tang7526/roslyn,poizan42/roslyn,oberxon/roslyn,paulvanbrenk/roslyn,basoundr/roslyn,paulvanbrenk/roslyn,stjeong/roslyn,magicbing/roslyn,ahmedshuhel/roslyn,krishnarajbb/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,tmeschter/roslyn,BugraC/roslyn,VPashkov/roslyn,OmarTawfik/roslyn,VSadov/roslyn,antiufo/roslyn,physhi/roslyn,mavasani/roslyn,jeffanders/roslyn,poizan42/roslyn,rchande/roslyn,nagyistoce/roslyn,dpen2000/roslyn,Giftednewt/roslyn,shyamnamboodiripad/roslyn,oocx/roslyn,dovzhikova/roslyn,mmitche/roslyn,huoxudong125/roslyn,russpowers/roslyn,VitalyTVA/roslyn,AnthonyDGreen/roslyn,zooba/roslyn,yeaicc/roslyn,doconnell565/roslyn,thomaslevesque/roslyn,KiloBravoLima/roslyn,jhendrixMSFT/roslyn,heejaechang/roslyn,eriawan/roslyn,mirhagk/roslyn,vslsnap/roslyn,kuhlenh/roslyn,MatthieuMEZIL/roslyn,RipCurrent/roslyn,OmniSharp/roslyn,GuilhermeSa/roslyn,dpoeschl/roslyn,taylorjonl/roslyn,paulvanbrenk/roslyn,Hosch250/roslyn,Shiney/roslyn,pdelvo/roslyn,Giten2004/roslyn,tmat/roslyn,chenxizhang/roslyn,Inverness/roslyn,KevinH-MS/roslyn,vcsjones/roslyn,MatthieuMEZIL/roslyn,ValentinRueda/roslyn,mavasani/roslyn,RipCurrent/roslyn,weltkante/roslyn,antiufo/roslyn,OmarTawfik/roslyn,budcribar/roslyn,garryforreg/roslyn,panopticoncentral/roslyn,kienct89/roslyn,KevinRansom/roslyn,nemec/roslyn,abock/roslyn,jcouv/roslyn,rchande/roslyn,AlekseyTs/roslyn,VSadov/roslyn,nagyistoce/roslyn,cybernet14/roslyn,lisong521/roslyn,MavenRain/roslyn,xasx/roslyn,1234-/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,SeriaWei/roslyn,yjfxfjch/roslyn,balajikris/roslyn,danielcweber/roslyn,diryboy/roslyn,lisong521/roslyn,VitalyTVA/roslyn,pjmagee/roslyn,antiufo/roslyn,mmitche/roslyn,xoofx/roslyn,pjmagee/roslyn,pjmagee/roslyn,abock/roslyn,1234-/roslyn,ManishJayaswal/roslyn,agocke/roslyn,pdelvo/roslyn,dovzhikova/roslyn,MihaMarkic/roslyn-prank,CyrusNajmabadi/roslyn,Inverness/roslyn,dotnet/roslyn,weltkante/roslyn,basoundr/roslyn,hanu412/roslyn,TyOverby/roslyn,oocx/roslyn,tsdl2013/roslyn,davkean/roslyn,ljw1004/roslyn,jasonmalinowski/roslyn,jkotas/roslyn,balajikris/roslyn,drognanar/roslyn,swaroop-sridhar/roslyn,mattwar/roslyn,bbarry/roslyn,ErikSchierboom/roslyn,DinoV/roslyn,YOTOV-LIMITED/roslyn,GuilhermeSa/roslyn,reaction1989/roslyn,gafter/roslyn,hanu412/roslyn,VSadov/roslyn,DustinCampbell/roslyn,paladique/roslyn,xasx/roslyn,rgani/roslyn,michalhosala/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,danielcweber/roslyn,nguerrera/roslyn,lorcanmooney/roslyn,aelij/roslyn,sharwell/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,stephentoub/roslyn,russpowers/roslyn
src/EditorFeatures/Test/CodeAnalysisResources.cs
src/EditorFeatures/Test/CodeAnalysisResources.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Resources; namespace Microsoft.CodeAnalysis { // This class exists as a way to load resources from the Microsoft.CodeAnalysis.CodeAnalysisResources class from // the Microsoft.CodeAnalysis assembly. Microsoft.CodeAnalysis.CodeAnalysisResources is internal but we can't add // InternalsVisibleTo(this-assembly) because there are numerous shared (linked) files common to both // Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.Workspaces and that gives us major issues with duplicate // internal types that suddenly become visible (e.g., SpecializedCollections) and that leads down a rabbit hole // of requiring assembly aliasing that would make many tests in this project unreadable. The descision was made to // manually load the few resources we need from the CodeAnalysis assembly at the cost of Find All References and // Rename not working as expected. internal static class CodeAnalysisResources { public static string InMemoryAssembly => GetString("InMemoryAssembly"); private static ResourceManager _codeAnalysisResourceManager; private static string GetString(string resourceName) { if (_codeAnalysisResourceManager == null) { _codeAnalysisResourceManager = new ResourceManager("Microsoft.CodeAnalysis.CodeAnalysisResources", typeof(Compilation).Assembly); } return _codeAnalysisResourceManager.GetString(resourceName); } } }
using System.Resources; namespace Microsoft.CodeAnalysis { // This class exists as a way to load resources from the Microsoft.CodeAnalysis.CodeAnalysisResources class from // the Microsoft.CodeAnalysis assembly. Microsoft.CodeAnalysis.CodeAnalysisResources is internal but we can't add // InternalsVisibleTo(this-assembly) because there are numerous shared (linked) files common to both // Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.Workspaces and that gives us major issues with duplicate // internal types that suddenly become visible (e.g., SpecializedCollections) and that leads down a rabbit hole // of requiring assembly aliasing that would make many tests in this project unreadable. The descision was made to // manually load the few resources we need from the CodeAnalysis assembly at the cost of Find All References and // Rename not working as expected. internal static class CodeAnalysisResources { public static string InMemoryAssembly => GetString("InMemoryAssembly"); private static ResourceManager _codeAnalysisResourceManager; private static string GetString(string resourceName) { if (_codeAnalysisResourceManager == null) { _codeAnalysisResourceManager = new ResourceManager("Microsoft.CodeAnalysis.CodeAnalysisResources", typeof(Compilation).Assembly); } return _codeAnalysisResourceManager.GetString(resourceName); } } }
apache-2.0
C#
cc61c53579ea9714abfc881565a89c7c9882dc9b
Refactor virtual judge user table schema
JoyOI/OnlineJudge,JoyOI/OnlineJudge,JoyOI/OnlineJudge,JoyOI/OnlineJudge
src/JoyOI.OnlineJudge.Models/VirtualJudgeUser.cs
src/JoyOI.OnlineJudge.Models/VirtualJudgeUser.cs
using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets the locker id. /// </summary> /// <value>The locker id.</value> public Guid? LockerId { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:JoyOI.OnlineJudge.Models.VirtualJudgeUser"/> is in use. /// </summary> /// <value><c>true</c> if is in use; otherwise, <c>false</c>.</value> public bool IsInUse { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } }
mit
C#
30cff58da2c68a7e06525a69df5da95a1588ca49
Remove duplicate memory barrier
AdaptiveConsulting/Aeron.NET,AdaptiveConsulting/Aeron.NET
src/Adaptive.Aeron/LogBuffer/HeaderWriter.cs
src/Adaptive.Aeron/LogBuffer/HeaderWriter.cs
using System.Threading; using Adaptive.Aeron.Protocol; using Adaptive.Agrona; using Adaptive.Agrona.Concurrent; namespace Adaptive.Aeron.LogBuffer { /// <summary> /// Utility for applying a header to a message in a term buffer. /// /// This class is designed to be thread safe to be used across multiple producers and makes the header /// visible in the correct order for consumers. /// </summary> public class HeaderWriter { private readonly long _versionFlagsType; private readonly long _sessionId; private readonly long _streamId; public HeaderWriter() { } public HeaderWriter(IDirectBuffer defaultHeader) { _versionFlagsType = (long)defaultHeader.GetInt(HeaderFlyweight.VERSION_FIELD_OFFSET) << 32; _sessionId = (long)defaultHeader.GetInt(DataHeaderFlyweight.SESSION_ID_FIELD_OFFSET) << 32; _streamId = defaultHeader.GetInt(DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET) & 0xFFFFFFFFL; } /// <summary> /// Write a header to the term buffer in <seealso cref="ByteOrder.LittleEndian"/> format using the minimum instructions. /// </summary> /// <param name="termBuffer"> to be written to. </param> /// <param name="offset"> at which the header should be written. </param> /// <param name="length"> of the fragment including the header. </param> /// <param name="termId"> of the current term buffer. </param> public virtual void Write(IAtomicBuffer termBuffer, int offset, int length, int termId) { var lengthVersionFlagsType = _versionFlagsType | (-length & 0xFFFFFFFFL); var termOffsetSessionId = _sessionId | (uint)offset; var streamAndTermIds = _streamId | ((long)termId << 32); termBuffer.PutLongOrdered(offset + HeaderFlyweight.FRAME_LENGTH_FIELD_OFFSET, lengthVersionFlagsType); // PutLongOrdered use Volatile.Write that already generates an implicit memory barrier // no need for Thread.MemoryBarrier(); termBuffer.PutLong(offset + DataHeaderFlyweight.TERM_OFFSET_FIELD_OFFSET, termOffsetSessionId); termBuffer.PutLong(offset + DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET, streamAndTermIds); } } }
using System.Threading; using Adaptive.Aeron.Protocol; using Adaptive.Agrona; using Adaptive.Agrona.Concurrent; namespace Adaptive.Aeron.LogBuffer { /// <summary> /// Utility for applying a header to a message in a term buffer. /// /// This class is designed to be thread safe to be used across multiple producers and makes the header /// visible in the correct order for consumers. /// </summary> public class HeaderWriter { private readonly long _versionFlagsType; private readonly long _sessionId; private readonly long _streamId; public HeaderWriter() { } public HeaderWriter(IDirectBuffer defaultHeader) { _versionFlagsType = (long)defaultHeader.GetInt(HeaderFlyweight.VERSION_FIELD_OFFSET) << 32; _sessionId = (long)defaultHeader.GetInt(DataHeaderFlyweight.SESSION_ID_FIELD_OFFSET) << 32; _streamId = defaultHeader.GetInt(DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET) & 0xFFFFFFFFL; } /// <summary> /// Write a header to the term buffer in <seealso cref="ByteOrder.LittleEndian"/> format using the minimum instructions. /// </summary> /// <param name="termBuffer"> to be written to. </param> /// <param name="offset"> at which the header should be written. </param> /// <param name="length"> of the fragment including the header. </param> /// <param name="termId"> of the current term buffer. </param> public virtual void Write(IAtomicBuffer termBuffer, int offset, int length, int termId) { var lengthVersionFlagsType = _versionFlagsType | (-length & 0xFFFFFFFFL); var termOffsetSessionId = _sessionId | (uint)offset; var streamAndTermIds = _streamId | ((long)termId << 32); //TODO why not just putlongvolatile? termBuffer.PutLongOrdered(offset + HeaderFlyweight.FRAME_LENGTH_FIELD_OFFSET, lengthVersionFlagsType); Thread.MemoryBarrier(); termBuffer.PutLong(offset + DataHeaderFlyweight.TERM_OFFSET_FIELD_OFFSET, termOffsetSessionId); termBuffer.PutLong(offset + DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET, streamAndTermIds); } } }
apache-2.0
C#
f99c3cdbfaaf3eaa73e59f54bcd67d204739218b
update running program code
RedSpiderMkV/LANMachines
src/LANMachines/LanMachinesRunner/Program.cs
src/LANMachines/LanMachinesRunner/Program.cs
using System; using System.Collections.Generic; using LanDiscovery; namespace LanMachines { internal class Program { internal static void Main(string[] args) { LanDiscoveryManager lanDiscovery = new LanDiscoveryManager(); List<string> lanMachines = lanDiscovery.GetNetworkMachines(); printStringList(lanMachines); Console.WriteLine("LAN ping complete"); Console.ReadKey(); } // end method private static void printStringList(List<string> stringList) { foreach (string s in stringList) { Console.WriteLine(s); } // end foreach } // end method } // end class } // end namespace
using System; using System.Collections.Generic; using LanDiscovery; namespace LanMachines { class Program { internal static void Main(string[] args) { LanDiscoveryManager lanDiscovery = new LanDiscoveryManager(); List<string> lanMachines = lanDiscovery.GetNetworkMachines(); foreach (string lanIp in lanMachines) { Console.WriteLine(lanIp); } Console.WriteLine("LAN ping complete"); Console.ReadKey(); } // end method } // end class } // end namespace
mit
C#
cf079690e528cadd4387402ca2a050d388604796
Use LargeTextureStore for online retrievals
UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,naoey/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,naoey/osu,peppy/osu,ZLima12/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu
osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs
osu.Game/Beatmaps/Drawables/BeatmapSetCover.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.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } }
// 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.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(TextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } }
mit
C#
37053608f1544f0a6a294b6695cbac323730931c
Use registered types for Out of Band handlers in packet handling type finder
ethanmoffat/EndlessClient
EOLib/Net/Handlers/PacketHandlingTypeFinder.cs
EOLib/Net/Handlers/PacketHandlingTypeFinder.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; using System.Linq; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder(IEnumerable<IPacketHandler> outOfBandHandlers) { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = outOfBandHandlers.Select(x => new FamilyActionPair(x.Family, x.Action)).ToList(); } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder() { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Connection, PacketAction.Player) }; } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }
mit
C#
1ce50db88ec5bf59f92bf92696d43ba645863542
test fix
stanac/LiteApi,stanac/LiteApi,stanac/LiteApi
LiteApi/LiteApi.Tests/LiteApiMiddleareTests.cs
LiteApi/LiteApi.Tests/LiteApiMiddleareTests.cs
using System; using System.Threading.Tasks; using Xunit; namespace LiteApi.Tests { public class LiteApiMiddleareTests { [Fact] public async Task LiteApiMiddleareTests_Registered_CanBeInvoked() { var servicesMock = new Moq.Mock<IServiceProvider>(); servicesMock.Setup(x => x.GetService(typeof(IServiceProvider))).Returns(servicesMock.Object); var middleware = new LiteApiMiddleware(null, LiteApiOptions.Default, servicesMock.Object); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.Request.Method = "GET"; httpCtx.Request.Path = "/"; await middleware.Invoke(httpCtx); // expect exception on next registration TestExtensions.AssertExpectedException<Exception>(() => new LiteApiMiddleware(null, LiteApiOptions.Default, null), "Middleware can be registered twice"); } } }
using System; using System.Threading.Tasks; using Xunit; namespace LiteApi.Tests { public class LiteApiMiddleareTests { [Fact] public async Task LiteApiMiddleareTests_Registered_CanBeInvoked() { var middleware = new LiteApiMiddleware(null, LiteApiOptions.Default, (new Moq.Mock<IServiceProvider>()).Object); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.Request.Method = "GET"; httpCtx.Request.Path = "/"; await middleware.Invoke(httpCtx); // expect exception on next registration TestExtensions.AssertExpectedException<Exception>(() => new LiteApiMiddleware(null, LiteApiOptions.Default, null), "Middleware can be registered twice"); } } }
mit
C#
0b3a6a754bb9ac140d8c41af416fe14c16976345
Fix bug where ther are no recipieints in To/Cc line
mrpeterson27/mail2bug,vitru/mail2bug,Spurrya/mail2bug
Mail2Bug/Email/EWS/RecipientsMailboxManager.cs
Mail2Bug/Email/EWS/RecipientsMailboxManager.cs
using System; using System.Collections.Generic; using System.Linq; namespace Mail2Bug.Email.EWS { /// <summary> /// This imiplementation of IMailboxManager monitors the inbox of an exchange user, and retrieves /// only messages that have a specific alias in the 'To' or 'CC' lines /// It can be initialized with a list of displayNames, in which case, if any of the displayNames are in the 'To' /// or 'CC' lines, the message will be retrieved /// </summary> public class RecipientsMailboxManager : IMailboxManager { private readonly IMessagePostProcessor _postProcessor; private readonly RecipientsMailboxManagerRouter _router; private readonly int _clientId; public RecipientsMailboxManager(RecipientsMailboxManagerRouter router, IEnumerable<string> recipients, IMessagePostProcessor postProcessor) { _router = router; _postProcessor = postProcessor; _clientId = _router.RegisterMailbox(m => ShouldConsiderMessage(m, recipients.ToArray())); } public IEnumerable<IIncomingEmailMessage> ReadMessages() { return _router.GetMessages(_clientId); } public void OnProcessingFinished(IIncomingEmailMessage message, bool successful) { _postProcessor.Process((EWSIncomingMessage)message, successful); } private static bool ShouldConsiderMessage(IIncomingEmailMessage message, string[] recipients) { if (message == null) { return false; } // If no recipients were mentioned, it means process all incoming emails if (!recipients.Any()) { return true; } // If the recipient is in either the To or CC lines, then this message should be considered return recipients.Any(recipient => EmailAddressesMatch(message.ToAddresses, recipient) || EmailAddressesMatch(message.ToNames, recipient) || EmailAddressesMatch(message.CcAddresses, recipient) || EmailAddressesMatch(message.CcNames, recipient)); } private static bool EmailAddressesMatch(IEnumerable<string> emailAddresses, string recipient) { return emailAddresses != null && emailAddresses.Any(address => address != null && address.Equals(recipient, StringComparison.InvariantCultureIgnoreCase)); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Mail2Bug.Email.EWS { /// <summary> /// This imiplementation of IMailboxManager monitors the inbox of an exchange user, and retrieves /// only messages that have a specific alias in the 'To' or 'CC' lines /// It can be initialized with a list of displayNames, in which case, if any of the displayNames are in the 'To' /// or 'CC' lines, the message will be retrieved /// </summary> public class RecipientsMailboxManager : IMailboxManager { private readonly IMessagePostProcessor _postProcessor; private readonly RecipientsMailboxManagerRouter _router; private readonly int _clientId; public RecipientsMailboxManager(RecipientsMailboxManagerRouter router, IEnumerable<string> recipients, IMessagePostProcessor postProcessor) { _router = router; _postProcessor = postProcessor; _clientId = _router.RegisterMailbox(m => ShouldConsiderMessage(m, recipients.ToArray())); } public IEnumerable<IIncomingEmailMessage> ReadMessages() { return _router.GetMessages(_clientId); } public void OnProcessingFinished(IIncomingEmailMessage message, bool successful) { _postProcessor.Process((EWSIncomingMessage)message, successful); } private static bool ShouldConsiderMessage(IIncomingEmailMessage message, string[] recipients) { if (message == null) { return false; } // If no recipients were mentioned, it means process all incoming emails if (!recipients.Any()) { return true; } // If the recipient is in either the To or CC lines, then this message should be considered return recipients.Any(recipient => EmailAddressesMatch(message.ToAddresses, recipient) || EmailAddressesMatch(message.ToNames, recipient) || EmailAddressesMatch(message.CcAddresses, recipient) || EmailAddressesMatch(message.CcNames, recipient)); } private static bool EmailAddressesMatch(IEnumerable<string> emailAddresses, string recipient) { return emailAddresses != null && emailAddresses.Any(address => address.Equals(recipient, StringComparison.InvariantCultureIgnoreCase)); } } }
mit
C#
29b03145c95baf3210c828a689409f7c4158ba41
work around for NUnit GUI runner problem
ShaKaRee/concordion-net,ShaKaRee/concordion-net,ShaKaRee/concordion-net,concordion/concordion-net,concordion/concordion-net,concordion/concordion-net
Concordion.Spec/Concordion/Configuration/BaseInputDirectoryTest.cs
Concordion.Spec/Concordion/Configuration/BaseInputDirectoryTest.cs
using System; using System.Collections.Generic; using System.Linq; using Concordion.Integration; using Concordion.Internal; using System.IO; namespace Concordion.Spec.Concordion.Configuration { [ConcordionTest] public class BaseInputDirectoryTest { private static bool m_InTestRun = false; public bool DirectoryBasedExecuted(string baseInputDirectory) { if (m_InTestRun) return true; m_InTestRun = true; //work around for bug of NUnit GUI runner baseInputDirectory = baseInputDirectory + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + this.GetType().Assembly.GetName().Name; var specificationConfig = new SpecificationConfig().Load(this.GetType()); specificationConfig.BaseInputDirectory = baseInputDirectory; var fixtureRunner = new FixtureRunner(specificationConfig); var testResult = fixtureRunner.Run(this); m_InTestRun = false; foreach (var failureDetail in testResult.FailureDetails) { Console.WriteLine(failureDetail.Message); Console.WriteLine(failureDetail.StackTrace); } foreach (var errorDetail in testResult.ErrorDetails) { Console.WriteLine(errorDetail.Message); Console.WriteLine(errorDetail.StackTrace); Console.WriteLine(errorDetail.Exception); } return !testResult.HasFailures && !testResult.HasExceptions; } public bool EmbeddedExecuted() { if (m_InTestRun) return true; m_InTestRun = true; var specificationConfig = new SpecificationConfig().Load(this.GetType()); specificationConfig.BaseInputDirectory = null; var fixtureRunner = new FixtureRunner(specificationConfig); var testResult = fixtureRunner.Run(this); m_InTestRun = false; return !testResult.HasFailures && !testResult.HasExceptions; } } }
using System; using System.Collections.Generic; using System.Linq; using Concordion.Integration; using Concordion.Internal; namespace Concordion.Spec.Concordion.Configuration { [ConcordionTest] public class BaseInputDirectoryTest { private static bool m_InTestRun = false; public bool DirectoryBasedExecuted(string baseInputDirectory) { if (m_InTestRun) return true; m_InTestRun = true; var specificationConfig = new SpecificationConfig().Load(this.GetType()); specificationConfig.BaseInputDirectory = baseInputDirectory; var fixtureRunner = new FixtureRunner(specificationConfig); var testResult = fixtureRunner.Run(this); m_InTestRun = false; return !testResult.HasFailures && !testResult.HasExceptions; } public bool EmbeddedExecuted() { if (m_InTestRun) return true; m_InTestRun = true; var specificationConfig = new SpecificationConfig().Load(this.GetType()); specificationConfig.BaseInputDirectory = null; var fixtureRunner = new FixtureRunner(specificationConfig); var testResult = fixtureRunner.Run(this); m_InTestRun = false; return !testResult.HasFailures && !testResult.HasExceptions; } } }
apache-2.0
C#
084e7fc2d8bd4f9dd169395bb33ed0fff65ff520
Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain.
IvionSauce/MeidoBot
Chainey/SentenceConstruct.cs
Chainey/SentenceConstruct.cs
using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get; private set; } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { var chain = new string[order]; int start = Forwards.Count - order; Forwards.CopyTo(start, chain, 0, order); return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { var chain = new string[order]; int start = Backwards.Count - order; Backwards.CopyTo(start, chain, 0, order); return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); WordCount = split.Length; order = split.Length; } internal void Append(string word) { Forwards.Add(word); WordCount++; } internal void Prepend(string word) { Backwards.Add(word); WordCount++; } } }
using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get { return Forwards.Count + Backwards.Count - order; } } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { int start = Forwards.Count - order; return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { int start = Backwards.Count - order; return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain, int order) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); this.order = order; } internal void Append(string word) { Forwards.Add(word); } internal void Prepend(string word) { Backwards.Add(word); } } }
bsd-2-clause
C#
597f3ee243aa7d6bbeff4ca991bec61f2cf8f29f
Update Nuget version of package to 1.1.0.10-rc
KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet
src/keypay-dotnet/Properties/AssemblyInfo.cs
src/keypay-dotnet/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc2")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
221cdf1c003652b67f58b86ddfe811e775c6caeb
fix code factor issues.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/MainViewModel.cs
WalletWasabi.Fluent/ViewModels/MainViewModel.cs
using Avalonia.Threading; using NBitcoin; using NBitcoin.Protocol; using ReactiveUI; using System; using System.Collections.Generic; using System.Reactive; using System.Text; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using Global = WalletWasabi.Gui.Global; namespace WalletWasabi.Fluent.ViewModels { public class MainViewModel : ViewModelBase, IScreen { private Global _global; private StatusBarViewModel _statusBar; private string _title = "Wasabi Wallet"; public MainViewModel(Global global) { _global = global; Network = global.Network; StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments); Dispatcher.UIThread.Post(async () => { await Task.Delay(5000); Router.Navigate.Execute(new HomeViewModel(this)); }); } public static MainViewModel Instance { get; internal set; } public RoutingState Router { get; } = new RoutingState(); public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; } public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack; public Network Network { get; } public StatusBarViewModel StatusBar { get { return _statusBar; } set { this.RaiseAndSetIfChanged(ref _statusBar, value); } } public string Title { get => _title; internal set => this.RaiseAndSetIfChanged(ref _title, value); } public void Initialize() { // Temporary to keep things running without VM modifications. MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false); StatusBar.Initialize(_global.Nodes.ConnectedNodes); if (Network != Network.Main) { Title += $" - {Network}"; } } } }
using Avalonia.Threading; using NBitcoin; using NBitcoin.Protocol; using ReactiveUI; using System; using System.Collections.Generic; using System.Reactive; using System.Text; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using Global = WalletWasabi.Gui.Global; namespace WalletWasabi.Fluent.ViewModels { public class MainViewModel : ViewModelBase, IScreen { private Global _global; private StatusBarViewModel _statusBar; private string _title = "Wasabi Wallet"; public static MainViewModel Instance { get; internal set; } public MainViewModel(Global global) { _global = global; Network = global.Network; StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments); Dispatcher.UIThread.Post(async () => { await Task.Delay(5000); Router.Navigate.Execute(new HomeViewModel(this)); }); } public void Initialize() { /// Temporary to keep things running without VM modifications. MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false); StatusBar.Initialize(_global.Nodes.ConnectedNodes); if (Network != Network.Main) { Title += $" - {Network}"; } } public RoutingState Router { get; } = new RoutingState(); public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; } public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack; public Network Network { get; } public StatusBarViewModel StatusBar { get { return _statusBar; } set { this.RaiseAndSetIfChanged(ref _statusBar, value); } } public string Title { get => _title; internal set => this.RaiseAndSetIfChanged(ref _title, value); } } }
mit
C#
dd94ed971803948c33a87ccce4469db0da3c9f6c
remove leftover
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/MainViewModel.cs
WalletWasabi.Fluent/ViewModels/MainViewModel.cs
#nullable enable using NBitcoin; using ReactiveUI; using System.Reactive; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Fluent.ViewModels.Dialog; using System; using Global = WalletWasabi.Gui.Global; namespace WalletWasabi.Fluent.ViewModels { public class MainViewModel : ViewModelBase, IScreen, IDialogHost { private Global _global; private StatusBarViewModel _statusBar; private string _title = "Wasabi Wallet"; private DialogViewModelBase? _currentDialog; private NavBarViewModel _navBar; public MainViewModel(Global global) { _global = global; Network = global.Network; StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments); NavBar = new NavBarViewModel(this, Router, global.WalletManager, global.UiConfig); } public static MainViewModel Instance { get; internal set; } public RoutingState Router { get; } = new RoutingState(); public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; } public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack; public Network Network { get; } public DialogViewModelBase? CurrentDialog { get => _currentDialog; set => this.RaiseAndSetIfChanged(ref _currentDialog, value); } public NavBarViewModel NavBar { get => _navBar; set => this.RaiseAndSetIfChanged(ref _navBar, value); } public StatusBarViewModel StatusBar { get => _statusBar; set => this.RaiseAndSetIfChanged(ref _statusBar, value); } public string Title { get => _title; internal set => this.RaiseAndSetIfChanged(ref _title, value); } public void Initialize() { // Temporary to keep things running without VM modifications. MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false); StatusBar.Initialize(_global.Nodes.ConnectedNodes); if (Network != Network.Main) { Title += $" - {Network}"; } } } }
#nullable enable using NBitcoin; using ReactiveUI; using System.Reactive; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Fluent.ViewModels.Dialog; using System; using Global = WalletWasabi.Gui.Global; namespace WalletWasabi.Fluent.ViewModels { public class MainViewModel : ViewModelBase, IScreen, IDialogHost { private Global _global; private StatusBarViewModel _statusBar; private string _title = "Wasabi Wallet"; private DialogViewModelBase? _currentDialog; private NavBarViewModel _navBar; public MainViewModel(Global global) { _global = global; Network = global.Network; StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments); NavBar = new NavBarViewModel(this, Router, global.WalletManager, global.UiConfig); } private Action<bool> DialogStateListener { get; set; } public static MainViewModel Instance { get; internal set; } public RoutingState Router { get; } = new RoutingState(); public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; } public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack; public Network Network { get; } public DialogViewModelBase? CurrentDialog { get => _currentDialog; set => this.RaiseAndSetIfChanged(ref _currentDialog, value); } public NavBarViewModel NavBar { get => _navBar; set => this.RaiseAndSetIfChanged(ref _navBar, value); } public StatusBarViewModel StatusBar { get => _statusBar; set => this.RaiseAndSetIfChanged(ref _statusBar, value); } public string Title { get => _title; internal set => this.RaiseAndSetIfChanged(ref _title, value); } public void Initialize() { // Temporary to keep things running without VM modifications. MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false); StatusBar.Initialize(_global.Nodes.ConnectedNodes); if (Network != Network.Main) { Title += $" - {Network}"; } } } }
mit
C#
9dbbc383e3abc0d93c8ceb0dab0c4f0b85b1b324
switch to hitting 6080 for test
agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro
api/Search.Api/Services/QuerySoeServiceAsync.cs
api/Search.Api/Services/QuerySoeServiceAsync.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Net.Http; using System.Threading.Tasks; using Containers; using Newtonsoft.Json.Linq; using Search.Api.Formatters; using Search.Api.Properties; namespace Search.Api.Services { public class QuerySoeServiceAsync : IQuerySoeService { private string _url = "/arcgis/rest/services/DEQEnviro/MapService/MapServer/exts/DeqSearchSoe/Search"; /// <summary> /// Queries the soe with specified values form value encoded. /// </summary> /// <param name="formValues">The form values.</param> /// <param name="secure"> /// if set to <c>true</c> [secure]. /// </param> /// <returns></returns> public async Task<ResponseContainer<Dictionary<int, JObject>>> Query( IEnumerable<KeyValuePair<string, string>> formValues, bool secure) { using (var client = new HttpClient()) { var baseUrl = "http://test.mapserv.utah.gov:6080"; #if DEBUG baseUrl = "http://localhost"; #endif #if RELEASE baseUrl = "http://mapserv.utah.gov"; #endif client.BaseAddress = new Uri(baseUrl); var content = new MultipartFormDataContent(); foreach (var pair in formValues) { content.Add(new StringContent(pair.Value), pair.Key); } if (secure) { _url = "/arcgis/rest/services/DEQEnviro/Secure/MapServer/exts/DeqSearchSoe/Search"; } var response = await client.PostAsync(_url, content); return await response.Content.ReadAsAsync<ResponseContainer<Dictionary<int, JObject>>>( new[] { new TextPlainResponseFormatter() }); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Net.Http; using System.Threading.Tasks; using Containers; using Newtonsoft.Json.Linq; using Search.Api.Formatters; using Search.Api.Properties; namespace Search.Api.Services { public class QuerySoeServiceAsync : IQuerySoeService { private string _url = "/arcgis/rest/services/DEQEnviro/MapService/MapServer/exts/DeqSearchSoe/Search"; /// <summary> /// Queries the soe with specified values form value encoded. /// </summary> /// <param name="formValues">The form values.</param> /// <param name="secure"> /// if set to <c>true</c> [secure]. /// </param> /// <returns></returns> public async Task<ResponseContainer<Dictionary<int, JObject>>> Query( IEnumerable<KeyValuePair<string, string>> formValues, bool secure) { using (var client = new HttpClient()) { var baseUrl = "http://test.mapserv.utah.gov"; #if DEBUG baseUrl = "http://localhost"; #endif #if RELEASE baseUrl = "http://mapserv.utah.gov"; #endif client.BaseAddress = new Uri(baseUrl); var content = new MultipartFormDataContent(); foreach (var pair in formValues) { content.Add(new StringContent(pair.Value), pair.Key); } if (secure) { _url = "/arcgis/rest/services/DEQEnviro/Secure/MapServer/exts/DeqSearchSoe/Search"; } var response = await client.PostAsync(_url, content); return await response.Content.ReadAsAsync<ResponseContainer<Dictionary<int, JObject>>>( new[] { new TextPlainResponseFormatter() }); } } } }
mit
C#
780e0ba51a884cf63a3277e0e4442a17959a3459
Fix CloudflareSolver
InfiniteSoul/Azuria
Azuria/Utilities/Net/CloudflareSolver.cs
Azuria/Utilities/Net/CloudflareSolver.cs
using System; using System.Text.RegularExpressions; using Azuria.Utilities.ErrorHandling; using JetBrains.Annotations; namespace Azuria.Utilities.Net { internal static class CloudflareSolver { #region internal static ProxerResult<string> Solve([NotNull] string response, [NotNull] Uri originalUri) { try { GroupCollection lWierdEquasion = new Regex(@"(var s, t, o, p[\S\s]+?};)[\S\s]+?(zyrziLd[\S\s]+?)a\.value = parseInt[\S\s]+?;").Match( response).Groups; string lScript = "var " + lWierdEquasion[1] + lWierdEquasion[2]; int lCloudflareAnswer = Convert.ToInt32(JsEval.Eval(lScript)) + originalUri.Host.Length; string lChallengeId = new Regex("name=\"jschl_vc\" value=\"(\\w+)\"").Match(response).Groups[1].Value; string lChallengePass = new Regex("name=\"pass\" value=\"(.+?)\"").Match(response).Groups[1].Value; if (string.IsNullOrEmpty(lChallengeId.Trim()) || string.IsNullOrEmpty(lChallengePass.Trim()) || lCloudflareAnswer == int.MinValue) return new ProxerResult<string>(new Exception[0]); return new ProxerResult<string>( $"jschl_vc={lChallengeId}&pass={lChallengePass}&jschl_answer={lCloudflareAnswer}"); } catch { return new ProxerResult<string>(new Exception[0]); } } #endregion } }
using System; using System.Text.RegularExpressions; using Azuria.Utilities.ErrorHandling; using JetBrains.Annotations; namespace Azuria.Utilities.Net { internal static class CloudflareSolver { #region internal static ProxerResult<string> Solve([NotNull] string response, [NotNull] Uri originalUri) { try { string lWierdVarMatch = new Regex("var\\s*?t,r,a,f,\\s?(\\S+?;)").Match(response).Groups[1].Value; string lWierdVar = lWierdVarMatch.Split('=')[0]; string lWierdEquasion = new Regex($"({lWierdVar}\\S+?);a.value = parseInt").Match(response).Groups[1].Value; string lScript = "var " + lWierdVarMatch + lWierdEquasion; int lCloudflareAnswer = Convert.ToInt32(JsEval.Eval(lScript)) + originalUri.Host.Length; string lChallengeId = new Regex("name=\"jschl_vc\" value=\"(\\w+)\"").Match(response).Groups[1].Value; string lChallengePass = new Regex("name=\"pass\" value=\"(.+?)\"").Match(response).Groups[1].Value; if (string.IsNullOrEmpty(lChallengeId.Trim()) || string.IsNullOrEmpty(lChallengePass.Trim()) || lCloudflareAnswer == int.MinValue) return new ProxerResult<string>(new Exception[0]); return new ProxerResult<string>( $"jschl_vc={lChallengeId}&pass={lChallengePass}&jschl_answer={lCloudflareAnswer}"); } catch { return new ProxerResult<string>(new Exception[0]); } } #endregion } }
mit
C#
5db837d4d8879d131046f725c5a8abcb182fa7cb
fix build
GregTrevellick/OpenInApp.Launcher,GregTrevellick/OpenInApp.Launcher,GregTrevellick/OpenInApp.Launcher
src/OpenInApp.Common/Helpers/AllAppsHelper.cs
src/OpenInApp.Common/Helpers/AllAppsHelper.cs
using System.Collections.Generic; using System.Text; namespace OpenInApp.Common.Helpers { public class AllAppsHelper { /// <summary> /// Checks if a specified artefact exists on disc. /// </summary> /// <param name="fullExecutableFileName">Full name of the artefact.</param> /// <returns></returns> public static bool DoesActualPathToExeExist(string fullExecutableFileName) { return ArtefactsHelper.DoArtefactsExist(new List<string> { fullExecutableFileName }); } /// <summary> /// Gets the typical file extensions as a CSV string. /// </summary> /// <param name="defaultExts">The default exts.</param> /// <returns></returns> public static string GetDefaultTypicalFileExtensionsAsCsv(IEnumerable<string> defaultExts) { var stringBuilder = new StringBuilder(); foreach (var defaultExt in defaultExts) { stringBuilder.Append(defaultExt).Append(','); } return stringBuilder.ToString().TrimEnd(','); } } }
using System.Collections.Generic; using System.Text; namespace OpenInApp.Common.Helpers { public class AllAppsHelper { /// <summary> /// Checks if a specified artefact exists on disc. /// </summary> /// <param name="fullExecutableFileName">Full name of the artefact.</param> /// <returns></returns> public static bool DoesActualPathToExeExist(string fullExecutableFileName) { return CommonFileHelper.DoArtefactsExist(new List<string> { fullExecutableFileName }); } /// <summary> /// Gets the typical file extensions as a CSV string. /// </summary> /// <param name="defaultExts">The default exts.</param> /// <returns></returns> public static string GetDefaultTypicalFileExtensionsAsCsv(IEnumerable<string> defaultExts) { var stringBuilder = new StringBuilder(); foreach (var defaultExt in defaultExts) { stringBuilder.Append(defaultExt).Append(','); } return stringBuilder.ToString().TrimEnd(','); } } }
mit
C#
9728f26455b64f29f440503d01dbe7efd8bb298c
fix typo error for brokerList for autofac ioc
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework.Plugins/IFramework.MessageQueue.ConfluentKafka/Config/FrameworkConfigurationExtension.cs
Src/iFramework.Plugins/IFramework.MessageQueue.ConfluentKafka/Config/FrameworkConfigurationExtension.cs
using IFramework.Config; using IFramework.IoC; namespace IFramework.MessageQueue.ConfluentKafka.Config { public static class FrameworkConfigurationExtension { private static int _backOffIncrement = 30; public static Configuration UseConfluentKafka(this Configuration configuration, string brokerlist, int backOffIncrement = 30) { IoCFactory.Instance.CurrentContainer .RegisterType<IMessageQueueClient, ConfluentKafkaClient>(Lifetime.Singleton, new ConstructInjection(new ParameterInjection("brokerList", brokerlist))); _backOffIncrement = backOffIncrement; return configuration; } public static int GetBackOffIncrement(this Configuration configuration) { return _backOffIncrement; } } }
using IFramework.Config; using IFramework.IoC; namespace IFramework.MessageQueue.ConfluentKafka.Config { public static class FrameworkConfigurationExtension { private static int _backOffIncrement = 30; public static Configuration UseConfluentKafka(this Configuration configuration, string brokerlist, int backOffIncrement = 30) { IoCFactory.Instance.CurrentContainer .RegisterType<IMessageQueueClient, ConfluentKafkaClient>(Lifetime.Singleton, new ConstructInjection(new ParameterInjection("brokerlist", brokerlist))); _backOffIncrement = backOffIncrement; return configuration; } public static int GetBackOffIncrement(this Configuration configuration) { return _backOffIncrement; } } }
mit
C#
0fa6c9fd4e6d81a1c250963896db47ff8ba86a93
Throw exception if not all compressed data could be read
SixLabors/Fonts
src/SixLabors.Fonts/Tables/WoffTableHeader.cs
src/SixLabors.Fonts/Tables/WoffTableHeader.cs
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System.IO; namespace SixLabors.Fonts.Tables { internal sealed class WoffTableHeader : TableHeader { public WoffTableHeader(string tag, uint offset, uint compressedLength, uint origLength, uint checkSum) : base(tag, checkSum, offset, origLength) => this.CompressedLength = compressedLength; public uint CompressedLength { get; } public override BigEndianBinaryReader CreateReader(Stream stream) { // Stream is not compressed. if (this.Length == this.CompressedLength) { return base.CreateReader(stream); } // Read all data from the compressed stream. stream.Seek(this.Offset, SeekOrigin.Begin); using var compressedStream = new IO.ZlibInflateStream(stream); byte[] uncompressedBytes = new byte[this.Length]; int bytesRead = compressedStream.Read(uncompressedBytes, 0, uncompressedBytes.Length); if (bytesRead < this.Length) { throw new InvalidFontFileException($"Could not read compressed data! Expected bytes: {this.Length}, bytes read: {bytesRead}"); } var memoryStream = new MemoryStream(uncompressedBytes); return new BigEndianBinaryReader(memoryStream, false); } // WOFF TableDirectoryEntry // UInt32 | tag | 4-byte sfnt table identifier. // UInt32 | offset | Offset to the data, from beginning of WOFF file. // UInt32 | compLength | Length of the compressed data, excluding padding. // UInt32 | origLength | Length of the uncompressed table, excluding padding. // UInt32 | origChecksum | Checksum of the uncompressed table. public static new WoffTableHeader Read(BigEndianBinaryReader reader) => new WoffTableHeader(reader.ReadTag(), reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32()); } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System.IO; namespace SixLabors.Fonts.Tables { internal sealed class WoffTableHeader : TableHeader { public WoffTableHeader(string tag, uint offset, uint compressedLength, uint origLength, uint checkSum) : base(tag, checkSum, offset, origLength) => this.CompressedLength = compressedLength; public uint CompressedLength { get; } public override BigEndianBinaryReader CreateReader(Stream stream) { // Stream is not compressed. if (this.Length == this.CompressedLength) { return base.CreateReader(stream); } // Read all data from the compressed stream. stream.Seek(this.Offset, SeekOrigin.Begin); using var compressedStream = new IO.ZlibInflateStream(stream); byte[] uncompressedBytes = new byte[this.Length]; compressedStream.Read(uncompressedBytes, 0, uncompressedBytes.Length); var memoryStream = new MemoryStream(uncompressedBytes); return new BigEndianBinaryReader(memoryStream, false); } // WOFF TableDirectoryEntry // UInt32 | tag | 4-byte sfnt table identifier. // UInt32 | offset | Offset to the data, from beginning of WOFF file. // UInt32 | compLength | Length of the compressed data, excluding padding. // UInt32 | origLength | Length of the uncompressed table, excluding padding. // UInt32 | origChecksum | Checksum of the uncompressed table. public static new WoffTableHeader Read(BigEndianBinaryReader reader) => new WoffTableHeader(reader.ReadTag(), reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32()); } }
apache-2.0
C#
71ffba9258edfd987d6f53da2577c4a1122060d5
fix EnumerableEx
RyotaMurohoshi/unity_snippets
unity/Assets/Scripts/Common/EnumerableEx.cs
unity/Assets/Scripts/Common/EnumerableEx.cs
using System.Collections.Generic; namespace System.Linq { public static class EnumerableEx { public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { if (first == null) throw new ArgumentNullException("first"); if (second == null) throw new ArgumentNullException("second"); if (resultSelector == null) throw new ArgumentNullException("resultSelector"); return ZipImpl(first, second, resultSelector); } private static IEnumerable<TResult> ZipImpl<TFirst, TSecond, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { using (var e1 = first.GetEnumerator()) using (var e2 = second.GetEnumerator()) while (e1.MoveNext() && e2.MoveNext()) { yield return resultSelector(e1.Current, e2.Current); } } } }
using System.Collections.Generic; namespace System.Linq { public static class EnumerableEx { public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { if (first == null) throw new ArgumentNullException("first"); if (second == null) throw new ArgumentNullException("second"); if (resultSelector == null) throw new ArgumentNullException("resultSelector"); return ZipImpl(first, second, resultSelector); } private static IEnumerable<TResult> ZipImpl<TFirst, TSecond, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { using (var e1 = first.GetEnumerator()) using (var e2 = second.GetEnumerator()) while (e1.MoveNext() && e2.MoveNext()) { yield return resultSelector(e1.Current, e2.Current); } } - } }
mit
C#
f16f2790b3d929d6eff06daf95253e0ad741cf97
Use readImei(Context) method
adjust/unity_sdk,adjust/unity_sdk,adjust/unity_sdk
Assets/AdjustImei/Android/AdjustImeiAndroid.cs
Assets/AdjustImei/Android/AdjustImeiAndroid.cs
using System; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk.imei { #if UNITY_ANDROID public class AdjustImeiAndroid { private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei"); private static AndroidJavaObject ajoCurrentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"); public static void ReadImei() { if (ajcAdjustImei == null) { ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei"); } ajcAdjustImei.CallStatic("readImei", ajoCurrentActivity); } public static void DoNotReadImei() { if (ajcAdjustImei == null) { ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei"); } ajcAdjustImei.CallStatic("doNotReadImei"); } } #endif }
using System; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk.imei { #if UNITY_ANDROID public class AdjustImeiAndroid { private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei"); public static void ReadImei() { if (ajcAdjustImei == null) { ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei"); } ajcAdjustImei.CallStatic("readImei"); } public static void DoNotReadImei() { if (ajcAdjustImei == null) { ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei"); } ajcAdjustImei.CallStatic("doNotReadImei"); } } #endif }
mit
C#
87f63ecf36a922274b52edc7882a69bcd1809afc
Fix VertexProperty.ToString().
ExRam/ExRam.Gremlinq
ExRam.Gremlinq.Core/Elements/VertexProperty.cs
ExRam.Gremlinq.Core/Elements/VertexProperty.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using LanguageExt; using NullGuard; namespace ExRam.Gremlinq.Core.GraphElements { public class VertexProperty<TValue, TMeta> : Property<TValue>, IVertexProperty { public VertexProperty(TValue value) { Value = value; } protected VertexProperty() { } public static implicit operator VertexProperty<TValue, TMeta>(TValue value) => new VertexProperty<TValue, TMeta>(value); public static implicit operator VertexProperty<TValue, TMeta>(TValue[] value) => throw new NotSupportedException(); public override string ToString() { return $"vp[{Label}->{GetValue()}]"; } internal override IDictionary<string, object> GetMetaProperties() => Properties?.Serialize().ToDictionary(x => x.Item1.Name, x => x.Item2) ?? (IDictionary<string, object>)ImmutableDictionary<string, object>.Empty; [AllowNull] public object Id { get; set; } [AllowNull] public string Label { get; set; } [AllowNull] public TMeta Properties { get; set; } } public class VertexProperty<TValue> : VertexProperty<TValue, IDictionary<string, object>> { protected VertexProperty() { Properties = new Dictionary<string, object>(); } public VertexProperty(TValue value) : this() { Value = value; } public static implicit operator VertexProperty<TValue>(TValue value) => new VertexProperty<TValue>(value); public static implicit operator VertexProperty<TValue>(TValue[] value) => throw new NotSupportedException(); internal override IDictionary<string, object> GetMetaProperties() => Properties; } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using LanguageExt; using NullGuard; namespace ExRam.Gremlinq.Core.GraphElements { public class VertexProperty<TValue, TMeta> : Property<TValue>, IVertexProperty { public VertexProperty(TValue value) { Value = value; } protected VertexProperty() { } public static implicit operator VertexProperty<TValue, TMeta>(TValue value) => new VertexProperty<TValue, TMeta>(value); public static implicit operator VertexProperty<TValue, TMeta>(TValue[] value) => throw new NotSupportedException(); public override string ToString() { return $"vp[{Key}->{GetValue()}]"; } internal override IDictionary<string, object> GetMetaProperties() => Properties?.Serialize().ToDictionary(x => x.Item1.Name, x => x.Item2) ?? (IDictionary<string, object>)ImmutableDictionary<string, object>.Empty; [AllowNull] public object Id { get; set; } [AllowNull] public string Label { get; set; } [AllowNull] public TMeta Properties { get; set; } } public class VertexProperty<TValue> : VertexProperty<TValue, IDictionary<string, object>> { protected VertexProperty() { Properties = new Dictionary<string, object>(); } public VertexProperty(TValue value) : this() { Value = value; } public static implicit operator VertexProperty<TValue>(TValue value) => new VertexProperty<TValue>(value); public static implicit operator VertexProperty<TValue>(TValue[] value) => throw new NotSupportedException(); internal override IDictionary<string, object> GetMetaProperties() => Properties; } }
mit
C#
5e15987fbf399f3c2900d384eb23dce3370531e7
Update LoadSpecificSheets.cs
aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Articles/LoadSpecificSheets.cs
Examples/CSharp/Articles/LoadSpecificSheets.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Articles { public class LoadSpecificSheets { public static void Main() { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Define a new Workbook. Workbook workbook; //Set the load data option with selected sheet(s). LoadDataOption dataOption = new LoadDataOption(); dataOption.SheetNames = new string[] { "Sheet2" }; //Load the workbook with the spcified worksheet only. LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx); loadOptions.LoadDataOptions = dataOption; loadOptions.LoadDataAndFormatting = true; //Creat the workbook. workbook = new Workbook(dataDir+ "TestData.xlsx", loadOptions); //Perform your desired task. //Save the workbook. workbook.Save(dataDir+ "outputFile.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Articles { public class LoadSpecificSheets { public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Define a new Workbook. Workbook workbook; //Set the load data option with selected sheet(s). LoadDataOption dataOption = new LoadDataOption(); dataOption.SheetNames = new string[] { "Sheet2" }; //Load the workbook with the spcified worksheet only. LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx); loadOptions.LoadDataOptions = dataOption; loadOptions.LoadDataAndFormatting = true; //Creat the workbook. workbook = new Workbook(dataDir+ "TestData.xlsx", loadOptions); //Perform your desired task. //Save the workbook. workbook.Save(dataDir+ "outputFile.out.xlsx"); } } }
mit
C#
32cc1d99aaa4c844657cc9199d8b7b6223cda738
Refactor - UserMessage instead of attribute
wachulski/nunit-migrator
nunit.migrator/CodeActions/AssertUserMessageDecorator.cs
nunit.migrator/CodeActions/AssertUserMessageDecorator.cs
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly string _userMessage; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); _userMessage = attribute.UserMessage; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_userMessage}\""))); var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly ExceptionExpectancyAtAttributeLevel _attribute; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { _attribute = attribute; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_attribute.UserMessage}\""))); // TODO: no need for full attribute, msg only var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }
mit
C#
f62bc87317d54ff7e67a754885c091b154f0be04
Remove unused test
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/test/src/CSharp/Daemon/Stages/PerformanceHighlightings/PerformanceStageTests.cs
resharper/resharper-unity/test/src/CSharp/Daemon/Stages/PerformanceHighlightings/PerformanceStageTests.cs
using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.Highlightings; using JetBrains.ReSharper.Psi; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.PerformanceHighlightings { [TestUnity] public class PerformanceStageTest : UnityGlobalHighlightingsStageTestBase { protected override string RelativeTestDataRoot => @"CSharp\Daemon\Stages\PerformanceCriticalCodeAnalysis\"; [Test] public void SimpleTest() { DoNamedTest(); } [Test] public void SimpleTest2() { DoNamedTest(); } [Test] public void CommonTest() { DoNamedTest(); } [Test]public void CoroutineTest() { DoNamedTest(); } [Test] public void UnityObjectEqTest() { DoNamedTest(); } [Test] public void IndirectCostlyTest() { DoNamedTest(); } [Test] public void InefficientCameraMainUsageWarningTest() {DoNamedTest();} [Test]public void InvokeAndSendMessageTest() {DoNamedTest();} [Test] public void DisabledWarningTest() {DoNamedTest();} [Test] public void LambdasTest() {DoNamedTest();} [Test] public void LocalFunctionsTest() {DoNamedTest();} [Test] public void CommentRootsTest() { DoNamedTest(); } [Test] public void EditorClassesTest() {DoNamedTest();} protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile file, IContextBoundSettingsStore settingsStore) { return highlighting is UnityPerformanceHighlightingBase; } } }
using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.Highlightings; using JetBrains.ReSharper.Psi; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.PerformanceHighlightings { [TestUnity] public class PerformanceStageTest : UnityGlobalHighlightingsStageTestBase { protected override string RelativeTestDataRoot => @"CSharp\Daemon\Stages\PerformanceCriticalCodeAnalysis\"; [Test] public void SimpleTest() { DoNamedTest(); } [Test] public void SimpleTest2() { DoNamedTest(); } [Test] public void CommonTest() { DoNamedTest(); } [Test]public void CoroutineTest() { DoNamedTest(); } [Test] public void UnityObjectEqTest() { DoNamedTest(); } [Test] public void IndirectCostlyTest() { DoNamedTest(); } [Test] public void InefficientCameraMainUsageWarningTest() {DoNamedTest();} [Test]public void InvokeAndSendMessageTest() {DoNamedTest();} [Test] public void DisabledWarningTest() {DoNamedTest();} [Test] public void LambdasTest() {DoNamedTest();} [Test] public void LocalFunctionsTest() {DoNamedTest();} [Test] public void CommentRootsTest() { DoNamedTest(); } [Test] public void AttributesTest() {DoNamedTest();} [Test] public void EditorClassesTest() {DoNamedTest();} protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile file, IContextBoundSettingsStore settingsStore) { return highlighting is UnityPerformanceHighlightingBase; } } }
apache-2.0
C#
33a805ffb6d6b547f610fd07cc7c3d9fd3978200
test more levels with xml config
kalotay/tech-academy-logging
Logging/Logging/XmlConfigurationTests.cs
Logging/Logging/XmlConfigurationTests.cs
using System.Linq; using NUnit.Framework; using log4net; using log4net.Appender; using log4net.Config; using log4net.Core; namespace Logging { [TestFixture] public class XmlConfigurationTests { private const string MemoryAppenderName = "MemoryAppender"; private static readonly ILog Log = LogManager.GetLogger(typeof(XmlConfigurationTests)); private MemoryAppender _memoryAppender; [TestFixtureSetUp] public void BootstrapLogging() { XmlConfigurator.Configure(); var repository = LogManager.GetRepository(); var appenders = repository.GetAppenders(); foreach (var appender in appenders.Where(appender => appender.Name == MemoryAppenderName)) { Assert.That(_memoryAppender, Is.Null, "Multiple appender with same name"); _memoryAppender = (MemoryAppender)appender; } Assert.That(_memoryAppender, Is.Not.Null, "Cannot find memory appender"); } [Test] public void LogsFatal() { Assert.That(Log.IsFatalEnabled, "Fatal level disabled"); Log.Fatal("Fatal"); var events = _memoryAppender.GetEvents(); var fatalEvents = events.Where(e => e.Level == Level.Fatal); Assert.That(fatalEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Fatal")); } [Test] public void LogsError() { Assert.That(Log.IsErrorEnabled, "Error level disabled"); Log.Error("Error"); var events = _memoryAppender.GetEvents(); var errorEvents = events.Where(e => e.Level == Level.Error); Assert.That(errorEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Error")); } [Test] public void LogsWarn() { Assert.That(Log.IsWarnEnabled, "Warn level disabled"); Log.Warn("Warn"); var events = _memoryAppender.GetEvents(); var warnEvents = events.Where(e => e.Level == Level.Warn); Assert.That(warnEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Warn")); } [Test] public void LogsInfo() { Assert.That(Log.IsInfoEnabled, "Info level disabled"); Log.Info("Info"); var events = _memoryAppender.GetEvents(); var infoEvents = events.Where(e => e.Level == Level.Info); Assert.That(infoEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Info")); } [Test] public void LogsDebug() { Assert.That(Log.IsDebugEnabled, "Debug level disabled"); Log.Debug("Debug"); var events = _memoryAppender.GetEvents(); var debugEvents = events.Where(e => e.Level == Level.Debug); Assert.That(debugEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Debug")); } } }
using System.Linq; using NUnit.Framework; using log4net; using log4net.Appender; using log4net.Config; using log4net.Core; namespace Logging { [TestFixture] public class XmlConfigurationTests { private const string MemoryAppenderName = "MemoryAppender"; private static readonly ILog Log = LogManager.GetLogger(typeof(XmlConfigurationTests)); private MemoryAppender _memoryAppender; [TestFixtureSetUp] public void BootstrapLogging() { XmlConfigurator.Configure(); var repository = LogManager.GetRepository(); var appenders = repository.GetAppenders(); foreach (var appender in appenders.Where(appender => appender.Name == MemoryAppenderName)) { Assert.That(_memoryAppender, Is.Null, "Multiple appender with same name"); _memoryAppender = (MemoryAppender)appender; } Assert.That(_memoryAppender, Is.Not.Null, "Cannot find memory appender"); } [Test] public void LogsFatal() { Assert.That(Log.IsFatalEnabled, "Fatal level disabled"); Log.Fatal("Fatal"); var events = _memoryAppender.GetEvents(); var fatalEvents = events.Where(e => e.Level == Level.Fatal); Assert.That(fatalEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Fatal")); } } }
mit
C#
8057202fe1cd718c20225dc8065d33f5391eedbd
Remove caching of invoked expressions as it is hard to do and adds little benefit
ccoton/MFlow,ccoton/MFlow,ccoton/MFlow
MFlow.Core/Internal/ExpressionBuilder.cs
MFlow.Core/Internal/ExpressionBuilder.cs
 using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } }
 using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } class InvokeCacheKey { public object Target{get;set;} public object Func{get;set;} } }
mit
C#
a94ba6d6809caf82ff58306b8a02d54eef1dd785
Correct #Name
TeamnetGroup/cap-net,darbio/cap-net
src/CAPNet.Tests/ValidatorTests/PolygonCoordinatePairsFirstLastValidatorTests.cs
src/CAPNet.Tests/ValidatorTests/PolygonCoordinatePairsFirstLastValidatorTests.cs
using CAPNet.Models; using System.Linq; using Xunit; namespace CAPNet { public class PolygonCoordinatePairsFirstLastValidatorTests { [Fact] public void PolygonWithFirstCoordinatePairDifferentFromLastCoordinatePairIsInvalid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 39.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.False(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.NotEmpty(pairErrors); } [Fact] public void PolygonWithFirstCoordinatePairEqualToLastCoordinatePairsIsValid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 38.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.True(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.Empty(pairErrors); } } }
using CAPNet.Models; using System.Linq; using Xunit; namespace CAPNet { public class PolygonCoordinatePairsFirstLastValidatorTests { [Fact] public void PolygonWithFirstCoordinatePairDifferentFromLastCoordinatePairIsInvalid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 39.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.False(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.NotEmpty(pairErrors); } [Fact] public void PolygonWithFirstCoordinatePairEqualToLastCoordinateParisIsValid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 38.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.True(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.Empty(pairErrors); } } }
mit
C#
c97069f4ffdd2c0be82167daf681707606fb7314
rework to inherit from BaseFormatterAttribute
billboga/Supurlative,kendaleiv/Supurlative,ritterim/Supurlative
src/Core/IgnoreAttribute.cs
src/Core/IgnoreAttribute.cs
using System; using System.Collections.Generic; namespace RimDev.Supurlative { [AttributeUsage(AttributeTargets.Property)] public class IgnoreAttribute : BaseFormatterAttribute { public override void Invoke(string fullPropertyName, object value, Type valueType, IDictionary<string, object> dictionary, SupurlativeOptions options) { return; } public override bool IsMatch(Type currentType, SupurlativeOptions options) { return false; } } }
using System; namespace RimDev.Supurlative { [AttributeUsage(AttributeTargets.Property)] public class IgnoreAttribute : Attribute { public IgnoreAttribute() { Ignore = true; } public bool Ignore { get; private set; } public static bool PropertyHasIgnoreAttribute(Object x, string propertyName) { var pi = x.GetType().GetProperty(propertyName); if (pi == null) return false; return Attribute.IsDefined(pi, typeof(IgnoreAttribute)); } } }
mit
C#
347a95b991400eac1ba9676d522354edbcc9e0af
Add doc comment.
eriawan/roslyn,KevinRansom/roslyn,xasx/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,jmarolf/roslyn,dotnet/roslyn,aelij/roslyn,VSadov/roslyn,weltkante/roslyn,abock/roslyn,mgoertz-msft/roslyn,genlu/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,mavasani/roslyn,AlekseyTs/roslyn,physhi/roslyn,aelij/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jcouv/roslyn,panopticoncentral/roslyn,physhi/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,gafter/roslyn,gafter/roslyn,cston/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,MichalStrehovsky/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,jcouv/roslyn,nguerrera/roslyn,DustinCampbell/roslyn,sharwell/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,tannergooding/roslyn,heejaechang/roslyn,eriawan/roslyn,heejaechang/roslyn,stephentoub/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,dotnet/roslyn,dpoeschl/roslyn,cston/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,davkean/roslyn,aelij/roslyn,nguerrera/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,sharwell/roslyn,davkean/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,tmat/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,davkean/roslyn,tmeschter/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,physhi/roslyn,cston/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,diryboy/roslyn,tmat/roslyn,dotnet/roslyn,weltkante/roslyn,agocke/roslyn,dpoeschl/roslyn,heejaechang/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,reaction1989/roslyn,abock/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,genlu/roslyn,tmeschter/roslyn,brettfo/roslyn,tmat/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,brettfo/roslyn,xasx/roslyn,weltkante/roslyn,AlekseyTs/roslyn,diryboy/roslyn,agocke/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,diryboy/roslyn,reaction1989/roslyn,AmadeusW/roslyn,wvdd007/roslyn,genlu/roslyn,DustinCampbell/roslyn,jcouv/roslyn,xasx/roslyn
src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.cs
src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { /// <summary> /// Service that can be used to generate <see cref="object.Equals(object)"/> and /// <see cref="object.GetHashCode"/> overloads for use from other IDE features. /// </summary> internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService { /// <summary> /// Formats only the members in the provided document that were generated by this interface. /// </summary> Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string localNameOpt, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { /// <summary> /// Service that can be used to generate <see cref="object.Equals(object)"/> and /// <see cref="object.GetHashCode"/> overloads for use from other IDE features. /// </summary> internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService { Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string localNameOpt, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); } }
mit
C#
ad7de72e03d4a227ed9a63f7c9956864665c1d92
Remove unused extension
mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn
src/Workspaces/Core/Portable/Shared/Extensions/FileLinePositionSpanExtensions.cs
src/Workspaces/Core/Portable/Shared/Extensions/FileLinePositionSpanExtensions.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. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class FileLinePositionSpanExtensions { } }
// 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. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class FileLinePositionSpanExtensions { /// <summary> /// Get mapped file path if exist, otherwise return null. /// </summary> public static string? GetMappedFilePathIfExist(this FileLinePositionSpan fileLinePositionSpan) => fileLinePositionSpan.HasMappedPath ? fileLinePositionSpan.Path : null; } }
mit
C#
d673cf58bed631d51d3784479f19eb53192f4b6c
Make DataListBoxItemAutomationPeer an inner class.
zooba/PTVS,Microsoft/PTVS,huguesv/PTVS,int19h/PTVS,Microsoft/PTVS,huguesv/PTVS,Microsoft/PTVS,int19h/PTVS,zooba/PTVS,huguesv/PTVS,zooba/PTVS,huguesv/PTVS,int19h/PTVS,Microsoft/PTVS,huguesv/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,Microsoft/PTVS,huguesv/PTVS,Microsoft/PTVS,zooba/PTVS
Python/Product/EnvironmentsList/DataListBox.cs
Python/Product/EnvironmentsList/DataListBox.cs
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Windows.Automation.Peers; using System.Windows.Controls; namespace Microsoft.PythonTools.EnvironmentsList { public sealed class DataListBox : ListBox { protected override AutomationPeer OnCreateAutomationPeer() { return new DataListBoxAutomationPeer(this); } sealed class DataListBoxAutomationPeer : ListBoxAutomationPeer { public DataListBoxAutomationPeer(ListBox owner) : base(owner) { } protected override ItemAutomationPeer CreateItemAutomationPeer(object item) { return new DataListBoxItemAutomationPeer(item, this); } } sealed class DataListBoxItemAutomationPeer : ListBoxItemAutomationPeer { public DataListBoxItemAutomationPeer(object owner, SelectorAutomationPeer selectorAutomationPeer) : base(owner, selectorAutomationPeer) { } protected override string GetClassNameCore() { return "DataListBoxItem"; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.DataItem; } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Windows.Automation.Peers; using System.Windows.Controls; namespace Microsoft.PythonTools.EnvironmentsList { public sealed class DataListBox : ListBox { protected override AutomationPeer OnCreateAutomationPeer() { return new DataListBoxAutomationPeer(this); } sealed class DataListBoxAutomationPeer : ListBoxAutomationPeer { public DataListBoxAutomationPeer(ListBox owner) : base(owner) { } protected override ItemAutomationPeer CreateItemAutomationPeer(object item) { return new DataListBoxItemAutomationPeer(item, this); } } } sealed class DataListBoxItemAutomationPeer : ListBoxItemAutomationPeer { public DataListBoxItemAutomationPeer(object owner, SelectorAutomationPeer selectorAutomationPeer) : base(owner, selectorAutomationPeer) { } protected override string GetClassNameCore() { return "DataListBoxItem"; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.DataItem; } } }
apache-2.0
C#
c435caa7d13bae645a0e49d253f0cf2f547a4ade
Add check for new deployments to DaysLiveReportElement (#5299)
QuantConnect/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,jameschch/Lean,QuantConnect/Lean,StefanoRaggi/Lean,jameschch/Lean,QuantConnect/Lean,AlexCatarino/Lean,JKarathiya/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,AlexCatarino/Lean,jameschch/Lean,JKarathiya/Lean,JKarathiya/Lean,StefanoRaggi/Lean,jameschch/Lean,JKarathiya/Lean,jameschch/Lean,QuantConnect/Lean
Report/ReportElements/DaysLiveReportElement.cs
Report/ReportElements/DaysLiveReportElement.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using QuantConnect.Packets; namespace QuantConnect.Report.ReportElements { internal class DaysLiveReportElement : ReportElement { private LiveResult _live; /// <summary> /// Create a new metric describing the number of days an algorithm has been live. /// </summary> /// <param name="name">Name of the widget</param> /// <param name="key">Location of injection</param> /// <param name="backtest">Backtest result object</param> /// <param name="live">Live result object</param> public DaysLiveReportElement(string name, string key, LiveResult live) { _live = live; Name = name; Key = key; } /// <summary> /// The generated output string to be injected /// </summary> public override string Render() { if (_live == null) { return "-"; } var equityPoints = ResultsUtil.EquityPoints(_live); if (equityPoints.Count == 0) { Result = 0; return "0"; } var daysLive = (DateTime.UtcNow - equityPoints.First().Key).Days; Result = daysLive; return daysLive.ToStringInvariant(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using QuantConnect.Packets; namespace QuantConnect.Report.ReportElements { internal class DaysLiveReportElement : ReportElement { private LiveResult _live; /// <summary> /// Create a new metric describing the number of days an algorithm has been live. /// </summary> /// <param name="name">Name of the widget</param> /// <param name="key">Location of injection</param> /// <param name="backtest">Backtest result object</param> /// <param name="live">Live result object</param> public DaysLiveReportElement(string name, string key, LiveResult live) { _live = live; Name = name; Key = key; } /// <summary> /// The generated output string to be injected /// </summary> public override string Render() { if (_live == null) { return "-"; } var equityPoints = ResultsUtil.EquityPoints(_live); var daysLive = (DateTime.UtcNow - equityPoints.First().Key).Days; Result = daysLive; return daysLive.ToStringInvariant(); } } }
apache-2.0
C#
03e48bd941adc3cf03f66cac62944b18c8907da0
Bump Version
mj1856/SimpleImpersonation
SimpleImpersonation/Properties/AssemblyInfo.cs
SimpleImpersonation/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("SimpleImpersonation")] [assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")] [assembly: AssemblyCompany("Matt Johnson")] [assembly: AssemblyProduct("Simple Impersonation")] [assembly: AssemblyCopyright("Copyright © Matt Johnson")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.1.*")] [assembly: AssemblyInformationalVersion("2.0.1")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("SimpleImpersonation")] [assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")] [assembly: AssemblyCompany("Matt Johnson")] [assembly: AssemblyProduct("Simple Impersonation")] [assembly: AssemblyCopyright("Copyright © Matt Johnson")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0")]
mit
C#
aa1659333b65a7eb84b385c3c6cb264c29ca66fc
Remove override of DialogHandler.Invalidate
PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto
Source/Eto.Platform.Mac/Forms/DialogHandler.cs
Source/Eto.Platform.Mac/Forms/DialogHandler.cs
using System; using SD = System.Drawing; using Eto.Drawing; using Eto.Forms; using MonoMac.AppKit; using MonoMac.Foundation; namespace Eto.Platform.Mac.Forms { public class DialogHandler : MacWindow<MyWindow, Dialog>, IDialog { Button button; MacModal.ModalHelper session; class DialogWindow : MyWindow { public new DialogHandler Handler { get { return base.Handler as DialogHandler; } set { base.Handler = value; } } public DialogWindow() : base(new SD.Rectangle(0,0,200,200), NSWindowStyle.Closable | NSWindowStyle.Titled, NSBackingStore.Buffered, false) { } [Export("cancelOperation:")] public void CancelOperation(IntPtr sender) { if (Handler.AbortButton != null) Handler.AbortButton.OnClick (EventArgs.Empty); } } public DialogDisplayMode DisplayMode { get; set; } public Button AbortButton { get; set; } public Button DefaultButton { get { return button; } set { button = value; if (button != null) { var b = button.ControlObject as NSButton; if (b != null) Control.DefaultButtonCell = b.Cell; else Control.DefaultButtonCell = null; } else Control.DefaultButtonCell = null; } } public DialogHandler () { this.DisposeControl = false; var dlg = new DialogWindow(); dlg.Handler = this; Control = dlg; ConfigureWindow (); } public DialogResult ShowDialog (Control parent) { if (parent != null) { if (parent.ControlObject is NSWindow) Control.ParentWindow = (NSWindow)parent.ControlObject; else if (parent.ControlObject is NSView) Control.ParentWindow = ((NSView)parent.ControlObject).Window; } Control.MakeKeyWindow (); Widget.Closed += HandleClosed; switch (DisplayMode) { case DialogDisplayMode.Attached: MacModal.RunSheet (Control, out session); break; default: case DialogDisplayMode.Default: case DialogDisplayMode.Separate: MacModal.Run (Control, out session); break; } return Widget.DialogResult; } void HandleClosed (object sender, EventArgs e) { if (session != null) session.Stop (); Widget.Closed -= HandleClosed; } public override void Close () { if (session != null && session.IsSheet) { session.Stop (); } else base.Close (); } } }
using System; using SD = System.Drawing; using Eto.Drawing; using Eto.Forms; using MonoMac.AppKit; using MonoMac.Foundation; namespace Eto.Platform.Mac.Forms { public class DialogHandler : MacWindow<MyWindow, Dialog>, IDialog { Button button; MacModal.ModalHelper session; class DialogWindow : MyWindow { public new DialogHandler Handler { get { return base.Handler as DialogHandler; } set { base.Handler = value; } } public DialogWindow() : base(new SD.Rectangle(0,0,200,200), NSWindowStyle.Closable | NSWindowStyle.Titled, NSBackingStore.Buffered, false) { } [Export("cancelOperation:")] public void CancelOperation(IntPtr sender) { if (Handler.AbortButton != null) Handler.AbortButton.OnClick (EventArgs.Empty); } } public DialogDisplayMode DisplayMode { get; set; } public Button AbortButton { get; set; } public Button DefaultButton { get { return button; } set { button = value; if (button != null) { var b = button.ControlObject as NSButton; if (b != null) Control.DefaultButtonCell = b.Cell; else Control.DefaultButtonCell = null; } else Control.DefaultButtonCell = null; } } public DialogHandler () { this.DisposeControl = false; var dlg = new DialogWindow(); dlg.Handler = this; Control = dlg; ConfigureWindow (); } public DialogResult ShowDialog (Control parent) { if (parent != null) { if (parent.ControlObject is NSWindow) Control.ParentWindow = (NSWindow)parent.ControlObject; else if (parent.ControlObject is NSView) Control.ParentWindow = ((NSView)parent.ControlObject).Window; } Control.MakeKeyWindow (); Widget.Closed += HandleClosed; switch (DisplayMode) { case DialogDisplayMode.Attached: MacModal.RunSheet (Control, out session); break; default: case DialogDisplayMode.Default: case DialogDisplayMode.Separate: MacModal.Run (Control, out session); break; } return Widget.DialogResult; } public void Invalidate(Rectangle rect) { throw new NotImplementedException(); } void HandleClosed (object sender, EventArgs e) { if (session != null) session.Stop (); Widget.Closed -= HandleClosed; } public override void Close () { if (session != null && session.IsSheet) { session.Stop (); } else base.Close (); } } }
bsd-3-clause
C#
3949f78f2487d6cce561f8ff8bbd537ff2e51cc3
change input on menu
heyx3/rubber-duck-love
Assets/Scripts/SplashMenu.cs
Assets/Scripts/SplashMenu.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SplashMenu : MonoBehaviour { public AudioSource music; public bool splashDone; public bool musicPlaying; public SpriteRenderer splash; public Animator instruction; public Animator credits; // Update is called once per frame void Start() { StartCoroutine(WaitAndStart(3.0f)); } void Update() { if (splashDone) { if (!musicPlaying) { splash.enabled = false; music.Play(); musicPlaying = true; } if (Input.anyKeyDown) { if (instruction.GetBool("visible") == true) { if (Input.GetButtonDown("Throw")) { SceneManager.LoadScene(1); } } if (Input.GetButtonDown("Quack")) { bool cred = credits.GetBool("visible"); credits.SetBool("visible", !cred); } if (instruction.GetBool("visible") != true) { instruction.SetBool("visible", true); } } } } private IEnumerator WaitAndStart(float waitTime) { yield return new WaitForSeconds(waitTime); splashDone = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SplashMenu : MonoBehaviour { public AudioSource music; public bool splashDone; public bool musicPlaying; public SpriteRenderer splash; public Animator instruction; public Animator credits; // Update is called once per frame void Start() { StartCoroutine(WaitAndStart(3.0f)); } void Update() { if (splashDone) { if (!musicPlaying) { splash.enabled = false; music.Play(); musicPlaying = true; } if (Input.anyKeyDown) { if (instruction.GetBool("visible") == true) { if (Input.GetKeyDown(KeyCode.Space)) { SceneManager.LoadScene(1); } } if (Input.GetKeyDown(KeyCode.C)) { bool cred = credits.GetBool("visible"); credits.SetBool("visible", !cred); } if (instruction.GetBool("visible") != true) { instruction.SetBool("visible", true); } } } } private IEnumerator WaitAndStart(float waitTime) { yield return new WaitForSeconds(waitTime); splashDone = true; } }
mit
C#
ba32cc21d92bed02a0b08c16d8a8131c7e57ec53
Add missing ctor field initializations
mkoscielniak/SSMScripter
SSMScripter/Scripter/Smo/SmoObjectMetadata.cs
SSMScripter/Scripter/Smo/SmoObjectMetadata.cs
using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Type = type; Schema = schema; Name = name; ParentSchema = parentSchema; ParentName = parentName; } } }
using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Schema = schema; Name = name; } } }
mit
C#
eefff8f026d2827190188811ba7b08031b238b7c
Update SettingsFixture.cs
Shuttle/Shuttle.Esb
Shuttle.Esb.Tests/Settings/SettingsFixture.cs
Shuttle.Esb.Tests/Settings/SettingsFixture.cs
using System; using System.IO; using Microsoft.Extensions.Configuration; namespace Shuttle.Esb.Tests { public class SettingsFixture { protected ServiceBusSettings GetSettings() { var result = new ServiceBusSettings(); new ConfigurationBuilder() .AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @".\Settings\appsettings.json")).Build() .GetSection(ServiceBusSettings.SectionName).Bind(result); return result; } } }
using System; using System.IO; using Microsoft.Extensions.Configuration; namespace Shuttle.Esb.Tests { public class SettingsFixture { protected ServiceBusSettings GetSettings() { var result = new Esb.ServiceBusSettings(); new ConfigurationBuilder() .AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @".\Settings\appsettings.json")).Build() .GetSection(Esb.ServiceBusSettings.SectionName).Bind(result); return result; } } }
bsd-3-clause
C#
87a7898f8817b35eca5e0649716990174818f252
Update Shaco.cs
metaphorce/leaguesharp
MetaSmite/Champions/Shaco.cs
MetaSmite/Champions/Shaco.cs
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Shaco { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.E, 625f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Shaco { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.E, 625f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnGameUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
mit
C#
950dd65f839144a2e06263673b498eecee46f2ae
make it a function
taka-oyama/UniHttp
Assets/UniHttp/Support/Cache/CacheStorage.cs
Assets/UniHttp/Support/Cache/CacheStorage.cs
using UnityEngine; using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace UniHttp { public class CacheStorage { // for some reason File.Exists returns false when threading, so I'm forced to lock it. object locker; IFileHandler fileHandler; DirectoryInfo baseDirectory; MD5 hash; string password; public CacheStorage(IFileHandler fileHandler, string baseDirectory) { this.locker = new object(); this.fileHandler = fileHandler; this.baseDirectory = new DirectoryInfo(baseDirectory).CreateSubdirectory("Cache"); this.hash = new MD5CryptoServiceProvider(); this.password = Application.identifier; } public virtual void Write(Uri uri, byte[] data) { lock(locker) { fileHandler.Write(ComputePath(uri), data); } } public virtual byte[] Read(Uri uri) { lock(locker) { return fileHandler.Read(ComputePath(uri)); } } public virtual bool Exists(Uri uri) { lock(locker) { return fileHandler.Exists(ComputePath(uri)); } } public virtual void Clear() { lock(locker) { var dirs = baseDirectory.GetDirectories(); for(var i = 0; i < dirs.Length; i++) { dirs[i].Delete(true); } } } string ComputePath(Uri uri) { return ComputeDirectory(uri) + ComputeFileName(uri); } string ComputeDirectory(Uri uri) { return baseDirectory.FullName + "/" + uri.Authority.Replace(":", "_") + "/"; } string ComputeFileName(Uri uri) { string data = string.Concat(password, uri.Authority, uri.AbsolutePath); byte[] bytes = hash.ComputeHash(Encoding.ASCII.GetBytes(data)); StringBuilder sb = new StringBuilder(); for(int i = 0; i < bytes.Length; i++) { sb.Append(bytes[i].ToString("X2")); } return sb.ToString(); } } }
using UnityEngine; using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace UniHttp { public class CacheStorage { // for some reason File.Exists returns false when threading, so I'm forced to lock it. object locker; IFileHandler fileHandler; DirectoryInfo baseDirectory; MD5 hash; string password; public CacheStorage(IFileHandler fileHandler, string baseDirectory) { this.locker = new object(); this.fileHandler = fileHandler; this.baseDirectory = new DirectoryInfo(baseDirectory).CreateSubdirectory("Cache"); this.hash = new MD5CryptoServiceProvider(); this.password = Application.identifier; } public virtual void Write(Uri uri, byte[] data) { lock(locker) { fileHandler.Write(ComputeDirectory(uri) + ComputeFileName(uri), data); } } public virtual byte[] Read(Uri uri) { lock(locker) { return fileHandler.Read(ComputeDirectory(uri) + ComputeFileName(uri)); } } public virtual bool Exists(Uri uri) { lock(locker) { return fileHandler.Exists(ComputeDirectory(uri) + ComputeFileName(uri)); } } public virtual void Clear() { lock(locker) { var dirs = baseDirectory.GetDirectories(); for(var i = 0; i < dirs.Length; i++) { dirs[i].Delete(true); } } } string ComputeDirectory(Uri uri) { return baseDirectory.FullName + "/" + uri.Authority.Replace(":", "_") + "/"; } string ComputeFileName(Uri uri) { string data = string.Concat(password, uri.Authority, uri.AbsolutePath); byte[] bytes = hash.ComputeHash(Encoding.ASCII.GetBytes(data)); StringBuilder sb = new StringBuilder(); for(int i = 0; i < bytes.Length; i++) { sb.Append(bytes[i].ToString("X2")); } return sb.ToString(); } } }
mit
C#
14c3a35c07ed0842d55bb8f18a885b13c5966cd2
Modify institutions path retrieval
code4romania/anabi-gestiune-api,code4romania/anabi-gestiune-api,code4romania/anabi-gestiune-api
Anabi.InstitutionsImporter/InstitutionImporter.cs
Anabi.InstitutionsImporter/InstitutionImporter.cs
using Newtonsoft.Json; using System.IO; using System.Collections.Generic; using System.Reflection; namespace Anabi.InstitutionsImporter { public static class InstitutionImporter { private readonly static string SOURCE = "institutions.json"; public static List<Institution> Deserialize() { string institutionsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), SOURCE); using (StreamReader streamReader = File.OpenText(institutionsPath)) { JsonSerializer serializer = new JsonSerializer(); return (List<Institution>)serializer .Deserialize(streamReader, typeof(List<Institution>)); } } } }
using Newtonsoft.Json; using System.IO; using System.Collections.Generic; namespace Anabi.InstitutionsImporter { public static class InstitutionImporter { public static List<Institution> Deserialize() { using (StreamReader streamReader = File.OpenText($@"institutions.json")) { JsonSerializer serializer = new JsonSerializer(); return (List<Institution>)serializer .Deserialize(streamReader, typeof(List<Institution>)); } } } }
mpl-2.0
C#
6c8ccb4455e357fcbfbf3f287705a486d794ce64
优化函数“空转”效率
topameng/tolua
Assets/ToLua/Injection/LuaInjectionStation.cs
Assets/ToLua/Injection/LuaInjectionStation.cs
using System; using System.Collections; using System.Collections.Generic; namespace LuaInterface { [Flags] public enum InjectType { None = 0, After = 1, Before = 1 << 1, Replace = 1 << 2, ReplaceWithPreInvokeBase = 1 << 3, ReplaceWithPostInvokeBase = 1 << 4 } public class LuaInjectionStation { public const byte NOT_INJECTION_FLAG = 0; public const byte INVALID_INJECTION_FLAG = byte.MaxValue; static int cacheSize; static byte[] injectionFlagCache; static LuaFunction[] injectFunctionCache; static LuaInjectionStation() { injectionFlagCache = new byte[cacheSize]; injectFunctionCache = new LuaFunction[cacheSize]; } public static byte GetInjectFlag(int index) { byte result = INVALID_INJECTION_FLAG; result = injectionFlagCache[index]; if (result == INVALID_INJECTION_FLAG) { return NOT_INJECTION_FLAG; } else if (result == NOT_INJECTION_FLAG) { /// Delay injection not supported if (LuaState.GetInjectInitState(index)) { injectionFlagCache[index] = INVALID_INJECTION_FLAG; } } return result; } public static LuaFunction GetInjectionFunction(int index) { return injectFunctionCache[index]; } public static void CacheInjectFunction(int index, byte injectFlag, LuaFunction func) { injectFunctionCache[index] = func; injectionFlagCache[index] = injectFlag; } } }
using System; using System.Collections; using System.Collections.Generic; namespace LuaInterface { [Flags] public enum InjectType { None = 0, After = 1, Before = 1 << 1, Replace = 1 << 2, ReplaceWithPreInvokeBase = 1 << 3, ReplaceWithPostInvokeBase = 1 << 4 } public class LuaInjectionStation { public const byte NOT_INJECTION_FLAG = 0; public const byte INVALID_INJECTION_FLAG = byte.MaxValue; static int cacheSize; static byte[] injectionFlagCache; static LuaFunction[] injectFunctionCache; static LuaInjectionStation() { injectionFlagCache = new byte[cacheSize]; injectFunctionCache = new LuaFunction[cacheSize]; } public static byte GetInjectFlag(int index) { byte result = INVALID_INJECTION_FLAG; result = injectionFlagCache[index]; if (result == NOT_INJECTION_FLAG) { /// Delay injection not supported if (LuaState.GetInjectInitState(index)) { injectionFlagCache[index] = INVALID_INJECTION_FLAG; } } else if (result == INVALID_INJECTION_FLAG) { return NOT_INJECTION_FLAG; } return result; } public static LuaFunction GetInjectionFunction(int index) { return injectFunctionCache[index]; } public static void CacheInjectFunction(int index, byte injectFlag, LuaFunction func) { injectFunctionCache[index] = func; injectionFlagCache[index] = injectFlag; } } }
mit
C#
c10516fe3c679bb3dc3535970b9d242fa8e85035
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.8.18")] [assembly: AssemblyInformationalVersion("0.8.18")] /* * Version 0.8.18 * * This version publishes the Experiment nuget package again. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.8.18")] [assembly: AssemblyInformationalVersion("0.8.18-pre01")] /* * Version 0.8.18-pre01 * * To test publishing. */
mit
C#
d9886d8c6b6a11c4ce8ca43b8483caabca2269d2
Fix typos
EricSten-MSFT/kudu,juvchan/kudu,shibayan/kudu,duncansmart/kudu,projectkudu/kudu,puneet-gupta/kudu,kenegozi/kudu,juvchan/kudu,mauricionr/kudu,EricSten-MSFT/kudu,dev-enthusiast/kudu,projectkudu/kudu,uQr/kudu,MavenRain/kudu,YOTOV-LIMITED/kudu,YOTOV-LIMITED/kudu,sitereactor/kudu,uQr/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu,bbauya/kudu,puneet-gupta/kudu,oliver-feng/kudu,projectkudu/kudu,shanselman/kudu,shanselman/kudu,duncansmart/kudu,duncansmart/kudu,barnyp/kudu,chrisrpatterson/kudu,shrimpy/kudu,EricSten-MSFT/kudu,projectkudu/kudu,kali786516/kudu,kali786516/kudu,shrimpy/kudu,shibayan/kudu,oliver-feng/kudu,duncansmart/kudu,kenegozi/kudu,badescuga/kudu,kenegozi/kudu,shibayan/kudu,mauricionr/kudu,sitereactor/kudu,chrisrpatterson/kudu,barnyp/kudu,badescuga/kudu,badescuga/kudu,barnyp/kudu,EricSten-MSFT/kudu,juvchan/kudu,chrisrpatterson/kudu,kenegozi/kudu,juvchan/kudu,dev-enthusiast/kudu,projectkudu/kudu,bbauya/kudu,mauricionr/kudu,juoni/kudu,kali786516/kudu,shibayan/kudu,uQr/kudu,mauricionr/kudu,dev-enthusiast/kudu,WeAreMammoth/kudu-obsolete,shanselman/kudu,bbauya/kudu,shrimpy/kudu,YOTOV-LIMITED/kudu,MavenRain/kudu,sitereactor/kudu,MavenRain/kudu,WeAreMammoth/kudu-obsolete,barnyp/kudu,puneet-gupta/kudu,MavenRain/kudu,badescuga/kudu,juvchan/kudu,bbauya/kudu,chrisrpatterson/kudu,juoni/kudu,sitereactor/kudu,shibayan/kudu,WeAreMammoth/kudu-obsolete,oliver-feng/kudu,badescuga/kudu,dev-enthusiast/kudu,kali786516/kudu,EricSten-MSFT/kudu,oliver-feng/kudu,sitereactor/kudu,juoni/kudu,shrimpy/kudu,puneet-gupta/kudu,juoni/kudu,uQr/kudu
Kudu.Services/Deployment/DeploymentService.cs
Kudu.Services/Deployment/DeploymentService.cs
using System.Collections.Generic; using System.ComponentModel; using System.Json; using System.ServiceModel; using System.ServiceModel.Web; using Kudu.Core.Deployment; namespace Kudu.Services.Deployment { [ServiceContract] public class DeploymentService { private readonly IDeploymentManager _deploymentManager; public DeploymentService(IDeploymentManager deploymentManager) { _deploymentManager = deploymentManager; } [Description("Gets the id of the current active deployment.")] [WebGet(UriTemplate = "id")] public string GetActiveDeploymentId() { return _deploymentManager.ActiveDeploymentId; } [Description("Performs a deployment.")] [WebInvoke(UriTemplate = "")] public void Deploy() { _deploymentManager.Deploy(); } [Description("Restore a previously successful deployment based on its id.")] [WebInvoke(UriTemplate = "restore")] public void Restore(JsonObject input) { _deploymentManager.Deploy((string)input["id"]); } [Description("Builds a specific deployment based on its id.")] [WebInvoke(UriTemplate = "build")] public void Build(JsonObject input) { _deploymentManager.Build((string)input["id"]); } [Description("Gets the deployment results of all deployments.")] [WebGet(UriTemplate = "log")] public IEnumerable<DeployResult> GetDeployResults() { return _deploymentManager.GetResults(); } [Description("Gets the log of a specific deployment based on its id.")] [WebGet(UriTemplate = "log?id={id}")] public IEnumerable<LogEntry> GetLogEntry(string id) { return _deploymentManager.GetLogEntries(id); } [Description("Gets the deployment result of a specific deployment based on its id.")] [WebGet(UriTemplate = "details?id={id}")] public DeployResult GetResult(string id) { return _deploymentManager.GetResult(id); } } }
using System.Collections.Generic; using System.ComponentModel; using System.Json; using System.ServiceModel; using System.ServiceModel.Web; using Kudu.Core.Deployment; namespace Kudu.Services.Deployment { [ServiceContract] public class DeploymentService { private readonly IDeploymentManager _deploymentManager; public DeploymentService(IDeploymentManager deploymentManager) { _deploymentManager = deploymentManager; } [Description("Gets the id of the current active deployement.")] [WebGet(UriTemplate = "id")] public string GetActiveDeploymentId() { return _deploymentManager.ActiveDeploymentId; } [Description("Performs a deployment.")] [WebInvoke(UriTemplate = "")] public void Deploy() { _deploymentManager.Deploy(); } [Description("Restore a previously successful deployment based on its id.")] [WebInvoke(UriTemplate = "restore")] public void Restore(JsonObject input) { _deploymentManager.Deploy((string)input["id"]); } [Description("Builds a specific deployement based on its id.")] [WebInvoke(UriTemplate = "build")] public void Build(JsonObject input) { _deploymentManager.Build((string)input["id"]); } [Description("Gets the deployment results of all deployments.")] [WebGet(UriTemplate = "log")] public IEnumerable<DeployResult> GetDeployResults() { return _deploymentManager.GetResults(); } [Description("Gets the log of a specific deployement based on its id.")] [WebGet(UriTemplate = "log?id={id}")] public IEnumerable<LogEntry> GetLogEntry(string id) { return _deploymentManager.GetLogEntries(id); } [Description("Gets the deployement result of a specific deployement based on its id.")] [WebGet(UriTemplate = "details?id={id}")] public DeployResult GetResult(string id) { return _deploymentManager.GetResult(id); } } }
apache-2.0
C#
a4997e0f51b45aef43d860b663161e00cf7b8563
Add ScriptNamedArgument.ToString
textamina/scriban,lunet-io/scriban
src/Scriban/Syntax/ScriptNamedArgument.cs
src/Scriban/Syntax/ScriptNamedArgument.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. namespace Scriban.Syntax { public class ScriptNamedArgument : ScriptExpression { public ScriptNamedArgument() { } public ScriptNamedArgument(string name) { Name = name; } public ScriptNamedArgument(string name, ScriptExpression value) { Name = name; Value = value; } public string Name { get; set; } public ScriptExpression Value { get; set; } public override object Evaluate(TemplateContext context) { if (Value != null) return context.Evaluate(Value); return true; } public override void Write(RenderContext context) { if (Name == null) { return; } context.Write(Name); if (Value != null) { context.Write(":"); context.Write(Value); } } public override string ToString() { return $"{Name}: {Value}"; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. namespace Scriban.Syntax { public class ScriptNamedArgument : ScriptExpression { public ScriptNamedArgument() { } public ScriptNamedArgument(string name) { Name = name; } public ScriptNamedArgument(string name, ScriptExpression value) { Name = name; Value = value; } public string Name { get; set; } public ScriptExpression Value { get; set; } public override object Evaluate(TemplateContext context) { if (Value != null) return context.Evaluate(Value); return true; } public override void Write(RenderContext context) { if (Name == null) { return; } context.Write(Name); if (Value != null) { context.Write(":"); context.Write(Value); } } } }
bsd-2-clause
C#
a6e47c7c78eb2ceeb52004894bad3e0d2d8798b6
Fix typo
MarcosMeli/FileHelpers
FileHelpers/Attributes/FieldNullValueAttribute.cs
FileHelpers/Attributes/FieldNullValueAttribute.cs
using System; using System.ComponentModel; namespace FileHelpers { /// <summary> /// Indicates the value to assign to the field in the case of a NULL value. /// A default value if none supplied in the field itself. /// </summary> /// <remarks> /// You must specify a string and a converter that can be converted to the /// type or an object of the correct type to be directly assigned. /// <para/> /// See the <a href="http://www.filehelpers.net/mustread">complete attributes list</a> for more /// information and examples of each one. /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class FieldNullValueAttribute : Attribute { /// <summary>Default value for a null value.</summary> public object NullValue { get; private set; } // internal bool NullValueOnWrite = false; /// <summary> /// Defines the default in event of a null value. /// Object must be of the correct type /// </summary> /// <param name="nullValue">The value to assign the case of a NULL value.</param> public FieldNullValueAttribute(object nullValue) { NullValue = nullValue; // NullValueOnWrite = useOnWrite; } // /// <summary>Defines the default for a null value.</summary> // /// <param name="nullValue">The value to assign in the "NULL" case.</param> // public FieldNullValueAttribute(object nullValue): this(nullValue, false) // {} // /// <summary>Indicates a type and a string to be converted to that type.</summary> // /// <param name="type">The type of the null value.</param> // /// <param name="nullValue">The string to be converted to the specified type.</param> // /// <param name="useOnWrite">Indicates that if the field has that value when the library writes, then the engine use an empty string.</param> // public FieldNullValueAttribute(Type type, string nullValue, bool useOnWrite):this(Convert.ChangeType(nullValue, type, null), useOnWrite) // {} /// <summary>Indicates a type and a string to be converted to that type.</summary> /// <param name="type">The type of the null value.</param> /// <param name="nullValue">The string to be converted to the specified type.</param> public FieldNullValueAttribute(Type type, string nullValue) : this(TypeDescriptor.GetConverter(type).ConvertFromString(nullValue)) {} } }
using System; using System.ComponentModel; namespace FileHelpers { /// <summary> /// Indicates the value to assign to the field in the case of a NULL value. /// A default value if none supplied in the field itself. /// </summary> /// <remarks> /// You must specify a string and a converter that can be converted to the /// type or an object of the correct type to be directly assigned. /// <para/> /// See the <a href="http://www.filehelpers.net/mustread">complete attributes list</a> for more /// information and examples of each one. /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class FieldNullValueAttribute : Attribute { /// <summary>Default value for a null value.</summary> public object NullValue { get; private set; } // internal bool NullValueOnWrite = false; /// <summary> /// Defines the default in event of a null value. /// Object must be of teh correct type /// </summary> /// <param name="nullValue">The value to assign the case of a NULL value.</param> public FieldNullValueAttribute(object nullValue) { NullValue = nullValue; // NullValueOnWrite = useOnWrite; } // /// <summary>Defines the default for a null value.</summary> // /// <param name="nullValue">The value to assign in the "NULL" case.</param> // public FieldNullValueAttribute(object nullValue): this(nullValue, false) // {} // /// <summary>Indicates a type and a string to be converted to that type.</summary> // /// <param name="type">The type of the null value.</param> // /// <param name="nullValue">The string to be converted to the specified type.</param> // /// <param name="useOnWrite">Indicates that if the field has that value when the library writes, then the engine use an empty string.</param> // public FieldNullValueAttribute(Type type, string nullValue, bool useOnWrite):this(Convert.ChangeType(nullValue, type, null), useOnWrite) // {} /// <summary>Indicates a type and a string to be converted to that type.</summary> /// <param name="type">The type of the null value.</param> /// <param name="nullValue">The string to be converted to the specified type.</param> public FieldNullValueAttribute(Type type, string nullValue) : this(TypeDescriptor.GetConverter(type).ConvertFromString(nullValue)) {} } }
mit
C#
07a4459c02f728b936cd993209b8e8cc220149e7
Update testeController.cs
NanoMania/GitRepoVisualStudio,NanoMania/GitRepoVisualStudio
GitTutorialVS/Controllers/testeController.cs
GitTutorialVS/Controllers/testeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace GitTutorialVS.Controllers { public class testeController : Controller { // GET: teste public ActionResult Index() { //wejdwe jhfvsdjhsdjhcskjdzikzshisizk return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace GitTutorialVS.Controllers { public class testeController : Controller { // GET: teste public ActionResult Index() { //wejdwejhfvsdjhsdjhcskjdzikzshisizk return View(); } } }
mit
C#
a0c2376fc139facf1c67d18f40ea729bc2a12cae
fix package name
WasimAhmad/Serenity,linpiero/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,TukekeSoft/Serenity,rolembergfilho/Serenity,TukekeSoft/Serenity,linpiero/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,dfaruque/Serenity,volkanceylan/Serenity,linpiero/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,linpiero/Serenity,dfaruque/Serenity,linpiero/Serenity,dfaruque/Serenity,TukekeSoft/Serenity
Serenity.Reporting/Properties/AssemblyInfo.cs
Serenity.Reporting/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Serenity Platform - Reporting Library")] [assembly: AssemblyDescription( "Contains reporting classes...")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Serenity Platform - Data Entity Library")] [assembly: AssemblyDescription( "Contains reporting classes...")] [assembly: ComVisible(false)]
mit
C#
99b156f4ef623885638a17a295c9f7a426c2d22f
edit parameter in login request.
robertzml/Hyperion,robertzml/Hyperion,robertzml/Hyperion
Hyperion.BizAdapter/Protocol/LoginRequest.cs
Hyperion.BizAdapter/Protocol/LoginRequest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hyperion.BizAdapter.Protocol { using Newtonsoft.Json; /// <summary> /// 登录请求 /// </summary> public class LoginRequest : BaseRequest { #region Field /// <summary> /// 控制器 /// </summary> private string contolller = "freemall/accountToApp/"; #endregion //Field #region Method /// <summary> /// 用户登录 /// </summary> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <param name="osType">操作系统类型</param> /// <param name="loginType">登录方式</param> /// <param name="imei">IMEI</param> /// <returns></returns> public dynamic Login(string userName, string password, int osType, int loginType, string imei) { string url = ""; if (loginType == 3) { url = string.Format("{0}{1}login?phone={2}&password={3}&osType={4}&loginType={5}&imei={6}", host, contolller, userName, password, osType, loginType, imei); } else { url = string.Format("{0}{1}login?userName={2}&password={3}&osType={4}&loginType={5}&imei={6}", host, contolller, userName, password, osType, loginType, imei); } var content = Get(url); dynamic obj = JsonConvert.DeserializeObject<dynamic>(content); return obj; } #endregion //Method } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hyperion.BizAdapter.Protocol { using Newtonsoft.Json; /// <summary> /// 登录请求 /// </summary> public class LoginRequest : BaseRequest { #region Field /// <summary> /// 控制器 /// </summary> private string contolller = "freemall/accountToApp/"; #endregion //Field #region Method /// <summary> /// 用户登录 /// </summary> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <param name="osType">操作系统类型</param> /// <param name="loginType">登录方式</param> /// <param name="imei">IMEI</param> /// <returns></returns> public dynamic Login(string userName, string password, int osType, int loginType, string imei) { string url = string.Format("{0}{1}login?userName={2}&password={3}&phoneType={4}&loginType={5}&imei={6}", host, contolller, userName, password, osType, loginType, imei); var content = Get(url); dynamic obj = JsonConvert.DeserializeObject<dynamic>(content); return obj; } #endregion //Method } }
apache-2.0
C#
c6ad963c8de38c88abeb696b0f3f7c7cf53a91fb
clone the connection for each reader and writer, allow multithread access to the event store
Pondidum/Ledger.Stores.Postgres,Pondidum/Ledger.Stores.Postgres
Ledger.Stores.Postgres/PostgresEventStore.cs
Ledger.Stores.Postgres/PostgresEventStore.cs
using Npgsql; namespace Ledger.Stores.Postgres { public class PostgresEventStore : IEventStore { private readonly NpgsqlConnection _connection; public PostgresEventStore(NpgsqlConnection connection) { _connection = connection; } public IStoreReader<TKey> CreateReader<TKey>(IStoreConventions storeConventions) { var connection = _connection.Clone(); connection.Open(); var transaction = connection.BeginTransaction(); return new PostgresStoreReader<TKey>( connection, transaction, sql => Events(storeConventions, sql), sql => Snapshots(storeConventions, sql) ); } public IStoreWriter<TKey> CreateWriter<TKey>(IStoreConventions storeConventions) { var connection = _connection.Clone(); connection.Open(); var transaction = connection.BeginTransaction(); return new PostgresStoreWriter<TKey>( connection, transaction, sql => Events(storeConventions, sql), sql => Snapshots(storeConventions, sql) ); } private string Events(IStoreConventions conventions, string sql) { return sql.Replace("{table}", conventions.EventStoreName()); } private string Snapshots(IStoreConventions conventions, string sql) { return sql.Replace("{table}", conventions.SnapshotStoreName()); } } }
using System.Collections.Generic; using System.Data; using System.Linq; using Dapper; using Newtonsoft.Json; using Npgsql; namespace Ledger.Stores.Postgres { public class PostgresEventStore : IEventStore { private readonly NpgsqlConnection _connection; public PostgresEventStore(NpgsqlConnection connection) { _connection = connection; } public IStoreReader<TKey> CreateReader<TKey>(IStoreConventions storeConventions) { if (_connection.State != ConnectionState.Open) _connection.Open(); var transaction = _connection.BeginTransaction(); return new PostgresStoreReader<TKey>( _connection, transaction, sql => Events(storeConventions, sql), sql => Snapshots(storeConventions, sql) ); } public IStoreWriter<TKey> CreateWriter<TKey>(IStoreConventions storeConventions) { if (_connection.State != ConnectionState.Open) _connection.Open(); var transaction = _connection.BeginTransaction(); return new PostgresStoreWriter<TKey>( _connection, transaction, sql => Events(storeConventions, sql), sql => Snapshots(storeConventions, sql) ); } private string Events(IStoreConventions conventions, string sql) { return sql.Replace("{table}", conventions.EventStoreName()); } private string Snapshots(IStoreConventions conventions, string sql) { return sql.Replace("{table}", conventions.SnapshotStoreName()); } } }
lgpl-2.1
C#
a428e82d22faf94ffc245688e8a7d353e648c714
change parameter name
kaosborn/KaosCollections
Source/RankedSet/ICollectionDebugView.cs
Source/RankedSet/ICollectionDebugView.cs
// // Library: KaosCollections // File: ICollectionDebugView.cs // // Copyright © 2009-2017 Kasey Osborn (github.com/kaosborn) // MIT License - Use and redistribute freely // using System; using System.Collections.Generic; using System.Diagnostics; namespace Kaos.Collections { internal class ICollectionDebugView<T> { private readonly ICollection<T> target; public ICollectionDebugView (ICollection<T> collection) { if (collection == null) throw new ArgumentNullException (nameof (collection)); this.target = collection; } [DebuggerBrowsable (DebuggerBrowsableState.RootHidden)] public T[] Items { get { var items = new T[target.Count]; target.CopyTo (items, 0); return items; } } } }
// // Library: KaosCollections // File: ICollectionDebugView.cs // // Copyright © 2009-2017 Kasey Osborn (github.com/kaosborn) // MIT License - Use and redistribute freely // using System; using System.Collections.Generic; using System.Diagnostics; namespace Kaos.Collections { /// <exclude /> internal class ICollectionDebugView<T> { private readonly ICollection<T> target; public ICollectionDebugView (ICollection<T> dictionary) { if (dictionary == null) throw new ArgumentNullException (nameof (dictionary)); this.target = dictionary; } [DebuggerBrowsable (DebuggerBrowsableState.RootHidden)] public T[] Items { get { var items = new T[target.Count]; target.CopyTo (items, 0); return items; } } } }
mit
C#
018826069452470464326ebf4dc81fe330e10f40
Mark SynthesisEditContext obsolete because it is a bad pattern to use.
kamsar/Synthesis
Source/Synthesis/SynthesisEditContext.cs
Source/Synthesis/SynthesisEditContext.cs
using System; using Sitecore.Data.Items; namespace Synthesis { #pragma warning disable 0618 // disable the warning about InnerItem here - it's cool /// <summary> /// Provides a means to put an item in editing mode. /// </summary> /// <remarks> /// The item is enters editing mode when this object is created and leaves editing /// mode when the object is disposed. /// This provides an easy to use mechanism for editing items. /// </remarks> [Obsolete("You should not use an edit context because if an exception is thrown partial updates may be written to the item anyway. Use Editing.BeginEdit()...Editing.EndEdit() instead.")] public class SynthesisEditContext : EditContext { public SynthesisEditContext(IStandardTemplateItem item) : base(item.InnerItem) { } } #pragma warning restore 0618 }
using Sitecore.Data.Items; namespace Synthesis { #pragma warning disable 0618 // disable the warning about InnerItem here - it's cool /// <summary> /// Provides a means to put an item in editing mode. /// </summary> /// <remarks> /// The item is enters editing mode when this object is created and leaves editing /// mode when the object is disposed. /// This provides an easy to use mechanism for editing items. /// </remarks> public class SynthesisEditContext : EditContext { public SynthesisEditContext(IStandardTemplateItem item) : base(item.InnerItem) { } } #pragma warning restore 0618 }
mit
C#
ccd23a11e1f25525384c865c06248772adaedd95
Add optional predicate to Slash.System.FileUtils.CopyDirectory to filter the files that should be copied
SlashGames/slash-framework,SlashGames/slash-framework,SlashGames/slash-framework
Source/Slash.System/Source/Utils/FileUtils.cs
Source/Slash.System/Source/Utils/FileUtils.cs
namespace Slash.SystemExt.Utils { using System; using System.IO; public static class FileUtils { public static void CopyDirectory(string sourcePath, string destinationPath, Func<string, bool> predicate = null) { sourcePath = Path.GetFullPath(sourcePath); destinationPath = Path.GetFullPath(destinationPath); Directory.CreateDirectory(destinationPath); //Now Create all of the directories foreach (var dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath)); } //Copy all the files & Replaces any files with the same name foreach (var newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) { if (predicate == null || predicate(newPath)) { File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true); } } } } }
namespace Slash.SystemExt.Utils { using System.IO; public static class FileUtils { public static void CopyDirectory(string sourcePath, string destinationPath) { sourcePath = Path.GetFullPath(sourcePath); destinationPath = Path.GetFullPath(destinationPath); Directory.CreateDirectory(destinationPath); //Now Create all of the directories foreach (var dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath)); } //Copy all the files & Replaces any files with the same name foreach (var newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true); } } } }
mit
C#
73c29ac36091855c94929de1756e87a9ed815241
Update CPUReadCPUIDAsm.cs
CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos
source/Cosmos.Core_Asm/CPU/CPUReadCPUIDAsm.cs
source/Cosmos.Core_Asm/CPU/CPUReadCPUIDAsm.cs
using Cosmos.Debug.Kernel; using XSharp; using XSharp.Assembler; using static XSharp.XSRegisters; namespace Cosmos.Core_Asm { public class CPUReadCPUIDAsm : AssemblerMethod { private const int CpuIdTypeArgOffset = 4; private const int CpuIdEAXAddressArgOffset = 8; private const int CpuIdEBXAddressArgOffset = 12; private const int CpuIdECXAddressArgOffset = 16; private const int CpuIdEDXAddressArgOffset = 20; public override void AssembleNew(Assembler aAssembler, object aMethodInfo) { XS.Comment("Load type arg"); XS.Set(EAX, EBP, sourceDisplacement: CpuIdTypeArgOffset, sourceIsIndirect: true); XS.Cpuid(); XS.Comment("Save eax result arg"); XS.Set(EDI, EBP, sourceDisplacement: CpuIdEAXAddressArgOffset, sourceIsIndirect: true); XS.Set(EDI, EAX, destinationIsIndirect: true); XS.Comment("Save ebx result arg"); XS.Set(EDI, EBP, sourceDisplacement: CpuIdEBXAddressArgOffset, sourceIsIndirect: true); XS.Set(EDI, EBX, destinationIsIndirect: true); XS.Comment("Save ecx result arg"); XS.Set(EDI, EBP, sourceDisplacement: CpuIdECXAddressArgOffset, sourceIsIndirect: true); XS.Set(EDI, ECX, destinationIsIndirect: true); XS.Comment("Save edx result arg"); XS.Set(EDI, EBP, sourceDisplacement: CpuIdEDXAddressArgOffset, sourceIsIndirect: true); XS.Set(EDI, EDX, destinationIsIndirect: true); } } }
using XSharp.Assembler; namespace Cosmos.Core_Asm { public class CPUReadCPUIDAsm : AssemblerMethod { public override void AssembleNew(Assembler aAssembler, object aMethodInfo) { // TODO Get the type parameter from EBP+8 and move it to EAX /* * mov eax, 16h * cpuid */ // TODO The result of cpuid will be in EDX:EAX so it will need to be moved to the return value // Set ESI to EBP+8? } } }
bsd-3-clause
C#
9c03290966f85e78a865fe75932fd14aac653a40
Bump to v0.5.1
dancol90/mi-360
Source/mi-360/Properties/AssemblyInfo.cs
Source/mi-360/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Le informazioni generali relative a un assembly sono controllate dal seguente // set di attributi. Modificare i valori di questi attributi per modificare le informazioni // associate a un assembly. [assembly: AssemblyTitle("mi-360")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniele Colanardi")] [assembly: AssemblyProduct("mi-360")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili // ai componenti COM. Se è necessario accedere a un tipo in questo assembly da // COM, impostare su true l'attributo ComVisible per tale tipo. [assembly: ComVisible(false)] // Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi [assembly: Guid("885b11ae-354c-4690-a0a5-e9a82f51f262")] // Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: // // Versione principale // Versione secondaria // Numero di build // Revisione // // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build // usando l'asterisco '*' come illustrato di seguito: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Le informazioni generali relative a un assembly sono controllate dal seguente // set di attributi. Modificare i valori di questi attributi per modificare le informazioni // associate a un assembly. [assembly: AssemblyTitle("mi-360")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniele Colanardi")] [assembly: AssemblyProduct("mi-360")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili // ai componenti COM. Se è necessario accedere a un tipo in questo assembly da // COM, impostare su true l'attributo ComVisible per tale tipo. [assembly: ComVisible(false)] // Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi [assembly: Guid("885b11ae-354c-4690-a0a5-e9a82f51f262")] // Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: // // Versione principale // Versione secondaria // Numero di build // Revisione // // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build // usando l'asterisco '*' come illustrato di seguito: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.0")]
bsd-3-clause
C#
b99af5b461c017c04b2ec0acc9f9689376e4d37b
Throw more specific error if no SSL cert
MatthewSteeples/XeroAPI.Net
source/XeroApi/OAuth/XeroApiPartnerSession.cs
source/XeroApi/OAuth/XeroApiPartnerSession.cs
using System; using System.Security.Cryptography.X509Certificates; using DevDefined.OAuth.Consumer; using DevDefined.OAuth.Framework; using DevDefined.OAuth.Storage.Basic; namespace XeroApi.OAuth { public class XeroApiPartnerSession : OAuthSession { [Obsolete("Use the constructor with ITokenRepository")] public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate) : base(CreateConsumerContext(userAgent, consumerKey, signingCertificate)) { ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate)); } public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate, ITokenRepository tokenRepository) : base(CreateConsumerContext(userAgent, consumerKey, signingCertificate), tokenRepository) { ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate)); } private static IOAuthConsumerContext CreateConsumerContext(string userAgent, string consumerKey, X509Certificate2 signingCertificate) { if (signingCertificate == null) throw new ArgumentNullException(nameof(signingCertificate)); return new OAuthConsumerContext { // Public apps use HMAC-SHA1 SignatureMethod = SignatureMethod.RsaSha1, UseHeaderForOAuthParameters = true, // Urls RequestTokenUri = XeroApiEndpoints.PartnerRequestTokenUri, UserAuthorizeUri = XeroApiEndpoints.UserAuthorizeUri, AccessTokenUri = XeroApiEndpoints.PartnerAccessTokenUri, BaseEndpointUri = XeroApiEndpoints.PartnerBaseEndpointUri, Key = signingCertificate.PrivateKey, ConsumerKey = consumerKey, ConsumerSecret = string.Empty, UserAgent = userAgent, }; } } }
using System; using System.Security.Cryptography.X509Certificates; using DevDefined.OAuth.Consumer; using DevDefined.OAuth.Framework; using DevDefined.OAuth.Storage.Basic; namespace XeroApi.OAuth { public class XeroApiPartnerSession : OAuthSession { [Obsolete("Use the constructor with ITokenRepository")] public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate) : base(CreateConsumerContext(userAgent, consumerKey, signingCertificate)) { ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate)); } public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate, ITokenRepository tokenRepository) : base(CreateConsumerContext(userAgent, consumerKey, signingCertificate), tokenRepository) { ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate)); } private static IOAuthConsumerContext CreateConsumerContext(string userAgent, string consumerKey, X509Certificate2 signingCertificate) { return new OAuthConsumerContext { // Public apps use HMAC-SHA1 SignatureMethod = SignatureMethod.RsaSha1, UseHeaderForOAuthParameters = true, // Urls RequestTokenUri = XeroApiEndpoints.PartnerRequestTokenUri, UserAuthorizeUri = XeroApiEndpoints.UserAuthorizeUri, AccessTokenUri = XeroApiEndpoints.PartnerAccessTokenUri, BaseEndpointUri = XeroApiEndpoints.PartnerBaseEndpointUri, Key = signingCertificate.PrivateKey, ConsumerKey = consumerKey, ConsumerSecret = string.Empty, UserAgent = userAgent, }; } } }
mit
C#
230bd74ee55f71e0bbf592b310c89d2657efbc8b
Increment version.
jyuch/ReflectionToStringBuilder
src/ReflectionToStringBuilder/Properties/AssemblyInfo.cs
src/ReflectionToStringBuilder/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ReflectionToStringBuilder")] [assembly: AssemblyDescription("ReflectionでToStringするアレ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReflectionToStringBuilder")] [assembly: AssemblyCopyright("Copyright © 2015 jyuch")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("7e1cb969-5d63-4c0f-89ec-a1d0604eba75")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ReflectionToStringBuilder")] [assembly: AssemblyDescription("ReflectionでToStringするアレ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReflectionToStringBuilder")] [assembly: AssemblyCopyright("Copyright © 2015 jyuch")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("7e1cb969-5d63-4c0f-89ec-a1d0604eba75")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
mit
C#
487af09a76cbbad363a1c88fa0b7f09cc72bc5d3
Create first automated acceptance test
lifebeyondfife/Decider
Tests/Acceptance/LeagueGenerationTest.cs
Tests/Acceptance/LeagueGenerationTest.cs
/* Copyright Iain McDonald 2010-2020 This file is part of Decider. */ using System; using Xunit; using Decider.Example.LeagueGeneration; namespace Decider.Tests.Example { public class LeagueGenerationTest { [Fact] public void TestGenerating10() { var leagueGeneration = new LeagueGeneration(10); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); Assert.Equal(10, leagueGeneration.FixtureWeeks[0][1]); Assert.Equal(11, leagueGeneration.FixtureWeeks[0][2]); Assert.Equal(12, leagueGeneration.FixtureWeeks[0][3]); Assert.Equal(11, leagueGeneration.FixtureWeeks[5][6]); Assert.Equal(12, leagueGeneration.FixtureWeeks[5][7]); Assert.Equal(13, leagueGeneration.FixtureWeeks[5][8]); Assert.Equal(0, leagueGeneration.State.Backtracks); Assert.Equal(1, leagueGeneration.State.NumberOfSolutions); } [Fact] public void TestGenerating20() { var leagueGeneration = new LeagueGeneration(20); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); Assert.Equal(20, leagueGeneration.FixtureWeeks[0][1]); Assert.Equal(21, leagueGeneration.FixtureWeeks[0][2]); Assert.Equal(22, leagueGeneration.FixtureWeeks[0][3]); Assert.Equal(30, leagueGeneration.FixtureWeeks[5][6]); Assert.Equal(31, leagueGeneration.FixtureWeeks[5][7]); Assert.Equal(32, leagueGeneration.FixtureWeeks[5][8]); Assert.Equal(17, leagueGeneration.FixtureWeeks[17][0]); Assert.Equal(18, leagueGeneration.FixtureWeeks[17][1]); Assert.Equal(19, leagueGeneration.FixtureWeeks[17][2]); Assert.Equal(6262, leagueGeneration.State.Backtracks); Assert.Equal(1, leagueGeneration.State.NumberOfSolutions); } } }
/* Copyright Iain McDonald 2010-2020 This file is part of Decider. */ using System; using Xunit; using Decider.Example.LeagueGeneration; namespace Decider.Tests.Example { public class LeagueGenerationTest { [Fact] public void TestGenerating10() { var leagueGeneration = new LeagueGeneration(10); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); Assert.Equal(10, leagueGeneration.FixtureWeeks[0][1]); Assert.Equal(11, leagueGeneration.FixtureWeeks[0][2]); Assert.Equal(12, leagueGeneration.FixtureWeeks[0][3]); Assert.Equal(11, leagueGeneration.FixtureWeeks[5][6]); Assert.Equal(12, leagueGeneration.FixtureWeeks[5][7]); Assert.Equal(13, leagueGeneration.FixtureWeeks[5][8]); Assert.Equal(0, leagueGeneration.State.Backtracks); Assert.Equal(1, leagueGeneration.State.NumberOfSolutions); } [Fact] public void TestGenerating20() { var leagueGeneration = new LeagueGeneration(20); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); Assert.Equal(20, leagueGeneration.FixtureWeeks[0][1]); Assert.Equal(21, leagueGeneration.FixtureWeeks[0][2]); Assert.Equal(22, leagueGeneration.FixtureWeeks[0][3]); Assert.Equal(30, leagueGeneration.FixtureWeeks[5][6]); Assert.Equal(31, leagueGeneration.FixtureWeeks[5][7]); Assert.Equal(32, leagueGeneration.FixtureWeeks[5][8]); Assert.Equal(17, leagueGeneration.FixtureWeeks[17][0]); Assert.Equal(18, leagueGeneration.FixtureWeeks[17][1]); Assert.Equal(19, leagueGeneration.FixtureWeeks[17][2]); Assert.Equal(6262, leagueGeneration.State.Backtracks); Assert.Equal(1, leagueGeneration.State.NumberOfSolutions); } } }
mit
C#
2e60ba768d0c0a7feb4b5bdec18abb10e5c0dbb3
Update EnumerableExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/EnumerableExtensions.cs
src/EnumerableExtensions.cs
using System; using System.Collections.Generic; using System.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains static methods for working with enumerables. /// </summary> public static class EnumerableExtensions { /// <summary> /// Randomise the order of the elements in the <paramref name="source"/> enumerable. /// </summary> /// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam> /// <param name="source">The enumerable containing the elements to shuffle.</param> /// <returns>An enumerable containing the same elements but in a random order.</returns> public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) { return Shuffle(source, new Random()); } /// <summary> /// Randomise the order of the elements in the <paramref name="source"/> enumerable, using the specified <paramref name="random"/> seed. /// </summary> /// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam> /// <param name="source">The enumerable containing the elements to shuffle.</param> /// <param name="random">The random seed to use.</param> /// <returns>An enumerable containing the same elements but in a random order.</returns> public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random) { // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm var elements = source.ToArray(); for (var i = elements.Length - 1; i >= 0; i--) { // Swap element "i" with a random earlier element it (or itself) // ... except we don't really need to swap it fully, as we can // return it immediately, and afterwards it's irrelevant. var swapIndex = random.Next(i + 1); // Random.Next maxValue is an exclusive upper-bound, which is why we add 1 yield return elements[swapIndex]; elements[swapIndex] = elements[i]; } } /// <summary> /// Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>, without enumerating through every element. /// </summary> /// <typeparam name="T">The type of elements in the enumerable.</typeparam> /// <param name="enumerable">The enumerable sequence to check.</param> /// <param name="count">The count to exceed.</param> /// <returns>Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>.</returns> public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count) { return enumerable.Take(count + 1).Count() > count; } /// <summary> /// Converts the current <paramref name="value"/> to an enumerable, containing the <paramref name="value"/> as it's sole element. /// </summary> /// <typeparam name="T">The type of the element.</typeparam> /// <param name="value">The value that the new enumerable will contain.</param> /// <returns>Returns an enumerable containing a single element.</returns> public static IEnumerable<T> AsSingleEnumerable<T>(this T value) { //x return Enumerable.Repeat(value, 1); return new[] { value }; } } }
using System; using System.Collections.Generic; using System.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains static methods for working with <see cref="IEnumerable" />s. /// </summary> public static class EnumerableExtensions { /// <summary> /// Randomise the order of the elements in the <paramref name="source"/> enumerable. /// </summary> /// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam> /// <param name="source">The enumerable containing the elements to shuffle.</param> /// <returns>An enumerable containing the same elements but in a random order.</returns> public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) { return Shuffle(source, new Random()); } /// <summary> /// Randomise the order of the elements in the <paramref name="source"/> enumerable, using the specified <paramref name="random"/> seed. /// </summary> /// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam> /// <param name="source">The enumerable containing the elements to shuffle.</param> /// <param name="random">The random seed to use.</param> /// <returns>An enumerable containing the same elements but in a random order.</returns> public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random) { // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm var elements = source.ToArray(); for (var i = elements.Length - 1; i >= 0; i--) { // Swap element "i" with a random earlier element it (or itself) // ... except we don't really need to swap it fully, as we can // return it immediately, and afterwards it's irrelevant. var swapIndex = random.Next(i + 1); // Random.Next maxValue is an exclusive upper-bound, which is why we add 1 yield return elements[swapIndex]; elements[swapIndex] = elements[i]; } } /// <summary> /// Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>, without enumerating through every element. /// </summary> /// <typeparam name="T">The type of elements in the enumerable.</typeparam> /// <param name="enumerable">The enumerable sequence to check.</param> /// <param name="count">The count to exceed.</param> /// <returns>Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>.</returns> public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count) { return enumerable.Take(count + 1).Count() > count; } /// <summary> /// Converts the current <paramref name="value"/> to an enumerable, containing the <paramref name="value"/> as it's sole element. /// </summary> /// <typeparam name="T">The type of the element.</typeparam> /// <param name="value">The value that the new enumerable will contain.</param> /// <returns>Returns an enumerable containing a single element.</returns> public static IEnumerable<T> AsSingleEnumerable<T>(this T value) { //x return Enumerable.Repeat(value, 1); return new[] { value }; } } }
apache-2.0
C#
b4fd5a90c020cc9ef592d2980232742424b63088
Add thank you text to Complete page
ParcelForMe/p4m-demo-shop,ParcelForMe/p4m-demo-shop,ParcelForMe/p4m-demo-shop,ParcelForMe/p4m-demo-shop
OpenOrderFramework/Views/Checkout/Complete.cshtml
OpenOrderFramework/Views/Checkout/Complete.cshtml
@model int @{ ViewBag.Title = "Checkout Complete"; } <link rel="import" href="/Scripts/widgets/p4m-ajax-block/p4m-ajax-block.html"> <p4m-ajax-block content-url="https://local.parcelfor.me:44333/Content/Thankyou/Thankyou.html"></p4m-ajax-block> <h2>Checkout Complete</h2> <p>Thanks for your order! Your order number is: @Model</p> <p> How about shopping for some more stuff in our @Html.ActionLink("store","Index", "Home") </p>
@model int @{ ViewBag.Title = "Checkout Complete"; } <h2>Checkout Complete</h2> <p>Thanks for your order! Your order number is: @Model</p> <p> How about shopping for some more stuff in our @Html.ActionLink("store","Index", "Home") </p>
mit
C#
057c66b849821fcde23e63a5ec3cc2b4cc802e0f
fix bugs in ConsoleBitmapViewer
workabyte/PowerArgs,adamabdelhamed/PowerArgs,adamabdelhamed/PowerArgs,workabyte/PowerArgs
PowerArgs/CLI/Drawing/ConsoleBitmapViewer.cs
PowerArgs/CLI/Drawing/ConsoleBitmapViewer.cs
namespace PowerArgs.Cli { /// <summary> /// A control that can render a ConsoleBitmap /// </summary> public class ConsoleBitmapViewer : ConsoleControl { /// <summary> /// The bitmap to render /// </summary> public ConsoleBitmap Bitmap { get => Get<ConsoleBitmap>(); set => Set(value); } /// <summary> /// Creates a new console bitmap viewer /// </summary> public ConsoleBitmapViewer() { this.CanFocus = false; } /// <summary> /// Pains the target bitmap /// </summary> /// <param name="context"></param> protected override void OnPaint(ConsoleBitmap context) { if (Bitmap == null) return; for(var x = 0; x < Width && x < Bitmap.Width; x++) { for(var y = 0; y < Height && y < Bitmap.Height; y++) { var c = Bitmap.GetPixel(x, y).Value; if(c.HasValue) { context.Pen = c.Value; context.DrawPoint(x, y); } } } } } }
namespace PowerArgs.Cli { /// <summary> /// A control that can render a ConsoleBitmap /// </summary> public class ConsoleBitmapViewer : ConsoleControl { /// <summary> /// The bitmap to render /// </summary> public ConsoleBitmap Bitmap { get; set; } /// <summary> /// Creates a new console bitmap viewer /// </summary> public ConsoleBitmapViewer() { this.CanFocus = false; } /// <summary> /// Pains the target bitmap /// </summary> /// <param name="context"></param> protected override void OnPaint(ConsoleBitmap context) { if (Bitmap == null) return; for(var x = 0; x < Width && x < Bitmap.Width; x++) { for(var y = 0; y < Height & Y < Bitmap.Height; y++) { var c = Bitmap.GetPixel(x, y).Value; if(c.HasValue) { context.Pen = c.Value; context.DrawPoint(x, y); } } } } } }
mit
C#
807bb4151f9483a513ceb423738f4b0aa95573b5
Add Debug output
MorganR/wizards-chess,MorganR/wizards-chess
WizardsChess/WizardsChess/GpioToggler.cs
WizardsChess/WizardsChess/GpioToggler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Gpio; namespace WizardsChess { public sealed class GpioToggler { public GpioToggler(TimeSpan period, int pinNum) { this.period = period; gpio = GpioController.GetDefault(); pin = gpio.OpenPin(pinNum); } public void Start() { pin.Write(GpioPinValue.High); currentPinVal = GpioPinValue.High; pin.SetDriveMode(GpioPinDriveMode.Output); toggleTask = Task.Run(async () => { while (true) { await Task.Delay(period); toggle(); } }); } private void toggle() { System.Diagnostics.Debug.WriteLine("Toggling"); switch (currentPinVal) { case GpioPinValue.High: pin.Write(GpioPinValue.Low); currentPinVal = GpioPinValue.Low; break; case GpioPinValue.Low: default: pin.Write(GpioPinValue.High); currentPinVal = GpioPinValue.High; break; } } private TimeSpan period; private GpioPinValue currentPinVal; private GpioPin pin; private GpioController gpio; private Task toggleTask; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Gpio; namespace WizardsChess { public sealed class GpioToggler { public GpioToggler(TimeSpan period, int pinNum) { this.period = period; gpio = GpioController.GetDefault(); pin = gpio.OpenPin(pinNum); } public void Start() { pin.Write(GpioPinValue.High); currentPinVal = GpioPinValue.High; pin.SetDriveMode(GpioPinDriveMode.Output); toggleTask = Task.Run(async () => { while (true) { await Task.Delay(period); toggle(); } }); } private void toggle() { switch (currentPinVal) { case GpioPinValue.High: pin.Write(GpioPinValue.Low); currentPinVal = GpioPinValue.Low; break; case GpioPinValue.Low: default: pin.Write(GpioPinValue.High); currentPinVal = GpioPinValue.High; break; } } private TimeSpan period; private GpioPinValue currentPinVal; private GpioPin pin; private GpioController gpio; private Task toggleTask; } }
apache-2.0
C#
c983ed8092ea9deece58581f6759a9651d961aa3
change api config
iuv-dev/routecore,iuv-dev/routecore
RouteCore/RouteCore/App_Start/WebApiConfig.cs
RouteCore/RouteCore/App_Start/WebApiConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace RouteCore { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "API/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace RouteCore { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
mit
C#
0b9466029c96d547de28f3859482cd7344fcd773
remove unneeded method
matrostik/SQLitePCL.pretty,bordoley/SQLitePCL.pretty
SQLitePCL.pretty.Async/InterfacesContract.cs
SQLitePCL.pretty.Async/InterfacesContract.cs
/* Copyright 2014 David Bordoley Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace SQLitePCL.pretty { [ContractClassFor(typeof(IAsyncDatabaseConnection))] internal abstract class IAsyncDatabaseConnectionContract : IAsyncDatabaseConnection { public abstract IObservable<DatabaseTraceEventArgs> Trace { get; } public abstract IObservable<DatabaseProfileEventArgs> Profile { get; } public abstract IObservable<DatabaseUpdateEventArgs> Update { get; } public abstract void Dispose(); public abstract Task DisposeAsync(); public IObservable<T> Use<T>(Func<IDatabaseConnection, IEnumerable<T>> f) { Contract.Requires(f != null); return default(IObservable<T>); } } [ContractClassFor(typeof(IAsyncStatement))] internal abstract class IAsyncStatementContract : IAsyncStatement { public abstract void Dispose(); public IObservable<T> Use<T>(Func<IStatement, IEnumerable<T>> f) { Contract.Requires(f != null); return default(IObservable<T>); } } }
/* Copyright 2014 David Bordoley Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace SQLitePCL.pretty { [ContractClassFor(typeof(IAsyncDatabaseConnection))] internal abstract class IAsyncDatabaseConnectionContract : IAsyncDatabaseConnection { public abstract IObservable<DatabaseTraceEventArgs> Trace { get; } public abstract IObservable<DatabaseProfileEventArgs> Profile { get; } public abstract IObservable<DatabaseUpdateEventArgs> Update { get; } public abstract void Dispose(); public abstract Task DisposeAsync(); public IObservable<T> Use<T>(Func<IDatabaseConnection, IEnumerable<T>> f) { Contract.Requires(f != null); return default(IObservable<T>); } } [ContractClassFor(typeof(IAsyncStatement))] internal abstract class IAsyncStatementContract : IAsyncStatement { public abstract void Dispose(); public abstract Task DisposeAsync(); public IObservable<T> Use<T>(Func<IStatement, IEnumerable<T>> f) { Contract.Requires(f != null); return default(IObservable<T>); } } }
apache-2.0
C#
a2fccb073d6aa0b636b0f4b63fae22182d91930d
Change div class and change the position of button back
Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog
SpaceBlog/SpaceBlog/Views/Comment/Edit.cshtml
SpaceBlog/SpaceBlog/Views/Comment/Edit.cshtml
@model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; ViewBag.Message = "Comment"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="container"> <h2>@ViewBag.Title</h2> <h4>@ViewBag.Message</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10" style="margin-top: 10px"> <input type="submit" value="Save" class="btn btn-success" /> @Html.ActionLink("Back", "Index", new { @id = ""}, new { @class = "btn btn-primary" }) </div> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Comment</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
mit
C#
47c6d90db3bef9f0100b5d886b43c8711e13c448
fix S_BOSS_GAGE_INFO field types
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TeraPacketParser/Messages/S_BOSS_GAGE_INFO.cs
TeraPacketParser/Messages/S_BOSS_GAGE_INFO.cs
namespace TeraPacketParser.Messages { public class S_BOSS_GAGE_INFO : ParsedMessage { //private ulong id, targetId; //private int templateId, huntingZoneId;//, unk1; //private float /*hpDiff,*/ currHp, maxHp; //private byte enrage/*, unk3*/; public ulong EntityId { get; } public uint TemplateId { get; } public uint HuntingZoneId { get; } public float CurrentHP { get; } public float MaxHP { get; } public ulong Target { get; } public bool Enrage { get; } public S_BOSS_GAGE_INFO(TeraMessageReader reader) : base(reader) { EntityId = reader.ReadUInt64(); HuntingZoneId = reader.ReadUInt32(); TemplateId = reader.ReadUInt32(); Target = reader.ReadUInt64(); reader.Skip(4); //unk1 = reader.ReadInt32(); //if (reader.Version < 321550 || reader.Version > 321600) //{ Enrage = reader.ReadBoolean(); CurrentHP = reader.ReadInt64(); MaxHP = reader.ReadInt64(); //} //else //{ // hpDiff = reader.ReadSingle(); // enrage = reader.ReadByte(); // currHp = reader.ReadSingle(); // maxHp = reader.ReadSingle(); //} //unk3 = reader.ReadByte(); } } }
namespace TeraPacketParser.Messages { public class S_BOSS_GAGE_INFO : ParsedMessage { //private ulong id, targetId; //private int templateId, huntingZoneId;//, unk1; //private float /*hpDiff,*/ currHp, maxHp; //private byte enrage/*, unk3*/; public ulong EntityId { get; } public int TemplateId { get; } public int HuntingZoneId { get; } public float CurrentHP { get; } public float MaxHP { get; } public ulong Target { get; } public bool Enrage { get; } public S_BOSS_GAGE_INFO(TeraMessageReader reader) : base(reader) { EntityId = reader.ReadUInt64(); HuntingZoneId = reader.ReadInt32(); TemplateId = reader.ReadInt32(); Target = reader.ReadUInt64(); reader.Skip(4); //unk1 = reader.ReadInt32(); //if (reader.Version < 321550 || reader.Version > 321600) //{ Enrage = reader.ReadBoolean(); CurrentHP = reader.ReadInt64(); MaxHP = reader.ReadInt64(); //} //else //{ // hpDiff = reader.ReadSingle(); // enrage = reader.ReadByte(); // currHp = reader.ReadSingle(); // maxHp = reader.ReadSingle(); //} //unk3 = reader.ReadByte(); } } }
mit
C#
d519f13fe62047aa7d9fe93614c4426adca52031
Ajuste no valor Maximum closes #3
adrianocaldeira/thunder
src/main/Thunder/ComponentModel/DataAnnotations/NumberAttribute.cs
src/main/Thunder/ComponentModel/DataAnnotations/NumberAttribute.cs
using System; using System.ComponentModel.DataAnnotations; namespace Thunder.ComponentModel.DataAnnotations { /// <summary> /// Positive number validator /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class NumberAttribute : ValidationAttribute { /// <summary> /// Initialize new instance of <see cref="NumberAttribute"/>. /// </summary> public NumberAttribute() { Maximum = 9999999; } /// <summary> /// Get or set minimum mumber. Default 0. /// </summary> public int Minimum { get; set; } /// <summary> /// Get or set maximum mumber. Default 999. /// </summary> public int Maximum { get; set; } /// <summary> /// Is number /// </summary> /// <param name="value">Value</param> /// <returns></returns> public override bool IsValid(object value) { if (value == null) return true; int number; if (int.TryParse(value.ToString(), out number)) { return (number >= Minimum && number <= Maximum); } return false; } } }
using System; using System.ComponentModel.DataAnnotations; namespace Thunder.ComponentModel.DataAnnotations { /// <summary> /// Positive number validator /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class NumberAttribute : ValidationAttribute { /// <summary> /// Initialize new instance of <see cref="NumberAttribute"/>. /// </summary> public NumberAttribute() { Maximum = 999; } /// <summary> /// Get or set minimum mumber. Default 0. /// </summary> public int Minimum { get; set; } /// <summary> /// Get or set maximum mumber. Default 999. /// </summary> public int Maximum { get; set; } /// <summary> /// Is number /// </summary> /// <param name="value">Value</param> /// <returns></returns> public override bool IsValid(object value) { if (value == null) return true; int number; if (int.TryParse(value.ToString(), out number)) { return (number >= Minimum && number <= Maximum); } return false; } } }
mit
C#
3ea220ebe6f6a814ef0b5fb391e2af4523fec3b6
Add new file userAuth.cpl/Droid/Properties/AssemblyInfo.cs
ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl
userAuth.cpl/Droid/Properties/AssemblyInfo.cs
userAuth.cpl/Droid/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using Android.App; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("userAuth.cpl.Droid")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("RonThomas")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; using Android.App; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("userAuth.cpl.Droid")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("RonThomas")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
3a0c2a879d3310bd57416cafd94db17917492462
Add another extensions support for wallpaper service.
yas-mnkornym/SylphyHorn,Grabacr07/SylphyHorn,mntone/SylphyHorn
source/SylphyHorn/Services/WallpaperService.cs
source/SylphyHorn/Services/WallpaperService.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using SylphyHorn.Interop; using SylphyHorn.Serialization; using WindowsDesktop; namespace SylphyHorn.Services { public class WallpaperService : IDisposable { private static readonly string[] _supportedExtensions = { ".png", ".jpg", ".jpeg", ".bmp", }; public static WallpaperService Instance { get; } = new WallpaperService(); private WallpaperService() { VirtualDesktop.CurrentChanged += VirtualDesktopOnCurrentChanged; } private static void VirtualDesktopOnCurrentChanged(object sender, VirtualDesktopChangedEventArgs e) { VisualHelper.InvokeOnUIDispatcher(() => { var desktops = VirtualDesktop.GetDesktops(); var newIndex = Array.IndexOf(desktops, e.NewDesktop) + 1; var dirPath = Settings.General.DesktopBackgroundFolderPath.Value ?? ""; if (Directory.Exists(dirPath)) { foreach (var extension in _supportedExtensions) { var filePath = Path.Combine(dirPath, newIndex + extension); var wallpaper = new FileInfo(filePath); if (wallpaper.Exists) { Set(wallpaper.FullName); break; } } } }); } public void Dispose() { VirtualDesktop.CurrentChanged -= VirtualDesktopOnCurrentChanged; } public static void Set(string path) { NativeMethods.SystemParametersInfo( SystemParametersInfo.SPI_SETDESKWALLPAPER, 0, path, SystemParametersInfoFlag.SPIF_UPDATEINIFILE | SystemParametersInfoFlag.SPIF_SENDWININICHANGE); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using SylphyHorn.Interop; using SylphyHorn.Serialization; using WindowsDesktop; namespace SylphyHorn.Services { public class WallpaperService : IDisposable { public static WallpaperService Instance { get; } = new WallpaperService(); private WallpaperService() { VirtualDesktop.CurrentChanged += VirtualDesktopOnCurrentChanged; } private static void VirtualDesktopOnCurrentChanged(object sender, VirtualDesktopChangedEventArgs e) { VisualHelper.InvokeOnUIDispatcher(() => { var desktops = VirtualDesktop.GetDesktops(); var newIndex = Array.IndexOf(desktops, e.NewDesktop) + 1; var imgDirectoryPath = Settings.General.DesktopBackgroundFolderPath.Value ?? ""; var imgPath = Path.Combine(imgDirectoryPath, newIndex + ".bmp"); if (File.Exists(imgPath)) { Set(imgPath); } }); } public void Dispose() { VirtualDesktop.CurrentChanged -= VirtualDesktopOnCurrentChanged; } public static void Set(string path) { NativeMethods.SystemParametersInfo( SystemParametersInfo.SPI_SETDESKWALLPAPER, 0, path, SystemParametersInfoFlag.SPIF_UPDATEINIFILE | SystemParametersInfoFlag.SPIF_SENDWININICHANGE); } } }
mit
C#
1f31e3fb5199b646c00ed448fe1ca2b7658752e8
Add volume UI to toolbar music button
peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game/Overlays/Toolbar/ToolbarMusicButton.cs
osu.Game/Overlays/Toolbar/ToolbarMusicButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Input.Bindings; using osuTK.Graphics; namespace osu.Game.Overlays.Toolbar { public class ToolbarMusicButton : ToolbarOverlayToggleButton { private Circle volumeBar; protected override Anchor TooltipAnchor => Anchor.TopRight; public ToolbarMusicButton() { Hotkey = GlobalAction.ToggleNowPlaying; AutoSizeAxes = Axes.X; } [BackgroundDependencyLoader(true)] private void load(NowPlayingOverlay music) { StateContainer = music; Flow.Padding = new MarginPadding { Horizontal = Toolbar.HEIGHT / 4 }; Flow.Add(new Container { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 3f, Height = IconContainer.Height, Margin = new MarginPadding { Horizontal = 2.5f }, Masking = true, Children = new[] { new Circle { RelativeSizeAxes = Axes.Both, Colour = Color4.White.Opacity(0.25f), }, volumeBar = new Circle { RelativeSizeAxes = Axes.Both, Height = 0f, Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Colour = Color4.White, } } }); } [Resolved] private AudioManager audio { get; set; } [Resolved(canBeNull: true)] private VolumeOverlay volume { get; set; } private IBindable<double> globalVolume; protected override void LoadComplete() { base.LoadComplete(); globalVolume = audio.Volume.GetBoundCopy(); globalVolume.BindValueChanged(v => volumeBar.Height = (float)v.NewValue, true); } protected override bool OnScroll(ScrollEvent e) { volume?.Adjust(GlobalAction.IncreaseVolume, e.ScrollDelta.Y, e.IsPrecise); return true; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Toolbar { public class ToolbarMusicButton : ToolbarOverlayToggleButton { protected override Anchor TooltipAnchor => Anchor.TopRight; public ToolbarMusicButton() { Hotkey = GlobalAction.ToggleNowPlaying; } [BackgroundDependencyLoader(true)] private void load(NowPlayingOverlay music) { StateContainer = music; } [Resolved(canBeNull: true)] private VolumeOverlay volume { get; set; } protected override bool OnScroll(ScrollEvent e) { volume?.Adjust(GlobalAction.IncreaseVolume, e.ScrollDelta.Y, e.IsPrecise); return true; } } }
mit
C#
fe4413811ac31257530189679d225ae530cf9db6
fix summary information
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
src/MobileApps/MyDriving/MyDriving.iOS/Screens/Trips/TripSummaryViewController.cs
src/MobileApps/MyDriving/MyDriving.iOS/Screens/Trips/TripSummaryViewController.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using UIKit; namespace MyDriving.iOS { public partial class TripSummaryViewController : UIViewController { public TripSummaryViewController(IntPtr handle) : base(handle) { } public ViewModel.CurrentTripViewModel ViewModel { get; set; } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = ViewModel.TripSummary.TotalDistanceDisplay; lblDuration.Text = ViewModel.TripSummary.TotalTimeDisplay; lblFuelConsumed.Text = ViewModel.TripSummary.FuelDisplay; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override async void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await DismissViewControllerAsync(true); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using UIKit; namespace MyDriving.iOS { public partial class TripSummaryViewController : UIViewController { public TripSummaryViewController(IntPtr handle) : base(handle) { } public ViewModel.CurrentTripViewModel ViewModel { get; set; } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override async void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await DismissViewControllerAsync(true); } } }
mit
C#
c8ff18dff0829672435020a5e9dfac37ae75b57d
Add the state system for detailed control.
yohei-washizaki/input-challenge,yohei-washizaki/input-challenge,yohei-washizaki/input-challenge
UnityProject/Assets/Washi/Scripts/PseudoScreen.cs
UnityProject/Assets/Washi/Scripts/PseudoScreen.cs
using UnityEngine; using System.Collections; [AddComponentMenu("Scripts/Washi/PseudoScreen")] public class PseudoScreen : MonoBehaviour { int width{get;set;} int height{get;set;} public bool _isActive = true; public bool isActive { get{return this._isActive;} private set{this._isActive = value;} } bool prevInput{get;set;} Vector2 prevMousePosition{get; set;} Vector2 curMousePosition{get;set;} public float _sensibility = 1.0F; public float sensibility { get{return this._sensibility;} set{this._sensibility = value;} } Vector2 startPoint{get; set;} private enum TouchState { None, Began, Ended, Canceled, Touching } TouchState touchState{get;set;} public int touchCount { get; private set; } // Use this for initialization void Start () { this.width = Screen.width; this.height = Screen.height; this.touchState = TouchState.None; this.touchCount = 0; } // Update is called once per frame void Update () { if(!this.isActive) { return; } // Change state. switch(this.touchState) { case TouchState.None: // No change. break; case TouchState.Began: this.touchState = TouchState.Touching; break; case TouchState.Touching: // No change. break; case TouchState.Ended: this.touchState = TouchState.None; --this.touchCount; break; case TouchState.Canceled: this.touchState = TouchState.None; --this.touchCount; break; default: break; } this.prevMousePosition = this.curMousePosition; this.curMousePosition = Input.mousePosition; // Handle state if(this.touchState == TouchState.None) { if(Input.GetMouseButtonDown(0)) { Debug.Log("Touch began."); this.startPoint = this.curMousePosition; this.touchState = TouchState.Began; ++this.touchCount; // TODO: Notify listeners of the event. } } else if(this.touchState == TouchState.Touching) { if(Input.GetMouseButtonUp(0)) { Debug.Log("Touch ended."); this.touchState = TouchState.Ended; // TODO: Notify listeners of the event. } else if(Input.GetMouseButton(0)) { if(Input.GetMouseButtonDown(1)) { Debug.Log("Touch canceled."); this.touchState = TouchState.Canceled; // TODO: Notify listeners of the event. } else { this.touchState = TouchState.Touching; Vector2 deltaMove = this.prevMousePosition - this.curMousePosition; if(deltaMove.sqrMagnitude > this.sensibility) { Debug.Log("Touch moved."); // TODO: Notify listeners of the event. } else { // Debug.Log("Touch stationary."); } } } } // Go through this path only on mobile devices. foreach(UnityEngine.Touch touch in Input.touches) { switch(touch.phase) { case TouchPhase.Began: Debug.Log("Touch began."); break; case TouchPhase.Canceled: Debug.Log("Touch canceled."); break; case TouchPhase.Ended: Debug.Log("Touch end."); break; case TouchPhase.Moved: Debug.Log("Touch moved."); break; case TouchPhase.Stationary: Debug.Log ("Touch stationary."); break; } } } }
using UnityEngine; using System.Collections; [AddComponentMenu("Scripts/Washi/PseudoScreen")] public class PseudoScreen : MonoBehaviour { int width; public int Width { get{return width;} } int height; public int Height { get{return height;} } private bool isActive = true; public bool IsActive { get{return this.isActive;} private set{this.isActive = value;} } // Use this for initialization void Start () { this.width = Screen.width; this.height = Screen.height; } // Update is called once per frame void Update () { if(!this.IsActive) { return; } if(Input.GetMouseButtonDown(0)) { } foreach(Touch touch in Input.touches) { switch(touch.phase) { case TouchPhase.Began: Debug.Log("Touch began."); break; case TouchPhase.Canceled: Debug.Log("Touch canceled."); break; case TouchPhase.Ended: Debug.Log("Touch end."); break; case TouchPhase.Moved: Debug.Log("Touch moved."); break; case TouchPhase.Stationary: Debug.Log ("Touch stationary."); break; } } } }
mit
C#
cdf618966a97541a37ab42433815c850f4ed120b
fix error
bcuff/FodyAddinSamples,Fody/FodyAddinSamples,Fody/FodyAddinSamples
ResourcerSample/Sample.cs
ResourcerSample/Sample.cs
using NUnit.Framework; using Resourcer; [TestFixture] public class ResourcerSample { [Test] public void Run() { var fromResource = Resource.AsString("SampleResource.txt"); Assert.AreEqual("Hello", fromResource); } }
using NUnit.Framework; using Resourcer; [TestFixture] public class ResourcerSample { [Test] public void Run() { var fromResource = Resource.AsString("SampleResource2.txt"); Assert.AreEqual("Hello", fromResource); var fromResource2 = Resource.AsString("SampleResource4.txt"); Assert.AreEqual("Hello", fromResource); } }
mit
C#
0ecd930cad6d2a562c93ba795707a9b271eea7b4
Add ScrollToTop extension method
pellea/waslibs,wasteam/waslibs,wasteam/waslibs,wasteam/waslibs,pellea/waslibs,janabimustafa/waslibs,janabimustafa/waslibs,pellea/waslibs,janabimustafa/waslibs
src/AppStudio.Uwp/Extensions/XamlExtensions.cs
src/AppStudio.Uwp/Extensions/XamlExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace AppStudio.Uwp { public static class XamlExtensions { public static T FindChildOfType<T>(this DependencyObject parent) where T : DependencyObject { if (parent == null) return null; T foundChild = null; int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); T childType = child as T; if (childType == null) { // The child is not of the request child type. Recursively drill down the tree. foundChild = child.FindChildOfType<T>(); if (foundChild != null) break; } else { // child element found. foundChild = (T)child; break; } } return foundChild; } public static void ScrollToTop(this DependencyObject parent) { ScrollViewer scrollViewer = parent.FindChildOfType<ScrollViewer>(); if (scrollViewer != null) { scrollViewer.ChangeView(0, 0, scrollViewer.ZoomFactor, true); } } public static object Resource(this string self) { if (Application.Current.Resources.ContainsKey(self)) { return Application.Current.Resources[self]; } else { return null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace AppStudio.Uwp { public static class XamlExtensions { public static T FindChildOfType<T>(this DependencyObject parent) where T : DependencyObject { if (parent == null) return null; T foundChild = null; int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); T childType = child as T; if (childType == null) { // The child is not of the request child type. Recursively drill down the tree. foundChild = child.FindChildOfType<T>(); if (foundChild != null) break; } else { // child element found. foundChild = (T)child; break; } } return foundChild; } public static object Resource(this string self) { if (Application.Current.Resources.ContainsKey(self)) { return Application.Current.Resources[self]; } else { return null; } } } }
mit
C#
0b7f211b3a9a98449fc0e6a6c6efd4a911645739
fix build error.
jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia
src/Avalonia.OpenGL/Angle/AngleEglInterface.cs
src/Avalonia.OpenGL/Angle/AngleEglInterface.cs
using System; using System.Runtime.InteropServices; namespace Avalonia.OpenGL.Angle { public class AngleEglInterface : EglInterface { [DllImport("avangle.dll", CharSet = CharSet.Ansi)] static extern IntPtr EGL_GetProcAddress(string proc); public AngleEglInterface() : base(LoadAngle()) { } static Func<string, IntPtr> LoadAngle() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var disp = EGL_GetProcAddress("eglGetPlatformDisplayEXT"); if (disp == IntPtr.Zero) { throw new OpenGlException("libegl.dll doesn't have eglGetPlatformDisplayEXT entry point"); } return EGL_GetProcAddress; } throw new PlatformNotSupportedException(); } } }
using System; using System.Runtime.InteropServices; namespace Avalonia.OpenGL.Angle { public class AngleEglInterface : EglInterface { [DllImport("avangle.dll", CharSet = CharSet.Ansi)] static extern IntPtr EGL_GetProcAddress(string proc); public AngleEglInterface() : base(LoadAngle()) { } static Func<string, IntPtr> LoadAngle() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var disp = EGL_GetProcAddress("eglGetPlatformDisplayEXT"); if (disp == IntPtr.Zero) { throw new OpenGlException("libegl.dll doesn't have eglGetPlatformDisplayEXT entry point"); } return eglGetProcAddress; } throw new PlatformNotSupportedException(); } } }
mit
C#
e0f6d50869be642ee974f23d05f28991493856a8
Fix add form
mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection
src/Cash-Flow-Projection/Views/Home/Add.cshtml
src/Cash-Flow-Projection/Views/Home/Add.cshtml
@model Cash_Flow_Projection.Models.Entry @using (Html.BeginForm("Add", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.HiddenFor(model => model.id) @Html.ValidationSummary() <div class="form-group form-group-xlg"> @Html.EditorFor(m => m.Date, new { @class = "form-control", required = "required", placeholder = Html.DisplayNameFor(x => x.Date) }) </div> <div class="form-group form-group-xlg"> @Html.TextBoxFor(m => m.Amount, new { @class = "form-control", required = "required", placeholder = Html.DisplayNameFor(x => x.Amount) }) </div> <div class="form-group form-group-xlg"> @Html.TextBoxFor(m => m.Description, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.Description) }) </div> <button type="submit">Add Entry</button> }
@model Cash_Flow_Projection.Models.Entry @using (Html.BeginForm("Add", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" )) { @Html.HiddenFor(model => model.id) @Html.ValidationSummary() <div class="form-group form-group-xlg"> @Html.TextBoxFor(m => m.Date, new { @class = "form-control", required = "required", placeholder = Html.DisplayNameFor(x => x.Date) }) </div> <div class="form-group form-group-xlg"> @Html.TextBoxFor(m => m.Amount, new { @class = "form-control", required = "required", placeholder = Html.DisplayNameFor(x => x.Amount) }) </div> <div class="form-group form-group-xlg"> @Html.TextBoxFor(m => m.Description, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.Description) }) </div> <button type="submit"></button> }
mit
C#
a5934e056ba85b3c82f899b066d9b5c1e4916d62
add msiing doc.
kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre
src/Editor/OSREEditor/Model/Actions/IAction.cs
src/Editor/OSREEditor/Model/Actions/IAction.cs
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------------------------*/ namespace OSREEditor.Model.Actions { /// <summary> /// This interfae is used to declare the API for acion implementations. /// </summary> interface IAction { /// <summary> /// Override this for your action execution. /// </summary> /// <returns>true, if successful.</returns> bool Execute(); } }
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------------------------*/ namespace OSREEditor.Model.Actions { interface IAction { bool Execute(); } }
mit
C#
c0001a8b71fb62d9911546a8bf0e54f14b9c3877
Update SDK version to 4.0.3
NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity
ncmb_unity/Assets/NCMB/Script/CommonConstant.cs
ncmb_unity/Assets/NCMB/Script/CommonConstant.cs
/******* Copyright 2017-2020 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "4.0.5"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
/******* Copyright 2017-2020 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "4.0.4"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
apache-2.0
C#
6fdc7be34b4cd63751b522b2d44a1a965f7f90fe
Update ExceptionExtensions.cs
SimonCropp/NServiceBus.Serilog
src/NServiceBus.Serilog/ExceptionExtensions.cs
src/NServiceBus.Serilog/ExceptionExtensions.cs
using System; #pragma warning disable 1591 static class ExceptionExtensions { public static bool TryReadData<T>(this Exception exception, string key, out T state) { var data = exception.Data; if (data.Contains(key)) { state = (T) data[key]; data.Remove(key); return true; } #pragma warning disable CS8653, CS8601 state = default; #pragma warning restore return false; } }
using System; #pragma warning disable 1591 static class ExceptionExtensions { public static bool TryReadData<T>(this Exception exception, string key, out T state) { var data = exception.Data; if (data.Contains(key)) { state = (T) data[key]; data.Remove(key); return true; } #pragma warning disable CS8653 state = default; #pragma warning restore CS8653 return false; } }
mit
C#
0263707a5971a00bfd23b9d0a70c0b1afd44f63b
Change assertion to support multiple issues in test
JetBrains/YouTrackSharp,JetBrains/YouTrackSharp
tests/YouTrackSharp.Tests/Integration/Issues/GetIssuesInProject.cs
tests/YouTrackSharp.Tests/Integration/Issues/GetIssuesInProject.cs
using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); foreach (dynamic issue in result) { Assert.Equal("DP1", issue.ProjectShortName); } } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }
using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); Assert.Collection(result, issue => Assert.Equal("DP1", ((dynamic)issue).ProjectShortName)); } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }
apache-2.0
C#
3aed9aa559c3e9c6d5f1dcc07c9c4f55bb1b4bc5
add IServiceProviderExtensionMethods.GetService<T>()
TakeAsh/cs-WpfUtility
WpfUtility/TrExtension.cs
WpfUtility/TrExtension.cs
using System; using System.Resources; using System.Windows.Markup; using System.Xaml; namespace WpfUtility { /// <summary> /// Translation Extension for XAML Markup /// </summary> /// <remarks> /// <list type="bullet"> /// <item>[XAML のマークアップ拡張を使った WPF での国際化 | プログラマーズ雑記帳](http://yohshiy.blog.fc2.com/blog-entry-242.html)</item> /// <item>[Internationalization in .NET and WPF - Lorenz Cuno Klopfenstein - Klopfenstein.net](http://www.klopfenstein.net/lorenz.aspx/internationalization-in-net-and-wpf-presentation-foundation)</item> /// <item>[Accessing "current class" from WPF custom MarkupExtension - Stack Overflow](http://stackoverflow.com/questions/3047448)</item> /// </list> /// </remarks> [MarkupExtensionReturnType(typeof(string))] public class TrExtension : MarkupExtension { const string NotFoundError = "#NotFound#"; string _key; public TrExtension(string key) { _key = key; } public override object ProvideValue(IServiceProvider serviceProvider) { if (String.IsNullOrEmpty(_key)) { return NotFoundError; } ResourceManager resourceManager; var rootObjectProvider = serviceProvider.GetService<IRootObjectProvider>(); if (rootObjectProvider != null && (resourceManager = ResourceHelper.GetResourceManager(rootObjectProvider.RootObject)) != null) { return resourceManager.GetString(_key) ?? _key; } return _key; } } public static class IServiceProviderExtensionMethods { public static T GetService<T>(this IServiceProvider serviceProvider) where T : class { return serviceProvider != null ? serviceProvider.GetService(typeof(T)) as T : null; } } }
using System; using System.Resources; using System.Windows.Markup; using System.Xaml; namespace WpfUtility { /// <summary> /// Translation Extension for XAML Markup /// </summary> /// <remarks> /// <list type="bullet"> /// <item>[XAML のマークアップ拡張を使った WPF での国際化 | プログラマーズ雑記帳](http://yohshiy.blog.fc2.com/blog-entry-242.html)</item> /// <item>[Internationalization in .NET and WPF - Lorenz Cuno Klopfenstein - Klopfenstein.net](http://www.klopfenstein.net/lorenz.aspx/internationalization-in-net-and-wpf-presentation-foundation)</item> /// <item>[Accessing "current class" from WPF custom MarkupExtension - Stack Overflow](http://stackoverflow.com/questions/3047448)</item> /// </list> /// </remarks> [MarkupExtensionReturnType(typeof(string))] public class TrExtension : MarkupExtension { const string NotFoundError = "#NotFound#"; string _key; public TrExtension(string key) { _key = key; } public override object ProvideValue(IServiceProvider serviceProvider) { if (String.IsNullOrEmpty(_key)) { return NotFoundError; } ResourceManager resourceManager; var rootObjectProvider = GetService<IRootObjectProvider>(serviceProvider); if (rootObjectProvider != null && (resourceManager = ResourceHelper.GetResourceManager(rootObjectProvider.RootObject)) != null) { return resourceManager.GetString(_key) ?? _key; } return _key; } private static T GetService<T>(IServiceProvider serviceProvider) where T : class { return serviceProvider.GetService(typeof(T)) as T; } } }
mit
C#
3d980a08c90898d26ba63c3ac69aa71547c9c29b
Add failing cases
ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
osu.Framework.Tests/Input/KeyCombinationTest.cs
osu.Framework.Tests/Input/KeyCombinationTest.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.Input.Bindings; namespace osu.Framework.Tests.Input { [TestFixture] public class KeyCombinationTest { private static readonly object[][] key_combination_display_test_cases = { new object[] { new KeyCombination(InputKey.Alt, InputKey.F4), "Alt-F4" }, new object[] { new KeyCombination(InputKey.D, InputKey.Control), "Ctrl-D" }, new object[] { new KeyCombination(InputKey.Shift, InputKey.F, InputKey.Control), "Ctrl-Shift-F" }, new object[] { new KeyCombination(InputKey.Alt, InputKey.Control, InputKey.Super, InputKey.Shift), "Ctrl-Alt-Shift-Win" }, new object[] { new KeyCombination(InputKey.LAlt, InputKey.F4), "LAlt-F4" }, new object[] { new KeyCombination(InputKey.D, InputKey.LControl), "LCtrl-D" }, new object[] { new KeyCombination(InputKey.LShift, InputKey.F, InputKey.LControl), "LCtrl-LShift-F" }, new object[] { new KeyCombination(InputKey.LAlt, InputKey.LControl, InputKey.LSuper, InputKey.LShift), "LCtrl-LAlt-LShift-LWin" }, new object[] { new KeyCombination(InputKey.Alt, InputKey.LAlt, InputKey.RControl, InputKey.A), "RCtrl-LAlt-A" }, new object[] { new KeyCombination(InputKey.Shift, InputKey.LControl, InputKey.X), "LCtrl-Shift-X" }, new object[] { new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.Alt, InputKey.Super, InputKey.LAlt, InputKey.RShift, InputKey.LSuper), "Ctrl-LAlt-RShift-LWin" }, }; [TestCaseSource(nameof(key_combination_display_test_cases))] public void TestKeyCombinationDisplayOrder(KeyCombination keyCombination, string expectedRepresentation) => Assert.That(keyCombination.ReadableString(), Is.EqualTo(expectedRepresentation)); } }
// 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.Input.Bindings; namespace osu.Framework.Tests.Input { [TestFixture] public class KeyCombinationTest { private static readonly object[][] key_combination_display_test_cases = { new object[] { new KeyCombination(InputKey.Alt, InputKey.F4), "Alt-F4" }, new object[] { new KeyCombination(InputKey.D, InputKey.Control), "Ctrl-D" }, new object[] { new KeyCombination(InputKey.Shift, InputKey.F, InputKey.Control), "Ctrl-Shift-F" }, new object[] { new KeyCombination(InputKey.Alt, InputKey.Control, InputKey.Super, InputKey.Shift), "Ctrl-Alt-Shift-Win" }, new object[] { new KeyCombination(InputKey.LAlt, InputKey.F4), "LAlt-F4" }, new object[] { new KeyCombination(InputKey.D, InputKey.LControl), "LCtrl-D" }, new object[] { new KeyCombination(InputKey.LShift, InputKey.F, InputKey.LControl), "LCtrl-LShift-F" }, new object[] { new KeyCombination(InputKey.LAlt, InputKey.LControl, InputKey.LSuper, InputKey.LShift), "LCtrl-LAlt-LShift-LWin" } }; [TestCaseSource(nameof(key_combination_display_test_cases))] public void TestKeyCombinationDisplayOrder(KeyCombination keyCombination, string expectedRepresentation) => Assert.That(keyCombination.ReadableString(), Is.EqualTo(expectedRepresentation)); } }
mit
C#
f4bbe7aea6af0dacbc7322e86f8990e0a931736c
Fix bullet impact effect exception (#10357)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/Projectiles/ProjectileSystem.cs
Content.Client/Projectiles/ProjectileSystem.cs
using Content.Shared.Projectiles; using Content.Shared.Spawners.Components; using Content.Shared.Weapons.Ranged.Systems; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameStates; namespace Content.Client.Projectiles; public sealed class ProjectileSystem : SharedProjectileSystem { [Dependency] private readonly AnimationPlayerSystem _player = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ProjectileComponent, ComponentHandleState>(OnHandleState); SubscribeNetworkEvent<ImpactEffectEvent>(OnProjectileImpact); } private void OnProjectileImpact(ImpactEffectEvent ev) { if (Deleted(ev.Coordinates.EntityId)) return; var ent = Spawn(ev.Prototype, ev.Coordinates); if (TryComp<SpriteComponent>(ent, out var sprite)) { sprite[EffectLayers.Unshaded].AutoAnimated = false; sprite.LayerMapTryGet(EffectLayers.Unshaded, out var layer); var state = sprite.LayerGetState(layer); var lifetime = 0.5f; if (TryComp<TimedDespawnComponent>(ent, out var despawn)) lifetime = despawn.Lifetime; var anim = new Animation() { Length = TimeSpan.FromSeconds(lifetime), AnimationTracks = { new AnimationTrackSpriteFlick() { LayerKey = EffectLayers.Unshaded, KeyFrames = { new AnimationTrackSpriteFlick.KeyFrame(state.Name, 0f), } } } }; _player.Play(ent, anim, "impact-effect"); } } private void OnHandleState(EntityUid uid, ProjectileComponent component, ref ComponentHandleState args) { if (args.Current is not ProjectileComponentState state) return; component.Shooter = state.Shooter; component.IgnoreShooter = state.IgnoreShooter; } }
using Content.Shared.Projectiles; using Content.Shared.Spawners.Components; using Content.Shared.Weapons.Ranged.Systems; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameStates; namespace Content.Client.Projectiles; public sealed class ProjectileSystem : SharedProjectileSystem { [Dependency] private readonly AnimationPlayerSystem _player = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ProjectileComponent, ComponentHandleState>(OnHandleState); SubscribeNetworkEvent<ImpactEffectEvent>(OnProjectileImpact); } private void OnProjectileImpact(ImpactEffectEvent ev) { var ent = Spawn(ev.Prototype, ev.Coordinates); if (TryComp<SpriteComponent>(ent, out var sprite)) { sprite[EffectLayers.Unshaded].AutoAnimated = false; sprite.LayerMapTryGet(EffectLayers.Unshaded, out var layer); var state = sprite.LayerGetState(layer); var lifetime = 0.5f; if (TryComp<TimedDespawnComponent>(ent, out var despawn)) lifetime = despawn.Lifetime; var anim = new Animation() { Length = TimeSpan.FromSeconds(lifetime), AnimationTracks = { new AnimationTrackSpriteFlick() { LayerKey = EffectLayers.Unshaded, KeyFrames = { new AnimationTrackSpriteFlick.KeyFrame(state.Name, 0f), } } } }; _player.Play(ent, anim, "impact-effect"); } } private void OnHandleState(EntityUid uid, ProjectileComponent component, ref ComponentHandleState args) { if (args.Current is not ProjectileComponentState state) return; component.Shooter = state.Shooter; component.IgnoreShooter = state.IgnoreShooter; } }
mit
C#
48a4690c5e2a6eeec1beb5bbba8907053b023a10
Update version to 0.3.1
elcattivo/CloudFlareUtilities
CloudFlareUtilities/Properties/AssemblyInfo.cs
CloudFlareUtilities/Properties/AssemblyInfo.cs
using System; using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CloudFlare Utilities")] [assembly: AssemblyDescription("A .NET PCL to bypass Cloudflare's Anti-DDoS measure (JavaScript challenge) using a DelegatingHandler.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("El Cattivo")] [assembly: AssemblyProduct("CloudFlare Utilities")] [assembly: AssemblyCopyright("Copyright © El Cattivo 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("0.3.1.0")] [assembly: AssemblyFileVersion("0.3.1.0")] [assembly: AssemblyInformationalVersion("0.3.1-alpha")] [assembly:CLSCompliant(true)] [assembly:ComVisible(false)] [assembly: InternalsVisibleTo("CloudFlareUtilities.Tests")]
using System; using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CloudFlare Utilities")] [assembly: AssemblyDescription("A .NET PCL to bypass Cloudflare's Anti-DDoS measure (JavaScript challenge) using a DelegatingHandler.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("El Cattivo")] [assembly: AssemblyProduct("CloudFlare Utilities")] [assembly: AssemblyCopyright("Copyright © El Cattivo 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")] [assembly: AssemblyInformationalVersion("0.3.0-alpha")] [assembly:CLSCompliant(true)] [assembly:ComVisible(false)] [assembly: InternalsVisibleTo("CloudFlareUtilities.Tests")]
mit
C#
34957ef3c639f3e7a7df0f809781eca1ef34c25a
Delete TakeAndReset methods on IReporter
Abc-Arbitrage/Zebus
src/Abc.Zebus.Persistence/Reporter/IReporter.cs
src/Abc.Zebus.Persistence/Reporter/IReporter.cs
namespace Abc.Zebus.Persistence.Reporter { public interface IReporter { void AddReplaySpeedReport(ReplaySpeedReport replaySpeedReport); void AddStorageReport(StorageReport storageReport); } }
using System.Collections.Generic; namespace Abc.Zebus.Persistence.Reporter { public interface IReporter { void AddReplaySpeedReport(ReplaySpeedReport replaySpeedReport); IList<ReplaySpeedReport> TakeAndResetReplaySpeedReports(); void AddStorageReport(StorageReport storageReport); IList<StorageReport> TakeAndResetStorageReports(); } }
mit
C#
e055fa0c461e6b44a819912b65e1737a91a9caaf
Increment version
R-Smith/vmPing
vmPing/Properties/AssemblyInfo.cs
vmPing/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("vmPing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("vmPing")] [assembly: AssemblyCopyright("Copyright © 2019 Ryan Smith")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.2.0")] [assembly: AssemblyFileVersion("1.3.2.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("vmPing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("vmPing")] [assembly: AssemblyCopyright("Copyright © 2019 Ryan Smith")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.1.0")] [assembly: AssemblyFileVersion("1.3.1.0")]
mit
C#
244f8289c8501f16d306c156be724a831ac651d8
Update aspnet middleware extension message to allow shouldRun to be passed in
Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
src/Glimpse.Host.Web.AspNet/GlimpseExtension.cs
src/Glimpse.Host.Web.AspNet/GlimpseExtension.cs
 using Glimpse.Web; using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app, Func<IHttpContext, bool> shouldRun) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices, shouldRun).Invoke); } } }
 using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } } }
mit
C#
4c202c49e4d4c0e810ed9773fdb5836a76e5418e
Bump to version 0.2.0.
FacilityApi/Facility
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyVersion("0.1.9.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
mit
C#
b7c2609c03aff9683be3b2c614dad22df71cc499
Fix indentation on tests/WriteLine.cs.
xen2/SharpLang,xen2/SharpLang,xen2/SharpLang,xen2/SharpLang,xen2/SharpLang
src/SharpLang.Compiler.Tests/tests/WriteLine.cs
src/SharpLang.Compiler.Tests/tests/WriteLine.cs
public static class Program { public static void Main() { System.Console.WriteLine("Hello, World!"); } }
public static class Program { public static void Main() { System.Console.WriteLine("Hello, World!"); } }
bsd-2-clause
C#
80275eb68a998b6af832c97c1f7afdb998833a09
fix version display
MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4
host/Views/Home/Index.cshtml
host/Views/Home/Index.cshtml
@{ var version = typeof(IdentityServer4.Hosting.IdentityServerMiddleware).Assembly.GetName().Version.ToString(); } <div class="welcome-page"> <div class="row page-header"> <div class="col-sm-10"> <h1> <img class="icon" src="~/icon.jpg"> Welcome to IdentityServer4 <small>(build @version)</small> </h1> </div> </div> <div class="row"> <div class="col-sm-8"> <p> IdentityServer publishes a <a href="~/.well-known/openid-configuration">discovery document</a> where you can find metadata and links to all the endpoints, key material, etc. </p> </div> <div class="col-sm-8"> <p> Click <a href="~/grants">here</a> to manage your stored grants. </p> </div> </div> <div class="row"> <div class="col-sm-8"> <p> Here are links to the <a href="https://github.com/identityserver/IdentityServer4">source code repository</a>, and <a href="https://github.com/identityserver/IdentityServer4.Samples">ready to use samples</a>. </p> </div> </div> </div>
@{ var version = typeof(HomeController).Assembly.GetName().Version.ToString(); } <div class="welcome-page"> <div class="row page-header"> <div class="col-sm-10"> <h1> <img class="icon" src="~/icon.jpg"> Welcome to IdentityServer4 <small>(build @version)</small> </h1> </div> </div> <div class="row"> <div class="col-sm-8"> <p> IdentityServer publishes a <a href="~/.well-known/openid-configuration">discovery document</a> where you can find metadata and links to all the endpoints, key material, etc. </p> </div> <div class="col-sm-8"> <p> Click <a href="~/grants">here</a> to manage your stored grants. </p> </div> </div> <div class="row"> <div class="col-sm-8"> <p> Here are links to the <a href="https://github.com/identityserver/IdentityServer4">source code repository</a>, and <a href="https://github.com/identityserver/IdentityServer4.Samples">ready to use samples</a>. </p> </div> </div> </div>
apache-2.0
C#
43e7d4364f3393dbbabf6f24505521ecf858acc3
Fix typos in (doc)comments
ChugR/amqpnetlite,Azure/amqpnetlite
test/Common/TestTarget.cs
test/Common/TestTarget.cs
// ------------------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System; using Amqp; namespace Test.Amqp { /// <summary> /// For self tests that create AMQP connections to a broker /// define the URI of the broker and the name of the queue to use. /// /// The default broker on localhost may be overridden with /// environment variable AMQPNETLITE_TESTTARGET. A single URI /// specifies both the broker (scheme, user, password, host, porte /// and source or target (path) of the broker resource to be /// exercised by the self tests. /// </summary> public class TestTarget { internal const string envVarName = "AMQPNETLITE_TESTTARGET"; internal const string defaultAddress = "amqp://guest:guest@localhost:5672/q1"; internal string address; internal string path; public TestTarget() { #if !COMPACT_FRAMEWORK && !NETFX_CORE && !NETMF this.address = Environment.GetEnvironmentVariable(envVarName); #endif if (this.address == null) { this.address = defaultAddress; } // Verify that the URI is well formed. Address addr = new Address(this.address); // Extract the path without the leading "/". path = addr.Path.Substring(1); } public string Path { get { return path; } } public Address Address { get { return new Address(address); } } } }
// ------------------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System; using Amqp; namespace Test.Amqp { /// <summary> /// For self tests that create AMQP connections to a broker /// define the URI of the broker and the name of the queue to use. /// /// The default broker on localhost may be overridden with /// environment variable AMQPNETLITE_TESTTARGET. A single URI /// specifies both the broker (scheme, user, password, host, port) /// and source or target (path) of the broker resource to be /// exercised by the self tests. /// </summary> public class TestTarget { internal const string envVarName = "AMQPNETLITE_TESTTARGET"; internal const string defaultAddress = "amqp://guest:guest@localhost:5672/q1"; internal string address; internal string path; public TestTarget() { #if !COMPACT_FRAMEWORK && !NETFX_CORE && !NETMF this.address = Environment.GetEnvironmentVariable(envVarName); #endif if (this.address == null) { this.address = defaultAddress; } // Verify that the URI is well formed. Address addr = new Address(this.address); // Extract the path without the leading "/". path = addr.Path.Substring(1); } public string Path { get { return path; } } public Address Address { get { return new Address(address); } } } }
apache-2.0
C#
b7474470057ff6345bea6eb0649883b36d81ae65
Test harness update
ArasExtensions/Aras.Model
Aras.Model.Design.Debug/Program.cs
Aras.Model.Design.Debug/Program.cs
/* Aras.Model provides a .NET cient library for Aras Innovator Copyright (C) 2015 Processwall Limited. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://opensource.org/licenses/AGPL-3.0. Company: Processwall Limited Address: The Winnowing House, Mill Lane, Askham Richard, York, YO23 3NW, United Kingdom Tel: +44 113 815 3440 Email: support@processwall.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aras.Model; using System.IO; namespace Aras.Model.Design.Debug { class Program { static void Main(string[] args) { // Connect to Server Model.Server server = new Model.Server("http://localhost/InnovatorServer100SP4/"); //server.ProxyURL = "http://127.0.0.1:8888"; server.LoadAssembly("Aras.Model.Design"); server.LoadAssembly("Aras.ViewModel.Design"); Model.Database database = server.Database("CMB"); Model.Session session = database.Login("admin", Model.Server.PasswordHash("innovator")); session.ItemType("CAD").AddToSelect("native_file,viewable_file"); Model.Stores.Item<Model.Design.Order> store = new Model.Stores.Item<Model.Design.Order>(session, "v_Order", Aras.Conditions.Eq("item_number", "dja0504v1")); Model.Design.Order order = store.First(); foreach(Model.Design.OrderContext ordercontext in order.OrderContexts) { VariantContext variantcontext = ordercontext.VariantContext; String question = variantcontext.Question; String value = ordercontext.Value; Properties.VariableList valuelist = ordercontext.ValueList; List list = valuelist.Values; IEnumerable<ListValue> values = list.Values; ListValue test = values.First(); } using (Model.Transaction transaction = session.BeginTransaction()) { order.Update(transaction); order.UpdateBOM(); transaction.Commit(); } } } }
/* Aras.Model provides a .NET cient library for Aras Innovator Copyright (C) 2015 Processwall Limited. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://opensource.org/licenses/AGPL-3.0. Company: Processwall Limited Address: The Winnowing House, Mill Lane, Askham Richard, York, YO23 3NW, United Kingdom Tel: +44 113 815 3440 Email: support@processwall.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aras.Model; using System.IO; namespace Aras.Model.Design.Debug { class Program { static void Main(string[] args) { // Connect to Server Model.Server server = new Model.Server("http://localhost/InnovatorServer100SP4/"); //server.ProxyURL = "http://127.0.0.1:8888"; server.LoadAssembly("Aras.Model.Design"); server.LoadAssembly("Aras.ViewModel.Design"); Model.Database database = server.Database("CMB"); Model.Session session = database.Login("admin", Model.Server.PasswordHash("innovator")); session.ItemType("CAD").AddToSelect("native_file,viewable_file"); Model.Stores.Item<Model.Design.Order> store = new Model.Stores.Item<Model.Design.Order>(session, "v_Order", Aras.Conditions.Eq("item_number", "dja0504v1")); Model.Design.Order order = store.First(); foreach(Model.Design.OrderContext ordercontext in order.OrderContexts) { VariantContext variantcontext = ordercontext.VariantContext; String question = variantcontext.Question; String value = ordercontext.Value; } using (Model.Transaction transaction = session.BeginTransaction()) { order.Update(transaction); order.UpdateBOM(); transaction.Commit(); } } } }
apache-2.0
C#
1487d24be9866a2e58a5e427f937a5daa3edbdb6
Update assembly info
Yonom/BotBits
BotBits/Properties/AssemblyInfo.cs
BotBits/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("BotBits")] [assembly: AssemblyProduct("BotBits")] [assembly: Guid("fbac626f-42ca-4413-ba36-1263bb636cbf")] [assembly: AssemblyDescription("BotBits is a framework to help bot makers make bots faster.")] [assembly: AssemblyCopyright("Copyright © Simon Farshid 2017")] [assembly: AssemblyTrademark("BotBits")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if DEBUG [assembly: InternalsVisibleTo("BotBits.Tests")] #endif
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("BotBits.Core")] [assembly: AssemblyProduct("BotBits.Core")] [assembly: Guid("fbac626f-42ca-4413-ba36-1263bb636cbf")] [assembly: AssemblyDescription("BotBits is a framework to help bot makers make bots faster.")] [assembly: AssemblyCopyright("Copyright © Sepehr Farshid 2015")] [assembly: AssemblyTrademark("BotBits")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly:InternalsVisibleTo("BotBits.Tests")]
mit
C#
24492f42c5a8c7ca9d82165ddcf5df2df315c7fb
Add constructor overload to DeviceMemory
rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary
CSGL.Vulkan/Vulkan/DeviceMemory.cs
CSGL.Vulkan/Vulkan/DeviceMemory.cs
using System; namespace CSGL.Vulkan { public class MemoryAllocateInfo { public ulong allocationSize; public uint memoryTypeIndex; } public class DeviceMemory : IDisposable, INative<VkDeviceMemory> { VkDeviceMemory deviceMemory; bool disposed = false; public Device Device { get; private set; } public VkDeviceMemory Native { get { return deviceMemory; } } public ulong Size { get; private set; } public DeviceMemory(Device device, MemoryAllocateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; CreateDeviceMemory(info.allocationSize, info.memoryTypeIndex); } public DeviceMemory(Device device, ulong allocationSize, uint memoryTypeIndex) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; CreateDeviceMemory(allocationSize, memoryTypeIndex); } void CreateDeviceMemory(ulong allocationSize, uint memoryTypeIndex) { var info = new VkMemoryAllocateInfo(); info.sType = VkStructureType.MemoryAllocateInfo; info.allocationSize = allocationSize; info.memoryTypeIndex = memoryTypeIndex; Device.Commands.allocateMemory(Device.Native, ref info, Device.Instance.AllocationCallbacks, out deviceMemory); Size = info.allocationSize; } public IntPtr Map(ulong offset, ulong size, VkMemoryMapFlags flags) { IntPtr data; var result = Device.Commands.mapMemory(Device.Native, deviceMemory, offset, size, flags, out data); if (result != VkResult.Success) throw new DeviceMemoryException(string.Format("Error mapping memory: {0}", result)); return data; } public void Unmap() { Device.Commands.unmapMemory(Device.Native, deviceMemory); } public void Dispose() { if (disposed) return; Device.Commands.freeMemory(Device.Native, deviceMemory, Device.Instance.AllocationCallbacks); disposed = true; } } public class DeviceMemoryException : Exception { public DeviceMemoryException(string message) : base(message) { } } }
using System; namespace CSGL.Vulkan { public class MemoryAllocateInfo { public ulong allocationSize; public uint memoryTypeIndex; } public class DeviceMemory : IDisposable, INative<VkDeviceMemory> { VkDeviceMemory deviceMemory; bool disposed = false; public Device Device { get; private set; } public VkDeviceMemory Native { get { return deviceMemory; } } public ulong Size { get; private set; } public DeviceMemory(Device device, MemoryAllocateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; Size = info.allocationSize; CreateDeviceMemory(info); } void CreateDeviceMemory(MemoryAllocateInfo mInfo) { var info = new VkMemoryAllocateInfo(); info.sType = VkStructureType.MemoryAllocateInfo; info.allocationSize = mInfo.allocationSize; info.memoryTypeIndex = mInfo.memoryTypeIndex; Device.Commands.allocateMemory(Device.Native, ref info, Device.Instance.AllocationCallbacks, out deviceMemory); } public IntPtr Map(ulong offset, ulong size, VkMemoryMapFlags flags) { IntPtr data; var result = Device.Commands.mapMemory(Device.Native, deviceMemory, offset, size, flags, out data); if (result != VkResult.Success) throw new DeviceMemoryException(string.Format("Error mapping memory: {0}", result)); return data; } public void Unmap() { Device.Commands.unmapMemory(Device.Native, deviceMemory); } public void Dispose() { if (disposed) return; Device.Commands.freeMemory(Device.Native, deviceMemory, Device.Instance.AllocationCallbacks); disposed = true; } } public class DeviceMemoryException : Exception { public DeviceMemoryException(string message) : base(message) { } } }
mit
C#
a240e67f19d0ab342a3e2260fa261708df659dae
Remove DefaultSettings as public API.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/IconClasses.cs
source/Nuke.Common/IconClasses.cs
// Copyright Matthias Koch 2018. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common; using Nuke.Common.ChangeLog; using Nuke.Common.Git; using Nuke.Common.Gitter; using Nuke.Common.Tools.CoverallsNet; using Nuke.Common.Tools.DocFx; using Nuke.Common.Tools.DotCover; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.DupFinder; using Nuke.Common.Tools.Git; using Nuke.Common.Tools.GitLink; using Nuke.Common.Tools.GitReleaseManager; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.InspectCode; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.Npm; using Nuke.Common.Tools.NuGet; using Nuke.Common.Tools.Nunit; using Nuke.Common.Tools.Octopus; using Nuke.Common.Tools.OpenCover; using Nuke.Common.Tools.Paket; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Tools.SignTool; using Nuke.Common.Tools.TestCloud; using Nuke.Common.Tools.VsTest; using Nuke.Common.Tools.WebConfigTransformRunner; using Nuke.Common.Tools.Xunit; using Nuke.Core.Execution; [assembly: IconClass(typeof(ChangelogTasks), "books")] [assembly: IconClass(typeof(CoverallsNetTasks), "pie-chart4")] [assembly: IconClass(typeof(DocFxTasks), "books")] [assembly: IconClass(typeof(DotCoverTasks), "shield2")] [assembly: IconClass(typeof(DotNetTasks), "fire")] [assembly: IconClass(typeof(DupFinderTasks), "code")] [assembly: IconClass(typeof(GitTasks), "git")] [assembly: IconClass(typeof(GitLinkTasks), "link")] [assembly: IconClass(typeof(GitReleaseManagerTasks), "books")] [assembly: IconClass(typeof(GitRepository), "git")] [assembly: IconClass(typeof(GitterTasks), "bubbles")] [assembly: IconClass(typeof(GitVersionTasks), "podium")] [assembly: IconClass(typeof(InspectCodeTasks), "code")] [assembly: IconClass(typeof(MSBuildTasks), "sword")] [assembly: IconClass(typeof(NpmTasks), "box")] [assembly: IconClass(typeof(NuGetTasks), "box")] [assembly: IconClass(typeof(NunitTasks), "bug2")] [assembly: IconClass(typeof(OctopusTasks), "cloud-upload")] [assembly: IconClass(typeof(OpenCoverTasks), "shield2")] [assembly: IconClass(typeof(PaketTasks), "box")] [assembly: IconClass(typeof(ReportGeneratorTasks), "pie-chart4")] [assembly: IconClass(typeof(SignToolTasks), "key")] [assembly: IconClass(typeof(TestCloudTasks), "bug2")] [assembly: IconClass(typeof(VsTestTasks), "bug2")] [assembly: IconClass(typeof(WebConfigTransformRunnerTasks), "file-empty2")] [assembly: IconClass(typeof(XunitTasks), "bug2")]
// Copyright Matthias Koch 2018. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common; using Nuke.Common.ChangeLog; using Nuke.Common.Git; using Nuke.Common.Gitter; using Nuke.Common.Tools.CoverallsNet; using Nuke.Common.Tools.DocFx; using Nuke.Common.Tools.DotCover; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.DupFinder; using Nuke.Common.Tools.Git; using Nuke.Common.Tools.GitLink; using Nuke.Common.Tools.GitReleaseManager; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.InspectCode; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.Npm; using Nuke.Common.Tools.NuGet; using Nuke.Common.Tools.Nunit; using Nuke.Common.Tools.Octopus; using Nuke.Common.Tools.OpenCover; using Nuke.Common.Tools.Paket; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Tools.SignTool; using Nuke.Common.Tools.TestCloud; using Nuke.Common.Tools.VsTest; using Nuke.Common.Tools.WebConfigTransformRunner; using Nuke.Common.Tools.Xunit; using Nuke.Core.Execution; [assembly: IconClass(typeof(ChangelogTasks), "books")] [assembly: IconClass(typeof(CoverallsNetTasks), "pie-chart4")] [assembly: IconClass(typeof(DefaultSettings), "equalizer")] [assembly: IconClass(typeof(DocFxTasks), "books")] [assembly: IconClass(typeof(DotCoverTasks), "shield2")] [assembly: IconClass(typeof(DotNetTasks), "fire")] [assembly: IconClass(typeof(DupFinderTasks), "code")] [assembly: IconClass(typeof(GitTasks), "git")] [assembly: IconClass(typeof(GitLinkTasks), "link")] [assembly: IconClass(typeof(GitReleaseManagerTasks), "books")] [assembly: IconClass(typeof(GitRepository), "git")] [assembly: IconClass(typeof(GitterTasks), "bubbles")] [assembly: IconClass(typeof(GitVersionTasks), "podium")] [assembly: IconClass(typeof(InspectCodeTasks), "code")] [assembly: IconClass(typeof(MSBuildTasks), "sword")] [assembly: IconClass(typeof(NpmTasks), "box")] [assembly: IconClass(typeof(NuGetTasks), "box")] [assembly: IconClass(typeof(NunitTasks), "bug2")] [assembly: IconClass(typeof(OctopusTasks), "cloud-upload")] [assembly: IconClass(typeof(OpenCoverTasks), "shield2")] [assembly: IconClass(typeof(PaketTasks), "box")] [assembly: IconClass(typeof(ReportGeneratorTasks), "pie-chart4")] [assembly: IconClass(typeof(SignToolTasks), "key")] [assembly: IconClass(typeof(TestCloudTasks), "bug2")] [assembly: IconClass(typeof(VsTestTasks), "bug2")] [assembly: IconClass(typeof(WebConfigTransformRunnerTasks), "file-empty2")] [assembly: IconClass(typeof(XunitTasks), "bug2")]
mit
C#
0e99f212146096d953d93a7f9230888055e3b3ac
Make sure test fails more often if locks are removed
RogerKratz/mbcache
MbCacheTest/Logic/Concurrency/SimultaneousCachePutTest.cs
MbCacheTest/Logic/Concurrency/SimultaneousCachePutTest.cs
using System; using System.Threading; using MbCacheTest.TestData; using NUnit.Framework; using SharpTestsEx; namespace MbCacheTest.Logic.Concurrency { public class SimultaneousCachePutTest : TestCase { public SimultaneousCachePutTest(Type proxyType) : base(proxyType) { } [Test] public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 1000.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); } } }
using System; using System.Threading; using MbCacheTest.TestData; using NUnit.Framework; using SharpTestsEx; namespace MbCacheTest.Logic.Concurrency { public class SimultaneousCachePutTest : TestCase { public SimultaneousCachePutTest(Type proxyType) : base(proxyType) { } [Test] public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 10.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); } } }
mit
C#
48ff2159cd9e9e6940f36061fe9080fd72cfc7f7
Add scene list getter.
Chaser324/unity-build
Editor/Build/Settings/SceneList.cs
Editor/Build/Settings/SceneList.cs
using System.Collections.Generic; using UnityEditor; namespace SuperSystems.UnityBuild { [System.Serializable] public class SceneList { public List<Scene> enabledScenes = new List<Scene>(); public SceneList() { } public void Refresh() { EditorBuildSettingsScene[] allScenes = EditorBuildSettings.scenes; // Verify that all scenes in list still exist. for (int i = 0; i < enabledScenes.Count; i++) { string sceneName = enabledScenes[i].filePath; bool sceneExists = false; for (int j = 0; j < allScenes.Length; j++) { if (string.Equals(sceneName, allScenes[j])) { sceneExists = true; break; } } if (!sceneExists) { enabledScenes.RemoveAt(i); --i; } } } public string[] GetSceneList() { List<string> scenes = new List<string>(); for (int i = 0; i < enabledScenes.Count; i++) { scenes.Add(enabledScenes[i].filePath); } return scenes.ToArray(); } [System.Serializable] public class Scene { public string filePath = string.Empty; } } }
using System.Collections.Generic; using UnityEditor; namespace SuperSystems.UnityBuild { [System.Serializable] public class SceneList { public List<Scene> enabledScenes = new List<Scene>(); public SceneList() { } public void Refresh() { EditorBuildSettingsScene[] allScenes = EditorBuildSettings.scenes; // Verify that all scenes in list still exist. for (int i = 0; i < enabledScenes.Count; i++) { string sceneName = enabledScenes[i].filePath; bool sceneExists = false; for (int j = 0; j < allScenes.Length; j++) { if (string.Equals(sceneName, allScenes[j])) { sceneExists = true; break; } } if (!sceneExists) { enabledScenes.RemoveAt(i); --i; } } } [System.Serializable] public class Scene { public string filePath = string.Empty; } } }
mit
C#
fc1223d5cc37c027636a753c957c68674ef6558d
Bump version to 2.0.0
mj1856/SimpleImpersonation
SimpleImpersonation/Properties/AssemblyInfo.cs
SimpleImpersonation/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("SimpleImpersonation")] [assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")] [assembly: AssemblyCompany("Matt Johnson")] [assembly: AssemblyProduct("Simple Impersonation")] [assembly: AssemblyCopyright("Copyright © Matt Johnson")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("SimpleImpersonation")] [assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")] [assembly: AssemblyCompany("Matt Johnson")] [assembly: AssemblyProduct("Simple Impersonation")] [assembly: AssemblyCopyright("Copyright © Matt Johnson")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.*")] [assembly: AssemblyInformationalVersion("1.1.0")]
mit
C#
70156dc89110171a3c17f06798e6c1c71f58e38e
Use explict Options
bradyholt/cron-expression-descriptor,bradyholt/cron-expression-descriptor
demo/controllers/DescriptorController.cs
demo/controllers/DescriptorController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace CronExpressionDescriptor.Demo.Controllers { [Route("api/[controller]")] public class DescriptorController : Controller { [HttpGet] public JsonResult Get(string expression, string locale) { var result = ExpressionDescriptor.GetDescription(expression, new Options() { ThrowExceptionOnParseError = false, Verbose = false, DayOfWeekStartIndexZero = true, Locale = (locale ?? "en-US") }); return Json(new { description = result }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace CronExpressionDescriptor.Demo.Controllers { [Route("api/[controller]")] public class DescriptorController : Controller { [HttpGet] public JsonResult Get(string expression, string locale) { var result = ExpressionDescriptor.GetDescription(expression, new Options() { ThrowExceptionOnParseError = false, Locale = (locale ?? "en-US") }); return Json(new { description = result }); } } }
mit
C#