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 |
|---|---|---|---|---|---|---|---|---|
4279da2437e8b17330c17f5200e972135f0b4361
|
Update default API connection address
|
patchkit-net/patchkit-library-dotnet,patchkit-net/patchkit-library-dotnet
|
src/PatchKit.Api/ApiConnectionSettings.cs
|
src/PatchKit.Api/ApiConnectionSettings.cs
|
using System;
using JetBrains.Annotations;
namespace PatchKit.Api
{
/// <summary>
/// <see cref="ApiConnection" /> settings.
/// </summary>
[Serializable]
public struct ApiConnectionSettings
{
/// <summary>
/// Returns default settings.
/// </summary>
public static ApiConnectionSettings CreateDefault()
{
return new ApiConnectionSettings
{
MainServer = "api.patchkit.net",
CacheServers =
new[]
{
"api-cache-node-1.patchkit.net:43230", "api-cache-node-2.patchkit.net:43230",
"api-cache-node-3.patchkit.net:43230"
},
Timeout = 5000
};
}
/// <summary>
/// Url to main API server.
/// </summary>
[NotNull] public string MainServer;
/// <summary>
/// Urls for cache API servers. Priority of servers is based on the array order.
/// </summary>
[CanBeNull] public string[] CacheServers;
/// <summary>
/// Timeout for connection with one server.
/// </summary>
public int Timeout;
/// <summary>
/// Total timeout of request - <see cref="Timeout"/> multipled by amount of servers (including main server).
/// </summary>
public int TotalTimeout
{
get
{
if (CacheServers == null)
{
return Timeout;
}
return Timeout*(1 + CacheServers.Length);
}
}
}
}
|
using System;
using JetBrains.Annotations;
namespace PatchKit.Api
{
/// <summary>
/// <see cref="ApiConnection" /> settings.
/// </summary>
[Serializable]
public struct ApiConnectionSettings
{
/// <summary>
/// Returns default settings.
/// </summary>
public static ApiConnectionSettings CreateDefault()
{
return new ApiConnectionSettings
{
MainServer = "http://api.patchkit.net",
CacheServers =
new[]
{
"api-cache-node-1.patchkit.net:43230", "api-cache-node-2.patchkit.net:43230",
"api-cache-node-3.patchkit.net:43230"
},
Timeout = 5000
};
}
/// <summary>
/// Url to main API server.
/// </summary>
[NotNull] public string MainServer;
/// <summary>
/// Urls for cache API servers. Priority of servers is based on the array order.
/// </summary>
[CanBeNull] public string[] CacheServers;
/// <summary>
/// Timeout for connection with one server.
/// </summary>
public int Timeout;
/// <summary>
/// Total timeout of request - <see cref="Timeout"/> multipled by amount of servers (including main server).
/// </summary>
public int TotalTimeout
{
get
{
if (CacheServers == null)
{
return Timeout;
}
return Timeout*(1 + CacheServers.Length);
}
}
}
}
|
mit
|
C#
|
1a82c8a82b1d8abaef4d56fc2476dcf38aad5cfe
|
Fix assembly name
|
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
|
IntegrationEngine.Model.net40/Properties/AssemblyInfo.cs
|
IntegrationEngine.Model.net40/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("IntegrationEngine.Model.net40")]
// 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("9e42b9d5-8f4b-4fa8-9877-c9994ce2e5ea")]
|
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("IntegrationEngine.Model.Net4")]
// 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("9e42b9d5-8f4b-4fa8-9877-c9994ce2e5ea")]
|
mit
|
C#
|
91c4a904147fce101b3228f391259d30dd880b6e
|
Add body name to some POI progress nodes
|
DMagic1/KSP_Contract_Window
|
Source/ContractsWindow/PanelInterfaces/StandardNodeUI.cs
|
Source/ContractsWindow/PanelInterfaces/StandardNodeUI.cs
|
#region license
/*The MIT License (MIT)
StandardNodeUI - Storage class for information about standard progress nodes
Copyright (c) 2016 DMagic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using KSPAchievements;
using ContractsWindow.Unity.Interfaces;
using ProgressParser;
using UnityEngine;
namespace ContractsWindow.PanelInterfaces
{
public class StandardNodeUI : IStandardNode
{
private progressStandard node;
public StandardNodeUI(progressStandard n)
{
if (n == null)
return;
node = n;
}
public bool IsComplete
{
get
{
if (node == null)
return false;
return node.IsComplete;
}
}
public string GetNote
{
get
{
if (node == null)
return "";
return string.Format(node.Note, node.NoteReference, node.KSPDateString);
}
}
public string NodeText
{
get
{
if (node == null)
return "";
string body = node.Body == null ? (node.PType == FinePrint.Utilities.ProgressType.POINTOFINTEREST ? node.BodyName : "") : node.Body.theName;
return string.Format(node.Descriptor, body);
}
}
private string coloredText(string s, string sprite, string color)
{
if (string.IsNullOrEmpty(s))
return "";
return string.Format("<color={0}>{1}{2}</color> ", color, sprite, s);
}
public string RewardText
{
get
{
if (node == null)
return "";
return string.Format("{0}{1}{2}", coloredText(node.FundsRewardString, "<sprite=2 tint=1>", "#69D84FFF"), coloredText(node.SciRewardString, "<sprite=1 tint=1>", "#02D8E9FF"), coloredText(node.RepRewardString, "<sprite=0 tint=1>", "#C9B003FF"));
}
}
}
}
|
#region license
/*The MIT License (MIT)
StandardNodeUI - Storage class for information about standard progress nodes
Copyright (c) 2016 DMagic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using ContractsWindow.Unity.Interfaces;
using ProgressParser;
using UnityEngine;
namespace ContractsWindow.PanelInterfaces
{
public class StandardNodeUI : IStandardNode
{
private progressStandard node;
public StandardNodeUI(progressStandard n)
{
if (n == null)
return;
node = n;
}
public bool IsComplete
{
get
{
if (node == null)
return false;
return node.IsComplete;
}
}
public string GetNote
{
get
{
if (node == null)
return "";
return string.Format(node.Note, node.NoteReference, node.KSPDateString);
}
}
public string NodeText
{
get
{
if (node == null)
return "";
string body = node.Body == null ? "" : node.Body.theName;
return string.Format(node.Descriptor, body);
}
}
private string coloredText(string s, string sprite, string color)
{
if (string.IsNullOrEmpty(s))
return "";
return string.Format("<color={0}>{1}{2}</color> ", color, sprite, s);
}
public string RewardText
{
get
{
if (node == null)
return "";
return string.Format("{0}{1}{2}", coloredText(node.FundsRewardString, "<sprite=2 tint=1>", "#69D84FFF"), coloredText(node.SciRewardString, "<sprite=1 tint=1>", "#02D8E9FF"), coloredText(node.RepRewardString, "<sprite=0 tint=1>", "#C9B003FF"));
}
}
}
}
|
mit
|
C#
|
54b8ae38fdc38822100a83b7162110cc8bda9a88
|
Update Feature1.cs
|
jacobrossandersen/GitTest1
|
ConsoleApp1/ConsoleApp1/Feature1.cs
|
ConsoleApp1/ConsoleApp1/Feature1.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Feature1
{
public int Add()
{
var x1 = 1;
var x2 = 2;
var sum = x1 + x2;
return sum;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Feature1
{
public int Add()
{
int x1 = 1;
int x2 = 2;
int sum = x1 + x2;
return sum;
}
}
}
|
mit
|
C#
|
6d1bec6347d5ce3d0f9b075e01e628af48d18ad9
|
Bump version to 15.0.0.32708
|
HearthSim/HearthDb
|
HearthDb/Properties/AssemblyInfo.cs
|
HearthDb/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("15.0.0.32708")]
[assembly: AssemblyFileVersion("15.0.0.32708")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("14.6.0.31761")]
[assembly: AssemblyFileVersion("14.6.0.31761")]
|
mit
|
C#
|
0d378711a83c65738963593a69996946177101ba
|
update default interval
|
jonfreeland/Log4Netly
|
Log4Netly/BufferedLogglyAppender.cs
|
Log4Netly/BufferedLogglyAppender.cs
|
using System.Threading;
using log4net.Appender;
using log4net.Core;
namespace Log4Netly
{
public class BufferedLogglyAppender : BufferingAppenderSkeleton
{
private string _url;
private const int DefaultIntervalInMs = 2500;
private readonly object _isCurrentlySendingLockObject = new object();
private readonly LoggingEventSerializer _serializer = new LoggingEventSerializer();
private readonly AsyncHttpClientWrapper _client = new AsyncHttpClientWrapper();
private readonly EndpointFactory _endpointFactory = new EndpointFactory();
/// <summary>
/// Loggly host for submitting log events.
/// </summary>
public string Endpoint { get; set; }
/// <summary>
/// Loggly customer token.
/// https://www.loggly.com/docs/customer-token-authentication-token/
/// </summary>
public string Token { get; set; }
/// <summary>
/// Comma-delimited list of tags to add to each log event.
/// https://www.loggly.com/docs/tags/
/// </summary>
public string Tags { get; set; }
public int IntervalInMs { get; set; }
public override void ActivateOptions()
{
var intervalInMs = IntervalInMs > 0 ? IntervalInMs : DefaultIntervalInMs;
new TimerScheduler(intervalInMs).Execute(ProcessBufferedMessages);
_url = _endpointFactory.BuildBulkEndpoint(Endpoint, Token, Tags);
Evaluator = new LevelEvaluator(Level.Fatal);
base.ActivateOptions();
}
private void ProcessBufferedMessages()
{
if (Monitor.TryEnter(_isCurrentlySendingLockObject))
{
try
{
Flush();
}
finally
{
Monitor.Exit(_isCurrentlySendingLockObject);
}
}
}
protected override void SendBuffer(LoggingEvent[] loggingEvent)
{
var content = _serializer.SerializeLoggingEvents(loggingEvent);
_client.Post(_url, content);
}
}
}
|
using System;
using System.Threading;
using log4net.Appender;
using log4net.Core;
namespace Log4Netly
{
public class BufferedLogglyAppender : BufferingAppenderSkeleton
{
private string _url;
private const int DefaultIntervalInMs = 1000;
private readonly object _isCurrentlySendingLockObject = new object();
private readonly LoggingEventSerializer _serializer = new LoggingEventSerializer();
private readonly AsyncHttpClientWrapper _client = new AsyncHttpClientWrapper();
private readonly EndpointFactory _endpointFactory = new EndpointFactory();
/// <summary>
/// Loggly host for submitting log events.
/// </summary>
public string Endpoint { get; set; }
/// <summary>
/// Loggly customer token.
/// https://www.loggly.com/docs/customer-token-authentication-token/
/// </summary>
public string Token { get; set; }
/// <summary>
/// Comma-delimited list of tags to add to each log event.
/// https://www.loggly.com/docs/tags/
/// </summary>
public string Tags { get; set; }
public int IntervalInMs { get; set; }
public override void ActivateOptions()
{
var intervalInMs = IntervalInMs > 0 ? IntervalInMs : DefaultIntervalInMs;
new TimerScheduler(intervalInMs).Execute(ProcessBufferedMessages);
_url = _endpointFactory.BuildBulkEndpoint(Endpoint, Token, Tags);
Evaluator = new LevelEvaluator(Level.Fatal);
base.ActivateOptions();
}
private void ProcessBufferedMessages()
{
if (Monitor.TryEnter(_isCurrentlySendingLockObject))
{
try
{
Flush();
}
finally
{
Monitor.Exit(_isCurrentlySendingLockObject);
}
}
}
protected override void SendBuffer(LoggingEvent[] loggingEvent)
{
var content = _serializer.SerializeLoggingEvents(loggingEvent);
_client.Post(_url, content);
}
}
}
|
mit
|
C#
|
5ed63b20fc50f98d5c9dbb0cefc93384c199a31b
|
update version
|
davidbetz/nalarium
|
Nalarium/Properties/AssemblyInfo.cs
|
Nalarium/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("Nalarium")]
[assembly: AssemblyDescription(".NET Development Foundation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("David Betz")]
[assembly: AssemblyProduct("Nalarium")]
[assembly: AssemblyCopyright("Copyright © David Betz 2007-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//+
[assembly: ComVisible(false)]
//+
[assembly: Guid("6E249E3E-95D3-416C-B9DD-544B08255E43")]
//+
[assembly: AssemblyVersion("3.6.0.0")]
[assembly: AssemblyFileVersion("3.6.0.0")]
//+
namespace Nalarium.Properties
{
[NotDocumented]
public class AssemblyInfo
{
internal static Assembly _Assembly = typeof (AssemblyInfo).Assembly;
//+
public static string AssemblyName = _Assembly.FullName;
public static byte[] PublicKey = _Assembly.GetName().GetPublicKey();
public static string PublicKeyString = Encoding.UTF8.GetString(PublicKey).ToLower();
}
}
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("Nalarium")]
[assembly: AssemblyDescription(".NET Development Foundation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("David Betz")]
[assembly: AssemblyProduct("Nalarium")]
[assembly: AssemblyCopyright("Copyright © David Betz 2007-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//+
[assembly: ComVisible(false)]
//+
[assembly: Guid("6E249E3E-95D3-416C-B9DD-544B08255E43")]
//+
[assembly: AssemblyVersion("3.5.13.0")]
[assembly: AssemblyFileVersion("3.5.13.0")]
//+
namespace Nalarium.Properties
{
[NotDocumented]
public class AssemblyInfo
{
internal static Assembly _Assembly = typeof (AssemblyInfo).Assembly;
//+
public static string AssemblyName = _Assembly.FullName;
public static byte[] PublicKey = _Assembly.GetName().GetPublicKey();
public static string PublicKeyString = Encoding.UTF8.GetString(PublicKey).ToLower();
}
}
|
bsd-3-clause
|
C#
|
863212a0b02bde535e8db9dd90474de329256a59
|
Bump version to 2.1.0.0
|
bobus15/proshine,MeltWS/proshine,Silv3rPRO/proshine
|
PROShine/Properties/AssemblyInfo.cs
|
PROShine/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
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("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[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("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: NeutralResourcesLanguage("en")]
|
using System.Reflection;
using System.Resources;
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("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[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("2.0.2.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
[assembly: NeutralResourcesLanguage("en")]
|
mit
|
C#
|
743944a3d500bbe10c40cffa29d86c7bcac247b5
|
Prueba de CI
|
JuanQuijanoAbad/UniversalSync,JuanQuijanoAbad/UniversalSync
|
Storage/Azure/StorageAzure/Blob.cs
|
Storage/Azure/StorageAzure/Blob.cs
|
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage.Blob;
using StorageAzure.Interface;
using System;
using System.IO;
namespace StorageAzure
{
public class Blob : ICloudRepository
{
private CloudBlobContainer _blobContainer { get; }
public Blob(IAzureConfig config)
{
_blobContainer = new BlobContanier(config).Create();
}
public bool Put(FileStream objeto)
{
var resultado = false;
try
{
var fichero = Path.GetFileName(objeto.Name);
var blob = _blobContainer.GetBlockBlobReference(fichero);
blob.UploadFromStream(objeto);
resultado = true;
}
catch (Exception)
{
throw;
}
return resultado;
}
public Boolean Delete(string fileName)
{
var blob = _blobContainer.GetBlockBlobReference(fileName);
return blob.DeleteIfExists();
}
public Stream Get(string fileName)
{
Stream file = new MemoryStream();
var blob = _blobContainer.GetBlockBlobReference(fileName);
blob.DownloadToStream(file);
return file;
}
}
}
|
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage.Blob;
using StorageAzure.Interface;
using System;
using System.IO;
namespace StorageAzure
{
public class Blob: ICloudRepository
{
private CloudBlobContainer _blobContainer { get; }
public Blob(IAzureConfig config)
{
_blobContainer = new BlobContanier(config).Create();
}
public bool Put(FileStream objeto)
{
var resultado = false;
try
{
var fichero = Path.GetFileName(objeto.Name);
var blob = _blobContainer.GetBlockBlobReference(fichero);
blob.UploadFromStream(objeto);
resultado = true;
}
catch (Exception)
{
throw;
}
return resultado;
}
public Boolean Delete(string fileName)
{
var blob = _blobContainer.GetBlockBlobReference(fileName);
return blob.DeleteIfExists();
}
public Stream Get(string fileName)
{
Stream file = new MemoryStream();
var blob = _blobContainer.GetBlockBlobReference(fileName);
blob.DownloadToStream(file);
return file;
}
}
}
|
mit
|
C#
|
ffcdb8c6f51aa739a3a9ab1bd6a2065441d46cee
|
fix define
|
corvusalba/my-little-lispy,corvusalba/my-little-lispy
|
src/CorvusAlba.MyLittleLispy.Runtime/Closure.cs
|
src/CorvusAlba.MyLittleLispy.Runtime/Closure.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace CorvusAlba.MyLittleLispy.Runtime
{
public class Closure : Value
{
public IEnumerable<Scope> Scopes { get; private set; }
public bool IsTailCall { get; set; }
public bool HasRestArg { get; private set; }
public Closure(string[] args, Node body, bool isTailCall = false)
{
Args = args;
Body = body;
IsTailCall = isTailCall;
if (Args == null)
{
Args = new string[] { };
return;
}
// TODO optimisation
if (Args.Any(a => a == "."))
{
HasRestArg = true;
Args = Args.Where(a => a != ".").ToArray();
}
}
public Closure(Context context, Node args, Node body, bool isTailCall = false)
{
Body = body;
Scopes = context.CurrentFrame.Export();
IsTailCall = isTailCall;
if (args == null)
{
Args = new string[] { };
return;
}
var argsExpression = args as Expression;
if (argsExpression == null)
{
HasRestArg = true;
Args = new[] { args.Quote(context).To<string>() };
return;
}
Args = args.Quote(context).To<IEnumerable<Value>>().Select(v => v.To<string>()).ToArray();
// TODO optimisation
if (Args.Any(a => a == "."))
{
HasRestArg = true;
Args = Args.Where(a => a != ".").ToArray();
}
}
public string[] Args { get; private set; }
public Node Body { get; private set; }
public override Node ToExpression()
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace CorvusAlba.MyLittleLispy.Runtime
{
public class Closure : Value
{
public IEnumerable<Scope> Scopes { get; private set; }
public bool IsTailCall { get; set; }
public bool HasRestArg { get; private set; }
public Closure(string[] args, Node body, bool isTailCall = false)
{
Args = args ?? new string[0];
Body = body;
IsTailCall = isTailCall;
}
public Closure(Context context, Node args, Node body, bool isTailCall = false)
{
Body = body;
Scopes = context.CurrentFrame.Export();
IsTailCall = isTailCall;
DetermineArgs(context, args);
}
private void DetermineArgs(Context context, Node args)
{
if (args == null)
{
Args = new string[] { };
return;
}
var argsExpression = args as Expression;
if (argsExpression == null)
{
HasRestArg = true;
Args = new[] { args.Quote(context).To<string>() };
return;
}
Args = args.Quote(context).To<IEnumerable<Value>>().Select(v => v.To<string>()).ToArray();
// TODO optimisation
if (Args.Any(a => a == "."))
{
HasRestArg = true;
Args = Args.Where(a => a != ".").ToArray();
}
}
public string[] Args { get; private set; }
public Node Body { get; private set; }
public override Node ToExpression()
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
ce9b10329ed73c152008193666d9099b07870604
|
Bump version to 4.1.1
|
blackmamba97/Transformer-Toolkit
|
Toolkit/Properties/AssemblyInfo.cs
|
Toolkit/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Transformer Toolkit")]
[assembly: AssemblyDescription("A toolkit for the TF700T, TF300T, ME301T and the N5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Max Röhrl")]
[assembly: AssemblyProduct("Transformer Toolkit")]
[assembly: AssemblyCopyright("Copyright © Max Röhrl 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("873db6df-3368-406b-bc7b-08efa89658ca")]
// 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("4.1.1")]
[assembly: AssemblyFileVersion("4.1.1")]
[assembly: NeutralResourcesLanguage("en")]
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Transformer Toolkit")]
[assembly: AssemblyDescription("A toolkit for the TF700T, TF300T, ME301T and the N5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Max Röhrl")]
[assembly: AssemblyProduct("Transformer Toolkit")]
[assembly: AssemblyCopyright("Copyright © Max Röhrl 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("873db6df-3368-406b-bc7b-08efa89658ca")]
// 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("4.1.0")]
[assembly: AssemblyFileVersion("4.1.0")]
[assembly: NeutralResourcesLanguage("en")]
|
mit
|
C#
|
efa81ae022b35936f91562970e0cf90f95e98bdf
|
Bump version to 4.1.0
|
blackmamba97/Transformer-Toolkit
|
Toolkit/Properties/AssemblyInfo.cs
|
Toolkit/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Transformer Toolkit")]
[assembly: AssemblyDescription("A toolkit for the TF700T, TF300T, ME301T and the N5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Max Röhrl")]
[assembly: AssemblyProduct("Transformer Toolkit")]
[assembly: AssemblyCopyright("Copyright © Max Röhrl 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("873db6df-3368-406b-bc7b-08efa89658ca")]
// 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("4.1.0")]
[assembly: AssemblyFileVersion("4.1.0")]
[assembly: NeutralResourcesLanguage("en")]
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Transformer Toolkit")]
[assembly: AssemblyDescription("A toolkit for the TF700T, TF300T, ME301T and the N5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Max Röhrl")]
[assembly: AssemblyProduct("Transformer Toolkit")]
[assembly: AssemblyCopyright("Copyright © Max Röhrl 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("873db6df-3368-406b-bc7b-08efa89658ca")]
// 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("4.0.0")]
[assembly: AssemblyFileVersion("4.0.0")]
[assembly: NeutralResourcesLanguage("en")]
|
mit
|
C#
|
5a49ee470be2e3fdbbaaa3a5cd0c0308f1dee0bf
|
Fix and simplify PropertyJsonConverter after refactoring
|
KodrAus/elasticsearch-net,azubanov/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,jonyadamit/elasticsearch-net,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,jonyadamit/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,UdiBen/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,elastic/elasticsearch-net,elastic/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,jonyadamit/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net
|
src/Nest/Mapping/Types/PropertyJsonConverter.cs
|
src/Nest/Mapping/Types/PropertyJsonConverter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Nest
{
internal class PropertyJsonConverter : JsonConverter
{
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject o = JObject.Load(reader);
JToken typeToken;
JToken propertiesToken;
var type = string.Empty;
var hasType = o.TryGetValue("type", out typeToken);
if (hasType)
type = typeToken.Value<string>().ToLowerInvariant();
else if (o.TryGetValue("properties", out propertiesToken))
type = "object";
serializer.TypeNameHandling = TypeNameHandling.None;
switch (type)
{
case "string":
return o.ToObject<StringProperty>();
case "float":
case "double":
case "byte":
case "short":
case "integer":
case "long":
return o.ToObject<NumberProperty>();
case "date":
return o.ToObject<DateProperty>();
case "boolean":
return o.ToObject<BooleanProperty>();
case "binary":
return o.ToObject<BinaryProperty>();
case "object":
return o.ToObject<ObjectProperty>();
case "nested":
return o.ToObject<NestedProperty>();
case "ip":
return o.ToObject<IpProperty>();
case "geo_point":
return o.ToObject<GeoPointProperty>();
case "geo_shape":
return o.ToObject<GeoShapeProperty>();
case "attachment":
return o.ToObject<AttachmentProperty>();
case "completion":
return o.ToObject<CompletionProperty>();
case "token_count":
return o.ToObject<TokenCountProperty>();
case "murmur3":
return o.ToObject<Murmur3HashProperty>();
}
return null;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IProperty);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Nest
{
internal class PropertyJsonConverter : JsonConverter
{
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
private IProperty GetTypeFromJObject(JObject po, JsonSerializer serializer)
{
JToken typeToken;
JToken propertiesToken;
var type = string.Empty;
var hasType = po.TryGetValue("type", out typeToken);
if (hasType)
type = typeToken.Value<string>().ToLowerInvariant();
else if (po.TryGetValue("properties", out propertiesToken))
type = "object";
serializer.TypeNameHandling = TypeNameHandling.None;
switch (type)
{
case "string":
return serializer.Deserialize(po.CreateReader(), typeof(StringProperty)) as StringProperty;
case "float":
case "double":
case "byte":
case "short":
case "integer":
case "long":
return serializer.Deserialize(po.CreateReader(), typeof(NumberProperty)) as NumberProperty;
case "date":
return serializer.Deserialize(po.CreateReader(), typeof(DateProperty)) as DateProperty;
case "boolean":
return serializer.Deserialize(po.CreateReader(), typeof(BooleanProperty)) as BooleanProperty;
case "binary":
return serializer.Deserialize(po.CreateReader(), typeof(BinaryProperty)) as BinaryProperty;
case "object":
return serializer.Deserialize(po.CreateReader(), typeof(ObjectProperty)) as ObjectProperty;
case "nested":
return serializer.Deserialize(po.CreateReader(), typeof(NestedProperty)) as NestedProperty;
case "ip":
return serializer.Deserialize(po.CreateReader(), typeof(IpProperty)) as IpProperty;
case "geo_point":
return serializer.Deserialize(po.CreateReader(), typeof(GeoPointProperty)) as GeoPointProperty;
case "geo_shape":
return serializer.Deserialize(po.CreateReader(), typeof(GeoShapeProperty)) as GeoShapeProperty;
case "attachment":
return serializer.Deserialize(po.CreateReader(), typeof(AttachmentProperty)) as AttachmentProperty;
}
return null;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
JObject o = JObject.Load(reader);
var esType = this.GetTypeFromJObject(o, serializer);
return esType;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IProperty);
}
}
}
|
apache-2.0
|
C#
|
41403dcd7915a54218c19de910836a57bac44cb1
|
Set IServiceCollection as return type for AddWorkFlow
|
danielgerlag/workflow-core
|
src/WorkflowCore/ServiceCollectionExtensions.cs
|
src/WorkflowCore/ServiceCollectionExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using WorkflowCore.Interface;
using WorkflowCore.Services;
using WorkflowCore.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using WorkflowCore.Primitives;
using WorkflowCore.Services.BackgroundTasks;
using WorkflowCore.Services.DefinitionStorage;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddWorkflow(this IServiceCollection services, Action<WorkflowOptions> setupAction = null)
{
if (services.Any(x => x.ServiceType == typeof(WorkflowOptions)))
throw new InvalidOperationException("Workflow services already registered");
var options = new WorkflowOptions(services);
setupAction?.Invoke(options);
services.AddTransient<IPersistenceProvider>(options.PersistanceFactory);
services.AddSingleton<IQueueProvider>(options.QueueFactory);
services.AddSingleton<IDistributedLockProvider>(options.LockFactory);
services.AddSingleton<IWorkflowRegistry, WorkflowRegistry>();
services.AddSingleton<WorkflowOptions>(options);
services.AddTransient<IBackgroundTask, WorkflowConsumer>();
services.AddTransient<IBackgroundTask, EventConsumer>();
services.AddTransient<IBackgroundTask, RunnablePoller>();
services.AddSingleton<IWorkflowController, WorkflowController>();
services.AddSingleton<IWorkflowHost, WorkflowHost>();
services.AddTransient<IWorkflowExecutor, WorkflowExecutor>();
services.AddTransient<IWorkflowBuilder, WorkflowBuilder>();
services.AddTransient<IDateTimeProvider, DateTimeProvider>();
services.AddTransient<IExecutionResultProcessor, ExecutionResultProcessor>();
services.AddTransient<IExecutionPointerFactory, ExecutionPointerFactory>();
services.AddTransient<IPooledObjectPolicy<IPersistenceProvider>, InjectedObjectPoolPolicy<IPersistenceProvider>>();
services.AddTransient<IPooledObjectPolicy<IWorkflowExecutor>, InjectedObjectPoolPolicy<IWorkflowExecutor>>();
services.AddTransient<IDefinitionLoader, DefinitionLoader>();
services.AddTransient<Foreach>();
return services;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using WorkflowCore.Interface;
using WorkflowCore.Services;
using WorkflowCore.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using WorkflowCore.Primitives;
using WorkflowCore.Services.BackgroundTasks;
using WorkflowCore.Services.DefinitionStorage;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static void AddWorkflow(this IServiceCollection services, Action<WorkflowOptions> setupAction = null)
{
if (services.Any(x => x.ServiceType == typeof(WorkflowOptions)))
throw new InvalidOperationException("Workflow services already registered");
var options = new WorkflowOptions(services);
setupAction?.Invoke(options);
services.AddTransient<IPersistenceProvider>(options.PersistanceFactory);
services.AddSingleton<IQueueProvider>(options.QueueFactory);
services.AddSingleton<IDistributedLockProvider>(options.LockFactory);
services.AddSingleton<IWorkflowRegistry, WorkflowRegistry>();
services.AddSingleton<WorkflowOptions>(options);
services.AddTransient<IBackgroundTask, WorkflowConsumer>();
services.AddTransient<IBackgroundTask, EventConsumer>();
services.AddTransient<IBackgroundTask, RunnablePoller>();
services.AddSingleton<IWorkflowController, WorkflowController>();
services.AddSingleton<IWorkflowHost, WorkflowHost>();
services.AddTransient<IWorkflowExecutor, WorkflowExecutor>();
services.AddTransient<IWorkflowBuilder, WorkflowBuilder>();
services.AddTransient<IDateTimeProvider, DateTimeProvider>();
services.AddTransient<IExecutionResultProcessor, ExecutionResultProcessor>();
services.AddTransient<IExecutionPointerFactory, ExecutionPointerFactory>();
services.AddTransient<IPooledObjectPolicy<IPersistenceProvider>, InjectedObjectPoolPolicy<IPersistenceProvider>>();
services.AddTransient<IPooledObjectPolicy<IWorkflowExecutor>, InjectedObjectPoolPolicy<IWorkflowExecutor>>();
services.AddTransient<IDefinitionLoader, DefinitionLoader>();
services.AddTransient<Foreach>();
}
}
}
|
mit
|
C#
|
6c35becdf60abcd49a85f8ff4ef6e06ebfed6a49
|
fix portable apps
|
zamont/core-setup,ellismg/core-setup,gkhanna79/core-setup,weshaggard/core-setup,zamont/core-setup,crummel/dotnet_core-setup,vivmishra/core-setup,ravimeda/core-setup,ericstj/core-setup,ellismg/core-setup,gkhanna79/core-setup,ericstj/core-setup,rakeshsinghranchi/core-setup,karajas/core-setup,vivmishra/core-setup,ellismg/core-setup,ericstj/core-setup,joperezr/core-setup,chcosta/core-setup,MichaelSimons/core-setup,ramarag/core-setup,vivmishra/core-setup,joperezr/core-setup,weshaggard/core-setup,crummel/dotnet_core-setup,vivmishra/core-setup,ramarag/core-setup,karajas/core-setup,ericstj/core-setup,ramarag/core-setup,weshaggard/core-setup,crummel/dotnet_core-setup,weshaggard/core-setup,chcosta/core-setup,wtgodbe/core-setup,ramarag/core-setup,joperezr/core-setup,rakeshsinghranchi/core-setup,karajas/core-setup,gkhanna79/core-setup,vivmishra/core-setup,janvorli/core-setup,cakine/core-setup,cakine/core-setup,janvorli/core-setup,ellismg/core-setup,ericstj/core-setup,zamont/core-setup,gkhanna79/core-setup,rakeshsinghranchi/core-setup,wtgodbe/core-setup,joperezr/core-setup,rakeshsinghranchi/core-setup,schellap/core-setup,joperezr/core-setup,cakine/core-setup,crummel/dotnet_core-setup,cakine/core-setup,zamont/core-setup,zamont/core-setup,wtgodbe/core-setup,ravimeda/core-setup,ravimeda/core-setup,karajas/core-setup,chcosta/core-setup,chcosta/core-setup,gkhanna79/core-setup,cakine/core-setup,steveharter/core-setup,crummel/dotnet_core-setup,wtgodbe/core-setup,wtgodbe/core-setup,steveharter/core-setup,schellap/core-setup,rakeshsinghranchi/core-setup,rakeshsinghranchi/core-setup,ramarag/core-setup,chcosta/core-setup,MichaelSimons/core-setup,MichaelSimons/core-setup,steveharter/core-setup,ravimeda/core-setup,gkhanna79/core-setup,ellismg/core-setup,zamont/core-setup,schellap/core-setup,karajas/core-setup,wtgodbe/core-setup,ramarag/core-setup,janvorli/core-setup,weshaggard/core-setup,steveharter/core-setup,cakine/core-setup,schellap/core-setup,MichaelSimons/core-setup,schellap/core-setup,MichaelSimons/core-setup,weshaggard/core-setup,chcosta/core-setup,janvorli/core-setup,schellap/core-setup,crummel/dotnet_core-setup,vivmishra/core-setup,steveharter/core-setup,joperezr/core-setup,karajas/core-setup,ravimeda/core-setup,steveharter/core-setup,MichaelSimons/core-setup,janvorli/core-setup,ellismg/core-setup,ravimeda/core-setup,ericstj/core-setup,janvorli/core-setup
|
build_projects/shared-build-targets-utils/Utils/BuildVersion.cs
|
build_projects/shared-build-targets-utils/Utils/BuildVersion.cs
|
using System.Collections.Generic;
namespace Microsoft.DotNet.Cli.Build
{
public class BuildVersion : Version
{
public string SimpleVersion => $"{Major}.{Minor}.{Patch}.{CommitCountString}";
public string VersionSuffix => $"{ReleaseSuffix}-{CommitCountString}";
public string NuGetVersion => $"{Major}.{Minor}.{Patch}-{VersionSuffix}";
public string NetCoreAppVersion => $"{Major}.{Minor}.{Patch}-{ReleaseSuffix}-{CommitCountString}-00";
public string ProductionVersion => $"{Major}.{Minor}.{Patch}";
}
}
|
using System.Collections.Generic;
namespace Microsoft.DotNet.Cli.Build
{
public class BuildVersion : Version
{
public string SimpleVersion => $"{Major}.{Minor}.{Patch}.{CommitCountString}";
public string VersionSuffix => $"{ReleaseSuffix}-{CommitCountString}";
public string NuGetVersion => $"{Major}.{Minor}.{Patch}-{VersionSuffix}";
public string NetCoreAppVersion => $"{Major}.{Minor}.{Patch}-{ReleaseSuffix}-{CommitCountString}";
public string ProductionVersion => $"{Major}.{Minor}.{Patch}";
}
}
|
mit
|
C#
|
4af450c49fd36655cab1597005c458918f3f62e0
|
comment out the unused [DllImport] to pass certification
|
mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp
|
source/SkiaSharp.Views/SkiaSharp.Views.UWP/GlesInterop/PropertySetInterop.cs
|
source/SkiaSharp.Views/SkiaSharp.Views.UWP/GlesInterop/PropertySetInterop.cs
|
using System.Runtime.InteropServices;
using Windows.Foundation.Collections;
namespace SkiaSharp.Views.GlesInterop
{
//internal static class PropertySetInterop
//{
// public static void AddSingle(PropertySet properties, string key, float value)
// {
// PropertySetInterop_AddSingle(properties, key, value);
// }
// public static void AddSize(PropertySet properties, string key, float width, float height)
// {
// PropertySetInterop_AddSize(properties, key, width, height);
// }
// private const string libInterop = "SkiaSharp.Views.Interop.UWP.dll";
// [DllImport(libInterop)]
// private static extern void PropertySetInterop_AddSingle(
// [MarshalAs(UnmanagedType.IInspectable)] object properties,
// [MarshalAs(UnmanagedType.HString)] string key,
// float value);
// [DllImport(libInterop)]
// private static extern void PropertySetInterop_AddSize(
// [MarshalAs(UnmanagedType.IInspectable)] object properties,
// [MarshalAs(UnmanagedType.HString)] string key,
// float width, float height);
//}
}
|
using System.Runtime.InteropServices;
using Windows.Foundation.Collections;
namespace SkiaSharp.Views.GlesInterop
{
internal static class PropertySetInterop
{
public static void AddSingle(PropertySet properties, string key, float value)
{
PropertySetInterop_AddSingle(properties, key, value);
}
public static void AddSize(PropertySet properties, string key, float width, float height)
{
PropertySetInterop_AddSize(properties, key, width, height);
}
private const string libInterop = "SkiaSharp.Views.Interop.UWP.dll";
[DllImport(libInterop)]
private static extern void PropertySetInterop_AddSingle(
[MarshalAs(UnmanagedType.IInspectable)] object properties,
[MarshalAs(UnmanagedType.HString)] string key,
float value);
[DllImport(libInterop)]
private static extern void PropertySetInterop_AddSize(
[MarshalAs(UnmanagedType.IInspectable)] object properties,
[MarshalAs(UnmanagedType.HString)] string key,
float width, float height);
}
}
|
mit
|
C#
|
9d1f88e7c2f30fee04718f6ae1578e90fbc9f6b2
|
Fix typo in log message. (#2247)
|
dotnet/docfx,pascalberger/docfx,pascalberger/docfx,pascalberger/docfx,superyyrrzz/docfx,superyyrrzz/docfx,dotnet/docfx,superyyrrzz/docfx,dotnet/docfx
|
src/Microsoft.DocAsCode.Metadata.ManagedReference/MsBuildEnvironmentScope.cs
|
src/Microsoft.DocAsCode.Metadata.ManagedReference/MsBuildEnvironmentScope.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.MSBuildLocator;
using Microsoft.DocAsCode.Common;
public class MSBuildEnvironmentScope : IDisposable
{
private readonly EnvironmentScope _innerScope;
public MSBuildEnvironmentScope()
{
// workaround for https://github.com/dotnet/docfx/issues/1969
// FYI https://github.com/dotnet/roslyn/issues/21799#issuecomment-343695700
var instances = MSBuildLocator.QueryVisualStudioInstances();
var latest = instances.FirstOrDefault(a => a.Version.Major == 15);
if (latest != null)
{
Logger.LogInfo($"Using msbuild {latest.MSBuildPath} as inner compiler.");
_innerScope = new EnvironmentScope(new Dictionary<string, string>
{
["VSINSTALLDIR"] = latest.VisualStudioRootPath,
["VisualStudioVersion"] = "15.0"
});
}
}
public void Dispose()
{
_innerScope?.Dispose();
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.MSBuildLocator;
using Microsoft.DocAsCode.Common;
public class MSBuildEnvironmentScope : IDisposable
{
private readonly EnvironmentScope _innerScope;
public MSBuildEnvironmentScope()
{
// workaround for https://github.com/dotnet/docfx/issues/1969
// FYI https://github.com/dotnet/roslyn/issues/21799#issuecomment-343695700
var instances = MSBuildLocator.QueryVisualStudioInstances();
var latest = instances.FirstOrDefault(a => a.Version.Major == 15);
if (latest != null)
{
Logger.LogInfo($"Using msbuild {latest.MSBuildPath} as inner comipiler.");
_innerScope = new EnvironmentScope(new Dictionary<string, string>
{
["VSINSTALLDIR"] = latest.VisualStudioRootPath,
["VisualStudioVersion"] = "15.0"
});
}
}
public void Dispose()
{
_innerScope?.Dispose();
}
}
}
|
mit
|
C#
|
d8becf30a46a4dc0bab40f155328c15516c5d83d
|
add Lambda Ignore extensions
|
serilog/serilog,redwards510/serilog,vossad01/serilog,ravensorb/serilog,adamchester/serilog,serilog/serilog,SaltyDH/serilog,DavidSSL/serilog,merbla/serilog,ajayanandgit/serilog,ravensorb/serilog,harishjan/serilog,jotautomation/serilog,harishjan/serilog,khellang/serilog,joelweiss/serilog,merbla/serilog,richardlawley/serilog,skomis-mm/serilog,skomis-mm/serilog,zmaruo/serilog,clarkis117/serilog,nblumhardt/serilog,CaioProiete/serilog,Applicita/serilog,colin-young/serilog,adamchester/serilog,joelweiss/serilog,vorou/serilog,colin-young/serilog,nblumhardt/serilog,clarkis117/serilog,JuanjoFuchs/serilog,Jaben/serilog
|
src/Serilog.Extras.LambdaIgnore/LoggerConfigurationLambdaIgnoreExtensions.cs
|
src/Serilog.Extras.LambdaIgnore/LoggerConfigurationLambdaIgnoreExtensions.cs
|
// Copyright 2014 Serilog Contributors
//
// 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.Expressions;
using Serilog.Configuration;
using Serilog.Extras.LambdaIgnore.Extras.LambdaIgnore;
namespace Serilog.Extras.LambdaIgnore
{
/// <summary>
/// Adds the Destructure.UsingLambdaIgnores() extension to <see cref="LoggerConfiguration"/>.
/// </summary>
public static class LoggerConfigurationLambdaIgnoreExtensions
{
/// <summary>
/// </summary>
/// <param name="configuration">The logger configuration to apply configuration to.</param>
/// <param name="ignored">The function expressions that expose the properties to ignore.</param>
/// <returns>An object allowing configuration to continue.</returns>
public static LoggerConfiguration UsingLambdaIgnores<TDestructureType>(this LoggerDestructuringConfiguration configuration, params Expression<Func<TDestructureType, object>>[] ignored)
{
return configuration.With(new LambdaIgnoreDestructuringPolicy<TDestructureType>(ignored));
}
}
}
|
// Copyright 2014 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Extras.LambdaIgnore
{
public class LoggerConfigurationLambdaIgnoreExtensions
{
}
}
|
apache-2.0
|
C#
|
4f01c03aef85e83135e8ce3dab8cdf6a6b081152
|
Fix merge conflict.
|
alesliehughes/monoDX,alesliehughes/monoDX
|
Microsoft.DirectX.DirectPlay/Microsoft.DirectX.DirectPlay/GroupInformation.cs
|
Microsoft.DirectX.DirectPlay/Microsoft.DirectX.DirectPlay/GroupInformation.cs
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Alistair Leslie-Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Microsoft.DirectX.DirectPlay;
using System;
namespace Microsoft.DirectX.DirectPlay
{
public struct GroupInformation
{
public string Name
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public GroupFlags GroupFlags
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public override string ToString()
{
throw new NotImplementedException ();
}
public byte[] GetData()
{
throw new NotImplementedException ();
}
public void SetData(byte[] value)
{
throw new NotImplementedException ();
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Alistair Leslie-Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Microsoft.DirectX.DirectPlay;
<<<<<<< HEAD
using Microsoft.DirectX.PrivateImplementationDetails;
using Microsoft.VisualC;
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
=======
using System;
>>>>>>> 398e26f5f51556c88e7f17d23de269732502d0fa
namespace Microsoft.DirectX.DirectPlay
{
public struct GroupInformation
{
public string Name
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public GroupFlags GroupFlags
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public override string ToString()
{
throw new NotImplementedException ();
}
public byte[] GetData()
{
throw new NotImplementedException ();
}
public void SetData(byte[] value)
{
throw new NotImplementedException ();
}
}
}
|
mit
|
C#
|
fe10acfa990a396c4a70f6723add3cbda51a581d
|
Change Image Reward path
|
tlaothong/xdailysoccer,tlaothong/xdailysoccer,tlaothong/xdailysoccer,tlaothong/xdailysoccer
|
src/DailySoccerSolution/DailySoccerAppService/Controllers/RewardController.cs
|
src/DailySoccerSolution/DailySoccerAppService/Controllers/RewardController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using DailySoccer.Shared.Models;
using DailySoccer.Shared.Facades;
namespace DailySoccerAppService.Controllers
{
public class RewardController : ApiController
{
public ApiServices Services { get; set; }
// GET api/Reward
//[HttpGet]
//public string Get()
//{
// return "Respond by GET method";
//}
[HttpGet]
public GetCurrentRewardsRespond GetCurrentRewards()
{
var reward = new List<RewardInformation>
{
new RewardInformation
{
ImagePath = "img/Logos/BannerReward01.png",
RemainingAmount = 5
},
new RewardInformation
{
ImagePath = "img/Logos/BannerReward02.png",
RemainingAmount = 3
},
new RewardInformation
{
ImagePath = "http://www.samsung.com/th/consumer-images/product/smartphone/2015/SM-G920FZKACAM/features/SM-G920FZKACAM-403979-0.jpg",
RemainingAmount = 1
}
};
return new GetCurrentRewardsRespond {
TicketCost = 50,
Rewards = reward
};
}
[HttpGet]
public IEnumerable<RewardGroupInformation> GetRewardGroup()
{
var rewardFacade = new RewardFacade();
return rewardFacade.GetRewardGroup();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using DailySoccer.Shared.Models;
using DailySoccer.Shared.Facades;
namespace DailySoccerAppService.Controllers
{
public class RewardController : ApiController
{
public ApiServices Services { get; set; }
// GET api/Reward
//[HttpGet]
//public string Get()
//{
// return "Respond by GET method";
//}
[HttpGet]
public GetCurrentRewardsRespond GetCurrentRewards()
{
var reward = new List<RewardInformation>
{
new RewardInformation
{
ImagePath = "http://www.samsung.com/th/consumer-images/product/smartphone/2015/SM-G920FZKACAM/features/SM-G920FZKACAM-403979-0.jpg",
RemainingAmount = 5
},
new RewardInformation
{
ImagePath = "http://www.samsung.com/th/consumer-images/product/smartphone/2015/SM-G920FZKACAM/features/SM-G920FZKACAM-403979-0.jpg",
RemainingAmount = 3
},
new RewardInformation
{
ImagePath = "http://www.samsung.com/th/consumer-images/product/smartphone/2015/SM-G920FZKACAM/features/SM-G920FZKACAM-403979-0.jpg",
RemainingAmount = 1
}
};
return new GetCurrentRewardsRespond {
TicketCost = 50,
Rewards = reward
};
}
[HttpGet]
public IEnumerable<RewardGroupInformation> GetRewardGroup()
{
var rewardFacade = new RewardFacade();
return rewardFacade.GetRewardGroup();
}
}
}
|
mit
|
C#
|
569cbfc4b9c3d144b579a4586d9d43e8e1489918
|
Use a small delta when comparing inexact doubles for equality.
|
alobakov/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core
|
src/NHibernate.Test/NHSpecificTest/NH1734/Fixture.cs
|
src/NHibernate.Test/NHSpecificTest/NH1734/Fixture.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1734
{
[TestFixture]
public class Fixture:BugTestCase
{
protected override void OnSetUp()
{
using(var session=this.OpenSession())
using(var tran=session.BeginTransaction())
{
var product = new Product {Amount = 3, Price = 43.2};
var product2 = new Product { Amount = 3, Price = 43.2 };
session.Save(product);
session.Save(product2);
tran.Commit();
}
}
protected override void OnTearDown()
{
using(var session=this.OpenSession())
using (var tran = session.BeginTransaction())
{
session.Delete("from Product");
tran.Commit();
}
}
[Test]
public void ReturnsApropriateTypeWhenSumUsedWithSomeFormula()
{
using (var session = this.OpenSession())
using (var tran = session.BeginTransaction())
{
double delta = 0.0000000000001;
var query=session.CreateQuery("select sum(Amount*Price) from Product");
var result=query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof (double)));
Assert.AreEqual(43.2 * 3 * 2, (double)result, delta);
query = session.CreateQuery("select sum(Price*Amount) from Product");
result = query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof(double)));
Assert.AreEqual(43.2 * 3 * 2, (double)result, delta);
query = session.CreateQuery("select sum(Price) from Product");
result = query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof(double)));
Assert.AreEqual(43.2 * 2, (double)result, delta);
query = session.CreateQuery("select sum(Amount) from Product");
result = query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof(Int64)));
Assert.That(result, Is.EqualTo(6));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1734
{
[TestFixture]
public class Fixture:BugTestCase
{
protected override void OnSetUp()
{
using(var session=this.OpenSession())
using(var tran=session.BeginTransaction())
{
var product = new Product {Amount = 3, Price = 43.2};
var product2 = new Product { Amount = 3, Price = 43.2 };
session.Save(product);
session.Save(product2);
tran.Commit();
}
}
protected override void OnTearDown()
{
using(var session=this.OpenSession())
using (var tran = session.BeginTransaction())
{
session.Delete("from Product");
tran.Commit();
}
}
[Test]
public void ReturnsApropriateTypeWhenSumUsedWithSomeFormula()
{
using (var session = this.OpenSession())
using (var tran = session.BeginTransaction())
{
var query=session.CreateQuery("select sum(Amount*Price) from Product");
var result=query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof (double)));
Assert.That(result, Is.EqualTo(43.2*3*2));
query = session.CreateQuery("select sum(Price*Amount) from Product");
result = query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof(double)));
Assert.That(result, Is.EqualTo(43.2 * 3 * 2));
query = session.CreateQuery("select sum(Price) from Product");
result = query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof(double)));
Assert.That(result, Is.EqualTo(43.2 * 2));
query = session.CreateQuery("select sum(Amount) from Product");
result = query.UniqueResult();
Assert.That(result, Is.InstanceOf(typeof(Int64)));
Assert.That(result, Is.EqualTo(6.0));
}
}
}
}
|
lgpl-2.1
|
C#
|
a41e847faa43970a192ac45164281b6938de4749
|
comment Explicit tests as an attempt to fix issue with AppVeyor
|
NFluent/NFluent,dupdob/NFluent,dupdob/NFluent,tpierrain/NFluent,tpierrain/NFluent,NFluent/NFluent,tpierrain/NFluent,dupdob/NFluent
|
tests/NFluent.Tests.Internals/ForDocumentation/LocaleChecks.cs
|
tests/NFluent.Tests.Internals/ForDocumentation/LocaleChecks.cs
|
// // --------------------------------------------------------------------------------------------------------------------
// // <copyright file="LocaleChecks.cs" company="">
// // Copyright 2013 Cyrille DUPUYDAUBY
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// // http://www.apache.org/licenses/LICENSE-2.0
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// // </copyright>
// // --------------------------------------------------------------------------------------------------------------------
// ReSharper disable once CheckNamespace
namespace NFluent.Tests.ForDocumentation
{
using Helpers;
using NUnit.Framework;
[TestFixture]
public class LocaleChecks
{
//[Test]
[Explicit("Scan all assemblies, execute tests in Spanish.")]
public void Spanish()
{
using (new CultureSession("es-ES"))
{
RunnerHelper.RunAllTests(false);
}
}
//[Test]
[Explicit("Scan all assemblies, execute tests in Chinese.")]
public void Chinese()
{
using (new CultureSession("zh-CN"))
{
RunnerHelper.RunAllTests(false);
}
}
//[Test]
[Explicit("Scan all assemblies, execute tests in Canadian French.")]
public void CanadianFrench()
{
using (new CultureSession("fr-CA"))
{
RunnerHelper.RunAllTests(false);
}
}
//[Test]
[Explicit("Scan all assemblies, execute tests in Japanese.")]
public void Japanese()
{
using (new CultureSession("ja-JP"))
{
RunnerHelper.RunAllTests(false);
}
}
// TODO: makes the teamcity build execute Explicit tests
}
}
|
// // --------------------------------------------------------------------------------------------------------------------
// // <copyright file="LocaleChecks.cs" company="">
// // Copyright 2013 Cyrille DUPUYDAUBY
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// // http://www.apache.org/licenses/LICENSE-2.0
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// // </copyright>
// // --------------------------------------------------------------------------------------------------------------------
// ReSharper disable once CheckNamespace
namespace NFluent.Tests.ForDocumentation
{
using Helpers;
using NUnit.Framework;
[TestFixture]
public class LocaleChecks
{
[Test]
[Explicit("Scan all assemblies, execute tests in Spanish.")]
public void Spanish()
{
using (new CultureSession("es-ES"))
{
RunnerHelper.RunAllTests(false);
}
}
[Test]
[Explicit("Scan all assemblies, execute tests in Chinese.")]
public void Chinese()
{
using (new CultureSession("zh-CN"))
{
RunnerHelper.RunAllTests(false);
}
}
[Test]
[Explicit("Scan all assemblies, execute tests in Canadian French.")]
public void CanadianFrench()
{
using (new CultureSession("fr-CA"))
{
RunnerHelper.RunAllTests(false);
}
}
[Test]
[Explicit("Scan all assemblies, execute tests in Japanese.")]
public void Japanese()
{
using (new CultureSession("ja-JP"))
{
RunnerHelper.RunAllTests(false);
}
}
// TODO: makes the teamcity build execute Explicit tests
}
}
|
apache-2.0
|
C#
|
29b7b64503be9169226876a213661bdafec4af80
|
update statesets
|
LagoVista/DeviceAdmin
|
src/LagoVista.IoT.DeviceAdmin.CloudRepos/Repos/StateSetRepo.cs
|
src/LagoVista.IoT.DeviceAdmin.CloudRepos/Repos/StateSetRepo.cs
|
using LagoVista.CloudStorage.DocumentDB;
using LagoVista.Core.PlatformSupport;
using LagoVista.IoT.DeviceAdmin.Interfaces.Repos;
using LagoVista.IoT.DeviceAdmin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.CloudRepos.Repos
{
public class StateSetRepo : DocumentDBRepoBase<StateSet>, IStateSetRepo
{
private bool _shouldConsolidateCollections;
public StateSetRepo(IDeviceRepoSettings settings, ILogger logger) : base(settings.DeviceDocDbStorage.Uri, settings.DeviceDocDbStorage.AccessKey, settings.DeviceDocDbStorage.ResourceName, logger)
{
_shouldConsolidateCollections = settings.ShouldConsolidateCollections;
}
protected override bool ShouldConsolidateCollections { get { return _shouldConsolidateCollections; } }
public Task AddStateSetAsync(StateSet unitSet)
{
return CreateDocumentAsync(unitSet);
}
public Task UpdateStateSetAsync(StateSet unitSet)
{
return UpsertDocumentAsync(unitSet);
}
public Task<StateSet> GetStateSetAsync(string unitSetId)
{
return GetDocumentAsync(unitSetId);
}
public async Task<bool> QueryKeyInUseAsync(string key, string orgId)
{
var items = await base.QueryAsync(attr => (attr.OwnerOrganization.Id == orgId || attr.IsPublic == true) && attr.Key == key);
return items.Any();
}
public async Task<IEnumerable<StateSetSummary>> GetStateSetsForOrgAsync(string orgId)
{
var items = await base.QueryAsync(qry => qry.IsPublic == true || qry.OwnerOrganization.Id == orgId);
return from item in items
select item.CreateStateSetSummary();
}
}
}
|
using LagoVista.CloudStorage.DocumentDB;
using LagoVista.Core.PlatformSupport;
using LagoVista.IoT.DeviceAdmin.Interfaces.Repos;
using LagoVista.IoT.DeviceAdmin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.CloudRepos.Repos
{
public class StateSetRepo : DocumentDBRepoBase<StateSet>, IStateSetRepo
{
private bool _shouldConsolidateCollections;
public StateSetRepo(IDeviceRepoSettings settings, ILogger logger) : base(settings.DeviceDocDbStorage.Uri, settings.DeviceDocDbStorage.AccessKey, settings.DeviceDocDbStorage.ResourceName, logger)
{
_shouldConsolidateCollections = settings.ShouldConsolidateCollections;
}
protected override bool ShouldConsolidateCollections { get { return _shouldConsolidateCollections; } }
public Task AddStateSetAsync(StateSet unitSet)
{
return CreateDocumentAsync(unitSet);
}
public Task UpdateStateSetAsync(StateSet unitSet)
{
return CreateDocumentAsync(unitSet);
}
public Task<StateSet> GetStateSetAsync(string unitSetId)
{
return GetDocumentAsync(unitSetId);
}
public async Task<bool> QueryKeyInUseAsync(string key, string orgId)
{
var items = await base.QueryAsync(attr => (attr.OwnerOrganization.Id == orgId || attr.IsPublic == true) && attr.Key == key);
return items.Any();
}
public async Task<IEnumerable<StateSetSummary>> GetStateSetsForOrgAsync(string orgId)
{
var items = await base.QueryAsync(qry => qry.IsPublic == true || qry.OwnerOrganization.Id == orgId);
return from item in items
select item.CreateStateSetSummary();
}
}
}
|
mit
|
C#
|
b94f5975eb7d0f338b2983628df175a975230b9e
|
Remove extra space.
|
SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex
|
src/Avalonia.Animation/TransitionInstance.cs
|
src/Avalonia.Animation/TransitionInstance.cs
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Metadata;
using System;
using System.Reactive.Linq;
using Avalonia.Animation.Easings;
using Avalonia.Animation.Utils;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
/// <summary>
/// Handles the timing and lifetime of a <see cref="Transition{T}"/>.
/// </summary>
internal class TransitionInstance : SingleSubscriberObservableBase<double>
{
private IDisposable _timerSubscription;
private TimeSpan _duration;
private readonly IClock _baseClock;
private IClock _clock;
public TransitionInstance(IClock clock, TimeSpan Duration)
{
_duration = Duration;
_baseClock = clock;
}
private void TimerTick(TimeSpan t)
{
var interpVal = (double)t.Ticks / _duration.Ticks;
// Clamp interpolation value.
if (interpVal >= 1d | (interpVal < 0d))
{
PublishNext(1d);
PublishCompleted();
}
else
{
PublishNext(interpVal);
}
}
protected override void Unsubscribed()
{
_timerSubscription?.Dispose();
_clock.PlayState = PlayState.Stop;
}
protected override void Subscribed()
{
_clock = new Clock(_baseClock);
_timerSubscription = _clock.Subscribe(TimerTick);
PublishNext(0.0d);
}
}
}
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Metadata;
using System;
using System.Reactive.Linq;
using Avalonia.Animation.Easings;
using Avalonia.Animation.Utils;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
/// <summary>
/// Handles the timing and lifetime of a <see cref="Transition{T}"/>.
/// </summary>
internal class TransitionInstance : SingleSubscriberObservableBase<double>
{
private IDisposable _timerSubscription;
private TimeSpan _duration;
private readonly IClock _baseClock;
private IClock _clock;
public TransitionInstance(IClock clock, TimeSpan Duration)
{
_duration = Duration;
_baseClock = clock;
}
private void TimerTick(TimeSpan t)
{
var interpVal = (double)t.Ticks / _duration.Ticks;
// Clamp interpolation value.
if (interpVal >= 1d | (interpVal < 0d))
{
PublishNext(1d);
PublishCompleted();
}
else
{
PublishNext(interpVal);
}
}
protected override void Unsubscribed()
{
_timerSubscription?.Dispose();
_clock.PlayState = PlayState.Stop;
}
protected override void Subscribed()
{
_clock = new Clock(_baseClock);
_timerSubscription = _clock.Subscribe(TimerTick);
PublishNext(0.0d);
}
}
}
|
mit
|
C#
|
8b366d9aff76fc3599262eb0940a22a7adc362c7
|
add default for generic
|
json-api-dotnet/JsonApiDotNetCore,Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core
|
src/JsonApiDotNetCore/Models/Identifiable.cs
|
src/JsonApiDotNetCore/Models/Identifiable.cs
|
namespace JsonApiDotNetCore.Models
{
public class Identifiable : Identifiable<int>
{}
public class Identifiable<T> : IIdentifiable<T>, IIdentifiable
{
public T Id { get; set; }
object IIdentifiable.Id
{
get { return Id; }
set { Id = (T)value; }
}
}
}
|
namespace JsonApiDotNetCore.Models
{
public abstract class Identifiable<T> : IIdentifiable<T>, IIdentifiable
{
public T Id { get; set; }
object IIdentifiable.Id
{
get { return Id; }
set { Id = (T)value; }
}
}
}
|
mit
|
C#
|
24a2c4af964dbb7166bfbd89bfefc07db3f66c85
|
fix openfile command
|
mike-ward/Markdown-Edit,punker76/Markdown-Edit
|
src/MarkdownEdit/Commands/OpenFileCommand.cs
|
src/MarkdownEdit/Commands/OpenFileCommand.cs
|
using System.Windows;
using System.Windows.Input;
using MarkdownEdit.Controls;
namespace MarkdownEdit.Commands
{
internal static class OpenFileCommand
{
public static readonly RoutedCommand Command = ApplicationCommands.Open;
static OpenFileCommand()
{
Application.Current.MainWindow.CommandBindings.Add(new CommandBinding(Command, Execute));
}
private static void Execute(object sender, ExecutedRoutedEventArgs e)
{
var mainWindow = (MainWindow)sender;
mainWindow.Editor.OpenFile(e.Parameter as string);
}
}
}
|
using System.Windows;
using System.Windows.Input;
using MarkdownEdit.Controls;
namespace MarkdownEdit.Commands
{
internal static class OpenFileCommand
{
public static readonly RoutedCommand Command = new RoutedCommand();
static OpenFileCommand()
{
Application.Current.MainWindow.CommandBindings.Add(new CommandBinding(Command, Execute));
}
private static void Execute(object sender, ExecutedRoutedEventArgs e)
{
var mainWindow = (MainWindow)sender;
mainWindow.Editor.OpenFile(e.Parameter as string);
}
}
}
|
mit
|
C#
|
207e3e2a6dae7516482489a4d800c62236f04789
|
Improve code documentation in the IStorageEngine interface
|
openchain/openchain
|
src/Openchain.Abstractions/IStorageEngine.cs
|
src/Openchain.Abstractions/IStorageEngine.cs
|
// Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Openchain
{
/// <summary>
/// Represents a data store for key-value pairs.
/// </summary>
public interface IStorageEngine : IDisposable
{
/// <summary>
/// Initializes the storage engine.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task Initialize();
/// <summary>
/// Adds a transaction to the store.
/// </summary>
/// <param name="transactions">A collection of serialized <see cref="Transaction"/> to add to the store.</param>
/// <exception cref="ConcurrentMutationException">A record has been mutated and the transaction is no longer valid.</exception>
/// <returns>The task object representing the asynchronous operation.</returns>
Task AddTransactions(IEnumerable<ByteString> transactions);
/// <summary>
/// Gets the current records for a set of keys.
/// </summary>
/// <param name="keys">The keys to query.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<Record>> GetRecords(IEnumerable<ByteString> keys);
/// <summary>
/// Gets the hash of the last transaction in the ledger.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ByteString> GetLastTransaction();
/// <summary>
/// Get an ordered list of transactions from a given point.
/// </summary>
/// <param name="from">The hash of the transaction to start from.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<ByteString>> GetTransactions(ByteString from);
}
}
|
// Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Openchain
{
/// <summary>
/// Represents a data store for key-value pairs.
/// </summary>
public interface IStorageEngine : IDisposable
{
/// <summary>
/// Initialize the storage engine.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task Initialize();
/// <summary>
/// Adds a transaction to the store.
/// </summary>
/// <param name="transactions">A collection of serialized <see cref="Transaction"/> to add to the store.</param>
/// <exception cref="ConcurrentMutationException">A record has been mutated and the transaction is no longer valid.</exception>
/// <returns>The task object representing the asynchronous operation.</returns>
Task AddTransactions(IEnumerable<ByteString> transactions);
/// <summary>
/// Gets the current records for a set of keys.
/// </summary>
/// <param name="keys">The keys to query.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<Record>> GetRecords(IEnumerable<ByteString> keys);
/// <summary>
/// Gets the hash of the last transaction in the ledger.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ByteString> GetLastTransaction();
/// <summary>
/// Get an ordered list of transactions from a given point.
/// </summary>
/// <param name="from">The hash of the transaction to start from.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<ByteString>> GetTransactions(ByteString from);
}
}
|
apache-2.0
|
C#
|
d75bbb2b88debd6b578e4e77ea5de73c87c2f4dc
|
Fix incorrect sorting.
|
UselessToucan/osu,smoogipoo/osu,Frontear/osuKyzer,ppy/osu,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,smoogipooo/osu,Drezi126/osu,ZLima12/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,DrabWeb/osu,ppy/osu,DrabWeb/osu,peppy/osu-new,ppy/osu,DrabWeb/osu,naoey/osu,Damnae/osu,smoogipoo/osu,johnneijzen/osu,UselessToucan/osu,Nabile-Rahmani/osu,peppy/osu,naoey/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,osu-RP/osu-RP,naoey/osu,smoogipoo/osu,EVAST9919/osu
|
osu.Game.Rulesets.Mania/Timing/TimingChangeContainer.cs
|
osu.Game.Rulesets.Mania/Timing/TimingChangeContainer.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using OpenTK;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Mania.Timing.Drawables;
namespace osu.Game.Rulesets.Mania.Timing
{
public class TimingChangeContainer : Container<DrawableTimingChange>
{
/// <summary>
/// The amount of time which this container spans.
/// </summary>
public double TimeSpan { get; set; }
/// <summary>
/// Adds a hit object to the most applicable timing change in this container.
/// </summary>
/// <param name="hitObject">The hit object to add.</param>
public void Add(DrawableHitObject hitObject)
{
var target = timingChangeFor(hitObject);
if (target == null)
throw new ArgumentException("No timing change could be found that can contain the hit object.", nameof(hitObject));
target.Add(hitObject);
}
protected override IComparer<Drawable> DepthComparer => new TimingChangeReverseStartTimeComparer();
/// <summary>
/// Finds the most applicable timing change that can contain a hit object.
/// </summary>
/// <param name="hitObject">The hit object to contain.</param>
/// <returns>The last timing change which can contain <paramref name="hitObject"/>. Null if no timing change can contain the hit object.</returns>
private DrawableTimingChange timingChangeFor(DrawableHitObject hitObject) => Children.FirstOrDefault(c => c.CanContain(hitObject));
}
/// <summary>
/// Compares two timing changes by their start time, falling back to creation order if their start time is equal.
/// This will compare the two timing changes in reverse order.
/// </summary>
public class TimingChangeReverseStartTimeComparer : Drawable.ReverseCreationOrderDepthComparer
{
public override int Compare(Drawable x, Drawable y)
{
var timingChangeX = x as DrawableTimingChange;
var timingChangeY = y as DrawableTimingChange;
// If either of the two drawables are not hit objects, fall back to the base comparer
if (timingChangeX?.TimingChange == null || timingChangeY?.TimingChange == null)
return base.Compare(x, y);
// Compare by start time
int i = timingChangeY.TimingChange.Time.CompareTo(timingChangeX.TimingChange.Time);
if (i != 0)
return i;
return base.Compare(x, y);
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using OpenTK;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Mania.Timing.Drawables;
namespace osu.Game.Rulesets.Mania.Timing
{
public class TimingChangeContainer : Container<DrawableTimingChange>
{
/// <summary>
/// The amount of time which this container spans.
/// </summary>
public double TimeSpan { get; set; }
/// <summary>
/// Adds a hit object to the most applicable timing change in this container.
/// </summary>
/// <param name="hitObject">The hit object to add.</param>
public void Add(DrawableHitObject hitObject)
{
var target = timingChangeFor(hitObject);
if (target == null)
throw new ArgumentException("No timing change could be found that can contain the hit object.", nameof(hitObject));
target.Add(hitObject);
}
/// <summary>
/// Finds the most applicable timing change that can contain a hit object.
/// </summary>
/// <param name="hitObject">The hit object to contain.</param>
/// <returns>The last timing change which can contain <paramref name="hitObject"/>.</returns>
private DrawableTimingChange timingChangeFor(DrawableHitObject hitObject) => Children.LastOrDefault(c => c.CanContain(hitObject)) ?? Children.FirstOrDefault();
}
}
|
mit
|
C#
|
7b26c9260f9d52e3ed1c30f9ca53bf9ea0e3fd49
|
Check for collision with balls only.
|
dirty-casuals/LD38-A-Small-World
|
Assets/Scripts/Core/World.cs
|
Assets/Scripts/Core/World.cs
|
using UnityEngine;
using UnityEngine.Events;
public class World : Planet {
private UnityEvent onPlanetHit = new UnityEvent();
private Lives lives;
private void Awake() {
lives = GetComponent<Lives>();
}
private void OnCollisionEnter( Collision other ) {
if( other.transform.GetComponent<Ball>() ) {
onPlanetHit.Invoke();
}
}
public void AddHitListener( UnityAction call ) {
onPlanetHit.AddListener( call );
}
public void AddOutOfLivesListener( UnityAction<int> call ) {
lives.AddOutOfLivesListener( call );
}
public void AddLivesChangedListener( UnityAction<int> call ) {
lives.AddLivesChangedListener( call );
}
}
|
using UnityEngine;
using UnityEngine.Events;
public class World : Planet {
private UnityEvent onPlanetHit = new UnityEvent();
private Lives lives;
private void Awake() {
lives = GetComponent<Lives>();
}
private void OnCollisionEnter( Collision other ) {
onPlanetHit.Invoke();
}
public void AddHitListener( UnityAction call ) {
onPlanetHit.AddListener( call );
}
public void AddOutOfLivesListener( UnityAction<int> call ) {
lives.AddOutOfLivesListener( call );
}
public void AddLivesChangedListener( UnityAction<int> call ) {
lives.AddLivesChangedListener( call );
}
}
|
mit
|
C#
|
c6fc2758b39fb06de97d2b74649a6650865562fb
|
Add ProxyLexer.Initialized : bool
|
StevenLiekens/TextFx,StevenLiekens/Txt
|
src/Txt.Core/ProxyLexer.cs
|
src/Txt.Core/ProxyLexer.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
namespace Txt.Core
{
public sealed class ProxyLexer<TElement> : Lexer<TElement>
where TElement : Element
{
private ILexer<TElement> innerLexer;
public bool Initialized { get; private set; }
public void Initialize([NotNull] ILexer<TElement> lexer)
{
if (lexer == null)
{
throw new ArgumentNullException(nameof(lexer));
}
if (Initialized)
{
throw new InvalidOperationException(
"Initialize(ILexer`1) has already been called. Changing the rule after it has been initialized is not allowed.");
}
innerLexer = lexer;
Initialized = true;
}
protected override IEnumerable<TElement> ReadImpl(ITextScanner scanner, ITextContext context)
{
if (!Initialized)
{
throw new InvalidOperationException("Initialize(ILexer`1) has never been called.");
}
Debug.Assert(innerLexer != null, "innerLexer != null");
return innerLexer.Read(scanner, context);
}
}
}
|
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Txt.Core
{
public sealed class ProxyLexer<TElement> : Lexer<TElement>
where TElement : Element
{
private ILexer<TElement> innerLexer;
public void Initialize([NotNull] ILexer<TElement> lexer)
{
if (lexer == null)
{
throw new ArgumentNullException(nameof(lexer));
}
if (innerLexer != null)
{
throw new InvalidOperationException(
"Initialize(ILexer`1) has already been called. Changing the rule after it has been initialized is not allowed.");
}
innerLexer = lexer;
}
protected override IEnumerable<TElement> ReadImpl(ITextScanner scanner, ITextContext context)
{
if (innerLexer == null)
{
throw new InvalidOperationException("Initialize(ILexer`1) has never been called.");
}
return innerLexer.Read(scanner, context);
}
}
}
|
mit
|
C#
|
fa01e2e777ec011ff33b5b708db2ab2ee4eeff60
|
Add Book Class to LibraryContext.
|
Programazing/Open-School-Library,Programazing/Open-School-Library
|
src/Open-School-Library/Data/LibraryContext.cs
|
src/Open-School-Library/Data/LibraryContext.cs
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Open_School_Library.Models.DatabaseModels;
namespace Open_School_Library.Data
{
public class LibraryContext : DbContext
{
public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Dewey> Deweys { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Open_School_Library.Models.DatabaseModels;
namespace Open_School_Library.Data
{
public class LibraryContext : DbContext
{
public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Dewey> Deweys { get; set; }
}
}
|
mit
|
C#
|
acfad73769f7f960b90cca4afe069e4a9f86fb73
|
fix isnotnull method
|
zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning
|
my_aspnetmvc_learning/Controllers/ImageController.cs
|
my_aspnetmvc_learning/Controllers/ImageController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file.IsNotNull())
{
logger.Info("FileName : " + file.FileName);
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null)
{
logger.Info("FileName : " + file.FileName);
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
}
|
mit
|
C#
|
70487d1bd79738a85d315311d5b5d5e5ecd554aa
|
Update QueueExtensionsTests.cs
|
huysentruitw/win-beacon,ghkim69/win-beacon
|
test/WinBeacon.Tests/QueueExtensionsTests.cs
|
test/WinBeacon.Tests/QueueExtensionsTests.cs
|
/*
* Copyright 2015 Huysentruit Wouter
*
* 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 NUnit.Framework;
using WinBeacon.Stack;
namespace WinBeacon.Tests
{
[TestFixture]
public class QueueExtensionsTests
{
[Test]
public void QueueExtensions_DequeueAll()
{
var input = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
byte[] output = queue.DequeueAll();
Assert.AreEqual(input, output);
}
[Test]
public void QueueExtensions_Dequeue_Exact()
{
var input = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
byte[] output = queue.Dequeue(3);
Assert.AreEqual(new byte[] { 0x12, 0x34, 0x56 }, output);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void QueueExtensions_Dequeue_TooMuch()
{
var input = new byte[] { 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
queue.Dequeue(6);
}
[Test]
public void QueueExtensions_Enqueue()
{
var input = new byte[] { 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>();
queue.Enqueue(input);
Assert.AreEqual(input.Length, queue.Count);
Assert.AreEqual(input, queue.DequeueAll());
}
}
}
|
/*
* Copyright 2015 Huysentruit Wouter
*
* 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 NUnit.Framework;
using WinBeacon.Stack;
namespace WinBeacon.Tests
{
[TestFixture]
public class QueueExtensionsTests
{
[Test]
public void QueueExtensions_DequeueAll()
{
var input = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
byte[] output = queue.DequeueAll();
Assert.AreEqual(input, output);
}
[Test]
public void QueueExtensions_Dequeue_Exact()
{
var input = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
byte[] output = queue.Dequeue(3);
Assert.AreEqual(new byte[] { 0x12, 0x34, 0x56 }, output);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void QueueExtensions_Dequeue_TooMuch()
{
var input = new byte[] { 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
queue.Dequeue(6);
}
[Test]
public void QueueExtensions_Enqueue()
{
var input = new byte[] { 0x9A, 0xBC, 0xDE, 0xF0 };
var queue = new Queue<byte>(input);
Assert.AreEqual(input.Length, queue.Count);
Assert.AreEqual(input, queue.DequeueAll());
}
}
}
|
mit
|
C#
|
d3b002a5aa2f7e769dc9b5259af664a51f881ef6
|
Handle dictionary insert race condition.
|
bretcope/BosunReporter.NET,lockwobr/BosunReporter.NET,qed-/BosunReporter.NET
|
BosunReporter/MetricGroup.cs
|
BosunReporter/MetricGroup.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace BosunReporter
{
public sealed class MetricGroup<T> where T : BosunMetric
{
private readonly object _dictionaryLock = new object();
private readonly MetricsCollector _collector;
private readonly string _name;
private readonly Dictionary<string, T> _metrics = new Dictionary<string,T>();
private readonly Func<string, T> _metricFactory;
public string Name { get { return _name; } }
internal MetricGroup(MetricsCollector collector, string name, Func<string, T> metricFactory = null)
{
_collector = collector;
_name = name;
_metricFactory = metricFactory ?? GetDefaultFactory();
}
public T this[string primaryTagValue]
{
get
{
T metric;
if (_metrics.TryGetValue(primaryTagValue, out metric))
return metric;
lock (_dictionaryLock)
{
if (_metrics.TryGetValue(primaryTagValue, out metric))
return metric;
metric = _collector.GetMetric(_name, _metricFactory(primaryTagValue));
_metrics[primaryTagValue] = metric;
return metric;
}
}
}
private Func<string, T> GetDefaultFactory()
{
// get the constructor which takes a single string argument
var constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new []{ typeof(string) }, null);
if (constructor == null)
{
throw new Exception(
String.Format(
"Cannot create a MetricGroup for Type \"{0}\". It does not have a constructor which takes a single string argument. " +
"Either add a constructor with that signature, or use the metricFactory argument to define a custom factory.",
typeof(T).FullName));
}
return s => (T)constructor.Invoke(new[] { (object)s });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace BosunReporter
{
public sealed class MetricGroup<T> where T : BosunMetric
{
private readonly MetricsCollector _collector;
private readonly string _name;
private readonly Dictionary<string, T> _metrics = new Dictionary<string,T>();
private readonly Func<string, T> _metricFactory;
public string Name { get { return _name; } }
internal MetricGroup(MetricsCollector collector, string name, Func<string, T> metricFactory = null)
{
_collector = collector;
_name = name;
_metricFactory = metricFactory ?? GetDefaultFactory();
}
public T this[string primaryTagValue]
{
get
{
T metric;
if (_metrics.TryGetValue(primaryTagValue, out metric))
return metric;
// not going to worry about concurrency here because GetMetric is already thread safe, and indempotent.
metric = _collector.GetMetric(_name, _metricFactory(primaryTagValue));
_metrics[primaryTagValue] = metric;
return metric;
}
}
private Func<string, T> GetDefaultFactory()
{
// get the constructor which takes a single string argument
var constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new []{ typeof(string) }, null);
if (constructor == null)
{
throw new Exception(
String.Format(
"Cannot create a MetricGroup for Type \"{0}\". It does not have a constructor which takes a single string argument. " +
"Either add a constructor with that signature, or use the metricFactory argument to define a custom factory.",
typeof(T).FullName));
}
return s => (T)constructor.Invoke(new[] { (object)s });
}
}
}
|
mit
|
C#
|
1bf21e135fa072ba94653f3c919b8460c43f9e1e
|
Fix infinite recursion in IEnumerable<T>.None() (#69)
|
karelz/GitHubIssues
|
BugReport/Util/Extensions.cs
|
BugReport/Util/Extensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BugReport.Util
{
public static class Extensions
{
public static bool EqualsIgnoreCase(this string str1, string str2)
{
return str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
}
public static bool ContainsIgnoreCase(this IEnumerable<string> strs, string str)
{
return strs.Where(s => s.EqualsIgnoreCase(str)).Any();
}
public static bool None<T>(this IEnumerable<T> items)
{
return !items.Any();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BugReport.Util
{
public static class Extensions
{
public static bool EqualsIgnoreCase(this string str1, string str2)
{
return str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
}
public static bool ContainsIgnoreCase(this IEnumerable<string> strs, string str)
{
return strs.Where(s => s.EqualsIgnoreCase(str)).Any();
}
public static bool None<T>(this IEnumerable<T> items)
{
return items.None();
}
}
}
|
mit
|
C#
|
4b597bbba79a1b9948f9dbd1823736b40dca9397
|
fix RoleConditionEvaluator (#9380)
|
xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2
|
src/OrchardCore.Modules/OrchardCore.Rules/Services/RoleConditionEvaluator.cs
|
src/OrchardCore.Modules/OrchardCore.Rules/Services/RoleConditionEvaluator.cs
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using OrchardCore.Rules.Models;
namespace OrchardCore.Rules.Services
{
public class RoleConditionEvaluator : ConditionEvaluator<RoleCondition>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IdentityOptions _options;
private readonly IConditionOperatorResolver _operatorResolver;
public RoleConditionEvaluator(
IHttpContextAccessor httpContextAccessor,
IOptions<IdentityOptions> options,
IConditionOperatorResolver operatorResolver)
{
_httpContextAccessor = httpContextAccessor;
_options = options.Value;
_operatorResolver = operatorResolver;
}
public override ValueTask<bool> EvaluateAsync(RoleCondition condition)
{
var roleClaimType = _options.ClaimsIdentity.RoleClaimType;
// IsInRole() & HasClaim() are case sensitive.
var operatorComparer = _operatorResolver.GetOperatorComparer(condition.Operation);
// Claim all if the operator is negative
if (condition.Operation is INegateOperator)
{
return (_httpContextAccessor.HttpContext.User?.Claims.Where(c => c.Type == roleClaimType).All(claim =>
operatorComparer.Compare(condition.Operation, claim.Value, condition.Value))
).GetValueOrDefault() ? True : False;
}
return (_httpContextAccessor.HttpContext.User?.Claims.Any(claim =>
claim.Type == roleClaimType &&
operatorComparer.Compare(condition.Operation, claim.Value, condition.Value))
).GetValueOrDefault() ? True : False;
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using OrchardCore.Rules.Models;
namespace OrchardCore.Rules.Services
{
public class RoleConditionEvaluator : ConditionEvaluator<RoleCondition>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IdentityOptions _options;
private readonly IConditionOperatorResolver _operatorResolver;
public RoleConditionEvaluator(
IHttpContextAccessor httpContextAccessor,
IOptions<IdentityOptions> options,
IConditionOperatorResolver operatorResolver)
{
_httpContextAccessor = httpContextAccessor;
_options = options.Value;
_operatorResolver = operatorResolver;
}
public override ValueTask<bool> EvaluateAsync(RoleCondition condition)
{
var roleClaimType = _options.ClaimsIdentity.RoleClaimType;
// IsInRole() & HasClaim() are case sensitive.
var operatorComparer = _operatorResolver.GetOperatorComparer(condition.Operation);
// Claim all if the operator is negative
if (condition.Operation is INegateOperator)
{
return (_httpContextAccessor.HttpContext.User?.Claims.All(claim =>
claim.Type == roleClaimType &&
operatorComparer.Compare(condition.Operation, claim.Value, condition.Value))
).GetValueOrDefault() ? True : False;
}
return (_httpContextAccessor.HttpContext.User?.Claims.Any(claim =>
claim.Type == roleClaimType &&
operatorComparer.Compare(condition.Operation, claim.Value, condition.Value))
).GetValueOrDefault() ? True : False;
}
}
}
|
bsd-3-clause
|
C#
|
91b8f400793ef42d9e781f510474bd199d104092
|
Update user count
|
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
|
src/LondonTravel.Site/Controllers/RegisterController.cs
|
src/LondonTravel.Site/Controllers/RegisterController.cs
|
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using MartinCostello.LondonTravel.Site.Models;
using MartinCostello.LondonTravel.Site.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MartinCostello.LondonTravel.Site.Controllers;
public class RegisterController : Controller
{
private readonly IAccountService _service;
public RegisterController(IAccountService service)
{
_service = service;
}
/// <summary>
/// Gets the result for the <c>/account/register/</c> action.
/// </summary>
/// <returns>
/// The result for the <c>/account/register/</c> action.
/// </returns>
[AllowAnonymous]
[HttpGet]
[Route("account/register", Name = SiteRoutes.Register)]
public async Task<IActionResult> Index()
{
if (User?.Identity?.IsAuthenticated == true)
{
return RedirectToRoute(SiteRoutes.Home);
}
long count = await GetRegisteredUsersCountAsync();
var model = new RegisterViewModel()
{
RegisteredUsers = count,
};
return View(model);
}
private async Task<long> GetRegisteredUsersCountAsync()
{
try
{
long count = await _service.GetUserCountAsync(useCache: true);
// Round down to the nearest thousand.
// Deduct one for "over X,000 users".
return ((count - 1) / 1000) * 1000;
}
#pragma warning disable CA1031
catch (Exception)
#pragma warning restore CA1031
{
// Over 9,500 users as of 22/08/2021
return 9_500;
}
}
}
|
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using MartinCostello.LondonTravel.Site.Models;
using MartinCostello.LondonTravel.Site.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MartinCostello.LondonTravel.Site.Controllers;
public class RegisterController : Controller
{
private readonly IAccountService _service;
public RegisterController(IAccountService service)
{
_service = service;
}
/// <summary>
/// Gets the result for the <c>/account/register/</c> action.
/// </summary>
/// <returns>
/// The result for the <c>/account/register/</c> action.
/// </returns>
[AllowAnonymous]
[HttpGet]
[Route("account/register", Name = SiteRoutes.Register)]
public async Task<IActionResult> Index()
{
if (User?.Identity?.IsAuthenticated == true)
{
return RedirectToRoute(SiteRoutes.Home);
}
long count = await GetRegisteredUsersCountAsync();
var model = new RegisterViewModel()
{
RegisteredUsers = count,
};
return View(model);
}
private async Task<long> GetRegisteredUsersCountAsync()
{
try
{
long count = await _service.GetUserCountAsync(useCache: true);
// Round down to the nearest thousand.
// Deduct one for "over X,000 users".
return ((count - 1) / 1000) * 1000;
}
#pragma warning disable CA1031
catch (Exception)
#pragma warning restore CA1031
{
// Over 7,000 users as of 28/10/2018
return 7_000;
}
}
}
|
apache-2.0
|
C#
|
caf0bd962ea33ae0bb1916fdfcb450b10510d0e0
|
Disable plot buttons until plot is available
|
MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS
|
src/Package/Impl/Plots/PlotWindowCommandController.cs
|
src/Package/Impl/Plots/PlotWindowCommandController.cs
|
using System;
using System.Diagnostics;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller;
namespace Microsoft.VisualStudio.R.Package.Plots {
internal sealed class PlotWindowCommandController : ICommandTarget {
private PlotWindowPane _pane;
public PlotWindowCommandController(PlotWindowPane pane) {
Debug.Assert(pane != null);
_pane = pane;
}
public CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
Debug.Assert(container != null);
if (container.Menu != null) {
container.Menu.Execute(id);
}
return CommandResult.Executed;
}
public void PostProcessInvoke(CommandResult result, Guid group, int id, object inputArg, ref object outputArg) {
}
public CommandStatus Status(Guid group, int id) {
RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
return (container != null && container.Menu != null) ? CommandStatus.SupportedAndEnabled : CommandStatus.Supported;
}
}
}
|
using System;
using System.Diagnostics;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller;
namespace Microsoft.VisualStudio.R.Package.Plots {
internal sealed class PlotWindowCommandController : ICommandTarget {
private PlotWindowPane _pane;
public PlotWindowCommandController(PlotWindowPane pane) {
Debug.Assert(pane != null);
_pane = pane;
}
public CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
Debug.Assert(container != null);
container.Menu.Execute(id);
return CommandResult.Executed;
}
public void PostProcessInvoke(CommandResult result, Guid group, int id, object inputArg, ref object outputArg) {
}
public CommandStatus Status(Guid group, int id) {
return CommandStatus.SupportedAndEnabled;
}
}
}
|
mit
|
C#
|
081ed55d0fb23c971cb2dacc0b93552462036e74
|
Fix tests
|
AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS
|
src/R/Components/Test/Fakes/Wpf/TestThemeUtilities.cs
|
src/R/Components/Test/Fakes/Wpf/TestThemeUtilities.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using Microsoft.R.Wpf.Themes;
using Microsoft.UnitTests.Core.Mef;
namespace Microsoft.R.Components.Test.Fakes.Wpf {
[ExcludeFromCodeCoverage]
[Export(typeof(IThemeUtilities))]
[PartMetadata(PartMetadataAttributeNames.SkipInEditorTestCompositionCatalog, null)]
internal sealed class TestThemeUtilities : IThemeUtilities {
public void SetImageBackgroundColor(DependencyObject o, object themeKey) {}
public void SetThemeScrollBars(DependencyObject o) {}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using Microsoft.R.Wpf.Themes;
namespace Microsoft.R.Components.Test.Fakes.Wpf {
[ExcludeFromCodeCoverage]
[Export(typeof(IThemeUtilities))]
internal sealed class TestThemeUtilities : IThemeUtilities {
public void SetImageBackgroundColor(DependencyObject o, object themeKey) {}
public void SetThemeScrollBars(DependencyObject o) {}
}
}
|
mit
|
C#
|
51f2b523efaf42c229cfdede2c0d78134121084b
|
Remove LSP base from Xaml content type definition to avoid regressing rps
|
mgoertz-msft/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,AmadeusW/roslyn,stephentoub/roslyn,sharwell/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,mavasani/roslyn,bartdesmet/roslyn,heejaechang/roslyn,diryboy/roslyn,jmarolf/roslyn,aelij/roslyn,KevinRansom/roslyn,weltkante/roslyn,mavasani/roslyn,tmat/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,sharwell/roslyn,sharwell/roslyn,tmat/roslyn,tannergooding/roslyn,AmadeusW/roslyn,physhi/roslyn,aelij/roslyn,physhi/roslyn,eriawan/roslyn,KevinRansom/roslyn,diryboy/roslyn,dotnet/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,gafter/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,tmat/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,eriawan/roslyn,aelij/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,jmarolf/roslyn,genlu/roslyn,gafter/roslyn,stephentoub/roslyn,heejaechang/roslyn,dotnet/roslyn,genlu/roslyn,wvdd007/roslyn,genlu/roslyn,brettfo/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,gafter/roslyn,KevinRansom/roslyn,brettfo/roslyn,tannergooding/roslyn
|
src/VisualStudio/Xaml/Impl/XamlStaticTypeDefinitions.cs
|
src/VisualStudio/Xaml/Impl/XamlStaticTypeDefinitions.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Xaml
{
public static class XamlStaticTypeDefinitions
{
/// <summary>
/// Definition of the XAML content type.
/// </summary>
[Export]
[Name(ContentTypeNames.XamlContentType)]
[BaseDefinition("code")]
internal static readonly ContentTypeDefinition XamlContentType;
// Associate .xaml as the Xaml content type.
[Export]
[FileExtension(StringConstants.XamlFileExtension)]
[ContentType(ContentTypeNames.XamlContentType)]
internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension;
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Xaml
{
public static class XamlStaticTypeDefinitions
{
/// <summary>
/// Definition of the XAML content type.
/// </summary>
[Export]
[Name(ContentTypeNames.XamlContentType)]
[BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)]
internal static readonly ContentTypeDefinition XamlContentType;
// Associate .xaml as the Xaml content type.
[Export]
[FileExtension(StringConstants.XamlFileExtension)]
[ContentType(ContentTypeNames.XamlContentType)]
internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension;
}
}
|
mit
|
C#
|
47804cf4de61960013f45259ed1db513fbf409cd
|
Update IFileSystemWatcher to: * Pass through FileChangeTypes when available * Allow clients to watch a directory (in addition to individual files)
|
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn
|
src/OmniSharp.Abstractions/FileWatching/IFileSystemWatcher.cs
|
src/OmniSharp.Abstractions/FileWatching/IFileSystemWatcher.cs
|
using OmniSharp.Models;
using System;
namespace OmniSharp.FileWatching
{
// TODO: Flesh out this API more
public interface IFileSystemWatcher
{
void Watch(string path, Action<string, FileChangeType?> callback);
/// <summary>
/// Called when a file is created, changed, or deleted.
/// </summary>
/// <param name="path">The path to the file</param>
/// <param name="verb">The type of change. Hosts are not required to pass a change type</param>
void TriggerChange(string path, FileChangeType? verb);
void WatchDirectory(string path, Action<string, FileChangeType?> callback);
}
}
|
using System;
namespace OmniSharp.FileWatching
{
// TODO: Flesh out this API more
public interface IFileSystemWatcher
{
void Watch(string path, Action<string> callback);
void TriggerChange(string path);
}
}
|
mit
|
C#
|
661be24fdeed5e71f7bb652cf98512eebbef7b02
|
Update ResourceStub.cs
|
CaptiveAire/Seq.App.YouTrack
|
src/Seq.App.YouTrack/Resources/ResourceStub.cs
|
src/Seq.App.YouTrack/Resources/ResourceStub.cs
|
// Copyright 2014-2019 CaptiveAire Systems
//
// 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.Reflection;
using EmbeddedResources;
namespace Seq.App.YouTrack.Resources
{
public static class TemplateResources
{
static TemplateResources()
{
_resourceLocator = new AssemblyResourceLocator(Assembly.GetExecutingAssembly());
_defaultIssueBodyTemplate = new Lazy<string>(() => GetEmbeddedResource($"{_templateNamespace}.DefaultIssueBodyTemplate.md"));
_defaultIssueSummeryTemplate =
new Lazy<string>(() => GetEmbeddedResource($"{_templateNamespace}.DefaultIssueSummaryTemplate.md"));
}
public static string DefaultIssueBodyTemplate => _defaultIssueBodyTemplate.Value;
public static string DefaultIssueSummaryTemplate => _defaultIssueSummeryTemplate.Value;
static readonly AssemblyResourceLocator _resourceLocator;
static readonly Lazy<string> _defaultIssueBodyTemplate;
static readonly string _templateNamespace = typeof(TemplateResources).Namespace;
static readonly Lazy<string> _defaultIssueSummeryTemplate;
static string GetEmbeddedResource(string name)
{
return new EmbeddedResourceLoader(_resourceLocator).LoadText(name);
}
}
}
|
// Seq.App.YouTrack - Copyright (c) 2019 CaptiveAire
using System;
using System.Reflection;
using EmbeddedResources;
namespace Seq.App.YouTrack.Resources
{
public static class TemplateResources
{
static TemplateResources()
{
_resourceLocator = new AssemblyResourceLocator(Assembly.GetExecutingAssembly());
_defaultIssueBodyTemplate = new Lazy<string>(() => GetEmbeddedResource($"{_templateNamespace}.DefaultIssueBodyTemplate.md"));
_defaultIssueSummeryTemplate =
new Lazy<string>(() => GetEmbeddedResource($"{_templateNamespace}.DefaultIssueSummaryTemplate.md"));
}
public static string DefaultIssueBodyTemplate => _defaultIssueBodyTemplate.Value;
public static string DefaultIssueSummaryTemplate => _defaultIssueSummeryTemplate.Value;
static readonly AssemblyResourceLocator _resourceLocator;
static readonly Lazy<string> _defaultIssueBodyTemplate;
static readonly string _templateNamespace = typeof(TemplateResources).Namespace;
static readonly Lazy<string> _defaultIssueSummeryTemplate;
static string GetEmbeddedResource(string name)
{
return new EmbeddedResourceLoader(_resourceLocator).LoadText(name);
}
}
}
|
apache-2.0
|
C#
|
e32b5f4c37d5f8b95041f30765912443763428c2
|
Change message.
|
googleprojectzero/sandbox-attacksurface-analysis-tools
|
NtApiDotNet/Win32/Security/Buffers/SecurityBufferOut.cs
|
NtApiDotNet/Win32/Security/Buffers/SecurityBufferOut.cs
|
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 NtApiDotNet.Win32.Security.Native;
using System;
namespace NtApiDotNet.Win32.Security.Buffers
{
/// <summary>
/// A security buffer which can only be an output.
/// </summary>
public sealed class SecurityBufferOut : SecurityBuffer
{
private byte[] _array;
private int _size;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">The type of buffer.</param>
/// <param name="size">The size of the output buffer.</param>
public SecurityBufferOut(SecurityBufferType type, int size) : base(type)
{
_size = size;
}
/// <summary>
/// Convert to buffer back to an array.
/// </summary>
/// <returns>The buffer as an array.</returns>
public override byte[] ToArray()
{
if (_array == null)
throw new InvalidOperationException("Can't access buffer until it's been populated.");
return _array;
}
internal override SecBuffer ToBuffer()
{
return new SecBuffer(Type, _size);
}
internal override void FromBuffer(SecBuffer buffer)
{
_array = buffer.ToArray();
_size = _array.Length;
}
}
}
|
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 NtApiDotNet.Win32.Security.Native;
using System;
namespace NtApiDotNet.Win32.Security.Buffers
{
/// <summary>
/// A security buffer which can only be an output.
/// </summary>
public sealed class SecurityBufferOut : SecurityBuffer
{
private byte[] _array;
private int _size;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">The type of buffer.</param>
/// <param name="size">The size of the output buffer.</param>
public SecurityBufferOut(SecurityBufferType type, int size) : base(type)
{
_size = size;
}
/// <summary>
/// Convert to buffer back to an array.
/// </summary>
/// <returns>The buffer as an array.</returns>
public override byte[] ToArray()
{
if (_array == null)
throw new InvalidOperationException("Can't access return until it's been populated.");
return _array;
}
internal override SecBuffer ToBuffer()
{
return new SecBuffer(Type, _size);
}
internal override void FromBuffer(SecBuffer buffer)
{
_array = buffer.ToArray();
_size = _array.Length;
}
}
}
|
apache-2.0
|
C#
|
5064ed1de015a91dada287fbae3b5c246eccba31
|
Allow null expected values for just ignoring the value (todo: maybe allow byte expected values).
|
mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy
|
test/TestApp/TestRunner.cs
|
test/TestApp/TestRunner.cs
|
using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace Manos.Tests {
public class TestRunner {
private bool LoadTest = true;
private Process LoadProcess = null;
private string MANOS_SERVER = "http://localhost:8080";
public static int Main (string [] args)
{
var r = new TestRunner ();
return r.Run ();
}
public TestRunner ()
{
}
public int Run ()
{
try {
RunStreamTests ();
} catch (Exception e) {
Console.WriteLine (e);
return -1;
}
return 0;
}
public void RunStreamTests ()
{
var st = new StreamTests (this);
st.Run ();
}
public void RunTest (string uri, string expected)
{
RunTestInternal (uri, uri, "GET", null, expected);
}
public void RunTest (string uri, string load_uri, string expected)
{
RunTestInternal (uri, load_uri, "GET", null, expected);
}
public void RunTestInternal (string uri, string load_uri, string method, Dictionary<string,string> data, string expected)
{
Console.Write ("RUNNING {0}...", uri);
uri = MANOS_SERVER + uri;
if (LoadTest) {
BeginLoad (uri);
}
var request = (HttpWebRequest) WebRequest.Create (uri);
request.Method = method;
HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception ("Bad status code for uri " + uri + " " + response.StatusCode + ".");
var stream = response.GetResponseStream ();
var reader = new StreamReader (stream);
string result = reader.ReadToEnd ();
if (expected != null && result != expected)
throw new Exception (String.Format ("Expected '{0}' for uri {1} got '{2}'", expected, uri, result));
if (LoadTest) {
WaitForLoad ();
}
Console.WriteLine ("PASSED");
}
private void BeginLoad (string uri)
{
LoadProcess = Process.Start ("ab", String.Format ("-c 50 -n 5000 -d -k {0}", uri));
}
private void WaitForLoad ()
{
try {
LoadProcess.WaitForExit ();
LoadProcess = null;
} catch (Exception e) {
Console.Error.WriteLine (e);
}
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace Manos.Tests {
public class TestRunner {
private bool LoadTest = true;
private Process LoadProcess = null;
private string MANOS_SERVER = "http://localhost:8080";
public static int Main (string [] args)
{
var r = new TestRunner ();
return r.Run ();
}
public TestRunner ()
{
}
public int Run ()
{
try {
RunStreamTests ();
} catch (Exception e) {
Console.WriteLine (e);
return -1;
}
return 0;
}
public void RunStreamTests ()
{
var st = new StreamTests (this);
st.Run ();
}
public void RunTest (string uri, string expected)
{
RunTestInternal (uri, uri, "GET", null, expected);
}
public void RunTest (string uri, string load_uri, string expected)
{
RunTestInternal (uri, load_uri, "GET", null, expected);
}
public void RunTestInternal (string uri, string load_uri, string method, Dictionary<string,string> data, string expected)
{
Console.Write ("RUNNING {0}...", uri);
uri = MANOS_SERVER + uri;
if (LoadTest) {
BeginLoad (uri);
}
var request = (HttpWebRequest) WebRequest.Create (uri);
request.Method = method;
HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception ("Bad status code for uri " + uri + " " + response.StatusCode + ".");
var stream = response.GetResponseStream ();
var reader = new StreamReader (stream);
string result = reader.ReadToEnd ();
if (result != expected)
throw new Exception (String.Format ("Expected '{0}' for uri {1} got '{2}'", expected, uri, result));
if (LoadTest) {
WaitForLoad ();
}
Console.WriteLine ("PASSED");
}
private void BeginLoad (string uri)
{
LoadProcess = Process.Start ("ab", String.Format ("-c 50 -n 5000 -d -k {0}", uri));
}
private void WaitForLoad ()
{
try {
LoadProcess.WaitForExit ();
LoadProcess = null;
} catch (Exception e) {
Console.Error.WriteLine (e);
}
}
}
}
|
mit
|
C#
|
919b6a4a557f0e0c0a1a3178b16a852e56a59de4
|
add arguments support
|
peitaosu/Diplomatist
|
SoundsRecord/win32/SoundsRecord/SoundsRecord/Program.cs
|
SoundsRecord/win32/SoundsRecord/SoundsRecord/Program.cs
|
/* Some Code Fragments from:
1. https://stackoverflow.com/questions/18812224/c-sharp-recording-audio-from-soundcard - Florian R.
*/
using System;
using CSCore.SoundIn;
using CSCore.Codecs.WAV;
using System.Threading;
namespace SoundsRecord
{
class Program
{
static int Main(string[] args)
{
if (args.Length == 0 || args[0] == "-h" || args[0] == "--help")
{
System.Console.WriteLine("Usage:");
System.Console.WriteLine(" SoundsRecord.exe <time/seconds> <output/wav>");
return 1;
}
using (WasapiCapture capture = new WasapiLoopbackCapture())
{
//initialize the selected device for recording
capture.Initialize();
//create a wavewriter to write the data to
using (WaveWriter w = new WaveWriter(args[1], capture.WaveFormat))
{
//setup an eventhandler to receive the recorded data
capture.DataAvailable += (s, e) =>
{
//save the recorded audio
w.Write(e.Data, e.Offset, e.ByteCount);
};
//start recording
capture.Start();
//delay and keep recording
Thread.Sleep(Int32.Parse(args[0]) * 1000);
//stop recording
capture.Stop();
}
}
return 0;
}
}
}
|
/* Some Code Fragments from:
1. https://stackoverflow.com/questions/18812224/c-sharp-recording-audio-from-soundcard - Florian R.
*/
using System;
using CSCore.SoundIn;
using CSCore.Codecs.WAV;
namespace SoundsRecord
{
class Program
{
static void Main(string[] args)
{
using (WasapiCapture capture = new WasapiLoopbackCapture())
{
//initialize the selected device for recording
capture.Initialize();
//create a wavewriter to write the data to
using (WaveWriter w = new WaveWriter("dump.wav", capture.WaveFormat))
{
//setup an eventhandler to receive the recorded data
capture.DataAvailable += (s, e) =>
{
//save the recorded audio
w.Write(e.Data, e.Offset, e.ByteCount);
};
//start recording
capture.Start();
Console.ReadKey();
//stop recording
capture.Stop();
}
}
}
}
}
|
mit
|
C#
|
25c222d60ae0218056dfc5b70182db5c1e5c56ee
|
Add documentation for string extensions.
|
henrikfroehling/TraktApiSharp
|
Source/Lib/TraktApiSharp/Extensions/StringExtensions.cs
|
Source/Lib/TraktApiSharp/Extensions/StringExtensions.cs
|
namespace TraktApiSharp.Extensions
{
using System;
using System.Linq;
/// <summary>Provides helper methods for strings.</summary>
public static class StringExtensions
{
private static readonly char[] DelimiterChars = { ' ', ',', '.', ':', ';', '\n', '\t' };
/// <summary>Converts the given string to a string, in which only the first letter is capitalized.</summary>
/// <param name="value">The string, in which only the first letter should be capitalized.</param>
/// <returns>A string, in which only the first letter is capitalized.</returns>
/// <exception cref="ArgumentException">Thrown, if the given string is null or empty.</exception>
public static string FirstToUpper(this string value)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("value not valid", nameof(value));
var trimmedValue = value.Trim();
if (trimmedValue.Length > 1)
return char.ToUpper(trimmedValue[0]) + trimmedValue.Substring(1).ToLower();
return trimmedValue.ToUpper();
}
/// <summary>Counts the words in a string.</summary>
/// <param name="value">The string, for which the words should be counted.</param>
/// <returns>The number of words in the given string or zero, if the given string is null or empty.</returns>
public static int WordCount(this string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var words = value.Split(DelimiterChars);
var filteredWords = words.Where(s => !string.IsNullOrEmpty(s));
return filteredWords.Count();
}
/// <summary>Returns, whether the given string contains any spaces.</summary>
/// <param name="value">The string, which should be checked.</param>
/// <returns>True, if the given string contains any spaces, otherwise false.</returns>
public static bool ContainsSpace(this string value)
{
return value.Contains(" ");
}
}
}
|
namespace TraktApiSharp.Extensions
{
using System;
using System.Linq;
public static class StringExtensions
{
private static readonly char[] DelimiterChars = { ' ', ',', '.', ':', ';', '\n', '\t' };
public static string FirstToUpper(this string value)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("value not valid", nameof(value));
var trimmedValue = value.Trim();
if (trimmedValue.Length > 1)
return char.ToUpper(trimmedValue[0]) + trimmedValue.Substring(1).ToLower();
return trimmedValue.ToUpper();
}
public static int WordCount(this string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var words = value.Split(DelimiterChars);
var filteredWords = words.Where(s => !string.IsNullOrEmpty(s));
return filteredWords.Count();
}
public static bool ContainsSpace(this string value)
{
return value.Contains(" ");
}
}
}
|
mit
|
C#
|
52bea7e8ebebc3b5c926b4aa1284a1c62bb65f7f
|
update version
|
prodot/ReCommended-Extension
|
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
|
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
|
using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("5.3.2.0")]
[assembly: AssemblyFileVersion("5.3.2")]
|
using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("5.3.1.0")]
[assembly: AssemblyFileVersion("5.3.1")]
|
apache-2.0
|
C#
|
6d9cdb8b1f5e7443a85e362aea1a946f46d43139
|
fix stuff
|
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
|
UnityProject/Assets/Scripts/UI/Net/Elements/NetLabel.cs
|
UnityProject/Assets/Scripts/UI/Net/Elements/NetLabel.cs
|
using System;
using UnityEngine;
using UnityEngine.UI;
///Text label, not modifiable by clients directly
[RequireComponent(typeof(TMPro.TMP_Text))]
[Serializable]
public class NetLabel : NetUIStringElement
{
/// <summary>
/// Invoked when the value synced between client / server is updated.
/// </summary>
[NonSerialized]
public StringEvent OnSyncedValueChanged = new StringEvent();
public override ElementMode InteractionMode => ElementMode.ServerWrite;
public override string Value
{
get
{
if (ElementTMP != null)
{
return (ElementTMP.text);
}
else
{
return (Element.text);
}
}
set
{
externalChange = true;
if (ElementTMP != null)
{
ElementTMP.text = value;
}
else if (Element != null)
{
Element.text = value;
}
externalChange = false;
OnSyncedValueChanged?.Invoke(value);
}
}
private Text element;
public Text Element
{
get
{
if (!element)
{
element = GetComponent<Text>();
}
return element;
}
}
private TMPro.TMP_Text elementTMP;
public TMPro.TMP_Text ElementTMP
{
get
{
if (!elementTMP)
{
elementTMP = GetComponent<TMPro.TMP_Text>();
}
return elementTMP;
}
}
public override void ExecuteServer(ConnectedPlayer subject)
{
}
}
|
using System;
using UnityEngine;
using UnityEngine.UI;
///Text label, not modifiable by clients directly
[RequireComponent(typeof(TMPro.TMP_Text))]
[Serializable]
public class NetLabel : NetUIStringElement
{
/// <summary>
/// Invoked when the value synced between client / server is updated.
/// </summary>
[NonSerialized]
public StringEvent OnSyncedValueChanged = new StringEvent();
public override ElementMode InteractionMode => ElementMode.ServerWrite;
public override string Value
{
get
{
if (ElementTMP != null)
{
return (ElementTMP.text);
}
else
{
return (Element.text);
}
}
set
{
externalChange = true;
if (ElementTMP != null)
{
ElementTMP.text = value;
}
else if (Element != null)
{
Element.text = value;
}
externalChange = false;
OnSyncedValueChanged?.Invoke(Element.text);
}
}
private Text element;
public Text Element
{
get
{
if (!element)
{
element = GetComponent<Text>();
}
return element;
}
}
private TMPro.TMP_Text elementTMP;
public TMPro.TMP_Text ElementTMP
{
get
{
if (!elementTMP)
{
elementTMP = GetComponent<TMPro.TMP_Text>();
}
return elementTMP;
}
}
public override void ExecuteServer(ConnectedPlayer subject)
{
}
}
|
agpl-3.0
|
C#
|
684b3c429395a6db948a481a38acc8c3d35c5145
|
Add assert to test.
|
ryanjfitz/SimpSim.NET
|
SimpSim.NET.Presentation.Tests/OutputViewModelTests.cs
|
SimpSim.NET.Presentation.Tests/OutputViewModelTests.cs
|
using SimpSim.NET.Presentation.ViewModels;
using Xunit;
namespace SimpSim.NET.Presentation.Tests
{
public class OutputViewModelTests
{
[Fact]
public void ClearCommandShouldEmptyOutputWindow()
{
OutputViewModel viewModel = new OutputViewModel(new SimpleSimulator());
viewModel.OutputWindowText = "This is some output text.";
Assert.NotNull(viewModel.OutputWindowText);
viewModel.ClearCommand.Execute(null);
Assert.Null(viewModel.OutputWindowText);
}
}
}
|
using SimpSim.NET.Presentation.ViewModels;
using Xunit;
namespace SimpSim.NET.Presentation.Tests
{
public class OutputViewModelTests
{
[Fact]
public void ClearCommandShouldEmptyOutputWindow()
{
OutputViewModel viewModel = new OutputViewModel(new SimpleSimulator());
viewModel.OutputWindowText = "This is some output text.";
viewModel.ClearCommand.Execute(null);
Assert.Null(viewModel.OutputWindowText);
}
}
}
|
mit
|
C#
|
3d932d8ed61489b98c957ff1990430cc43b10751
|
Fix email regex for account creation to accept all 2-letter domains. Ensure email validation ignores capitalized characters.
|
ethanmoffat/EndlessClient
|
EOLib/Domain/Account/CreateAccountParameterValidator.cs
|
EOLib/Domain/Account/CreateAccountParameterValidator.cs
|
using System.Linq;
using AutomaticTypeMapper;
namespace EOLib.Domain.Account
{
[AutoMappedType]
public class CreateAccountParameterValidator : ICreateAccountParameterValidator
{
private const string ValidEmailRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b";
public bool AccountNameIsNotLongEnough(string account)
{
return account.Length < 4;
}
public bool AccountNameIsTooObvious(string account)
{
return account.Distinct().Count() < 3;
}
public bool PasswordMismatch(string input, string confirm)
{
return input != confirm;
}
public bool PasswordIsTooShort(string password)
{
return password.Length < 6;
}
public bool PasswordIsTooObvious(string password)
{
return password.Distinct().Count() < 3;
}
public bool EmailIsInvalid(string email)
{
return !System.Text.RegularExpressions.Regex.IsMatch(email.ToLowerInvariant(), ValidEmailRegex);
}
}
public interface ICreateAccountParameterValidator
{
bool AccountNameIsNotLongEnough(string account);
bool AccountNameIsTooObvious(string account);
bool PasswordMismatch(string input, string confirm);
bool PasswordIsTooShort(string password);
bool PasswordIsTooObvious(string password);
bool EmailIsInvalid(string email);
}
}
|
using System.Linq;
using AutomaticTypeMapper;
namespace EOLib.Domain.Account
{
[AutoMappedType]
public class CreateAccountParameterValidator : ICreateAccountParameterValidator
{
private const string ValidEmailRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b";
public bool AccountNameIsNotLongEnough(string account)
{
return account.Length < 4;
}
public bool AccountNameIsTooObvious(string account)
{
return account.Distinct().Count() < 3;
}
public bool PasswordMismatch(string input, string confirm)
{
return input != confirm;
}
public bool PasswordIsTooShort(string password)
{
return password.Length < 6;
}
public bool PasswordIsTooObvious(string password)
{
return password.Distinct().Count() < 3;
}
public bool EmailIsInvalid(string email)
{
return !System.Text.RegularExpressions.Regex.IsMatch(email, ValidEmailRegex);
}
}
public interface ICreateAccountParameterValidator
{
bool AccountNameIsNotLongEnough(string account);
bool AccountNameIsTooObvious(string account);
bool PasswordMismatch(string input, string confirm);
bool PasswordIsTooShort(string password);
bool PasswordIsTooObvious(string password);
bool EmailIsInvalid(string email);
}
}
|
mit
|
C#
|
ae4a6170a2831ed669ecdb19aad9900a410f5c6c
|
Fix typo in NetCoreNUnit_SignIn_WithInvalidPassword test comment
|
atata-framework/atata-samples
|
NetCore.NUnit/AtataSamples.NetCore.NUnit/SignInTests.cs
|
NetCore.NUnit/AtataSamples.NetCore.NUnit/SignInTests.cs
|
using Atata;
using NUnit.Framework;
namespace AtataSamples.NetCore.NUnit
{
public class SignInTests : UITestFixture
{
[Test]
public void NetCoreNUnit_SignIn()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("abc123").
SignIn.ClickAndGo().
Heading.Should.Equal("Users"); // Verify that we are navigated to "Users" page.
}
[Test]
public void NetCoreNUnit_SignIn_WithInvalidPassword()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("WRONGPASSWORD").
SignIn.Click().
Heading.Should.Equal("Sign In"). // Verify that we are still on "Sign In" page.
Content.Should.Contain("Password or Email is invalid"); // Verify validation message.
}
}
}
|
using Atata;
using NUnit.Framework;
namespace AtataSamples.NetCore.NUnit
{
public class SignInTests : UITestFixture
{
[Test]
public void NetCoreNUnit_SignIn()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("abc123").
SignIn.ClickAndGo().
Heading.Should.Equal("Users"); // Verify that we are navigated to "Users" page.
}
[Test]
public void NetCoreNUnit_SignIn_WithInvalidPassword()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("WRONGPASSWORD").
SignIn.Click().
Heading.Should.Equal("Sign In"). // Verify that we are still on "Sing In" page.
Content.Should.Contain("Password or Email is invalid"); // Verify validation message.
}
}
}
|
apache-2.0
|
C#
|
7568c47232263e7d10af42410ef78594ceae436a
|
Fix :bug:
|
Zalodu/Schedutalk,Zalodu/Schedutalk
|
Schedutalk/Schedutalk/Schedutalk/Logic/HttpRequestor.cs
|
Schedutalk/Schedutalk/Schedutalk/Logic/HttpRequestor.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.Logic
{
class HttpRequestor
{
public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input)
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = requestTask(input);
var response = httpClient.SendAsync(request);
var result = await response.Result.Content.ReadAsStringAsync();
return result;
}
public string getJSONAsString(Func<string, HttpRequestMessage> requestTask, string placeName)
{
Task<string> task = getHttpRequestAsString(requestTask, placeName);
task.Wait();
//Format string
string replacement = task.Result;
if (0 == replacement[0].CompareTo('[')) replacement = replacement.Substring(1);
if (0 == replacement[replacement.Length - 1].CompareTo(']')) replacement = replacement.Remove(replacement.Length - 1);
return replacement;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.Logic
{
class HttpRequestor
{
public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input)
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = requestTask(input);
var response = httpClient.SendAsync(request);
var result = await response.Result.Content.ReadAsStringAsync();
return result;
}
public string getJSONAsString(Func<string, HttpRequestMessage> requestTask, string placeName)
{
Task<string> task = getHttpRequestAsString(requestTask, "E2");
task.Wait();
//Format string
string replacement = task.Result;
if (0 == replacement[0].CompareTo('[')) replacement = replacement.Substring(1);
if (0 == replacement[replacement.Length - 1].CompareTo(']')) replacement = replacement.Remove(replacement.Length - 1);
return replacement;
}
}
}
|
mit
|
C#
|
f2d229855d520edb35fb07db14bd2d2bafe90aed
|
Update assembly version.
|
christophediericx/ArduinoSketchUploader
|
Source/ArduinoSketchUploader/Properties/AssemblyInfo.cs
|
Source/ArduinoSketchUploader/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("ArduinoSketchUploader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArduinoSketchUploader")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0eaba44b-b93e-4ded-805a-f650d7eab091")]
// 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("2.2.0.0")]
[assembly: AssemblyFileVersion("2.2.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("ArduinoSketchUploader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArduinoSketchUploader")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0eaba44b-b93e-4ded-805a-f650d7eab091")]
// 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("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
|
mit
|
C#
|
9d4c26f37536cf50fe2b367a5a9d9e317aca9909
|
remove unused model property
|
mejas/UserManagementApplication
|
UserManagementApplication.Client.Models/SessionModel.cs
|
UserManagementApplication.Client.Models/SessionModel.cs
|
using UserManagementApplication.Client.Models.ServiceProxy;
using UserManagementApplication.Common.Security;
using UserManagementApplication.Remoting.Data;
using UserManagementApplication.Remoting.Data.Request;
namespace UserManagementApplication.Client.Models
{
public class SessionModel : ClientModel
{
#region Properties
protected SessionServiceProxy SessionProxy { get; set; }
#endregion
#region Constructors
public SessionModel()
{
SessionProxy = new SessionServiceProxy();
}
#endregion
#region Methods
public UserSession Login(string username, string password)
{
LogonRequest logonRequest = new LogonRequest()
{
Username = username,
Password = new HashGenerator().GenerateHash(password)
};
return InvokeMethod(() => SessionProxy.Logon(logonRequest));
}
public void Logout(UserSession sessionToken)
{
InvokeMethod(() => SessionProxy.Logoff(sessionToken));
}
public void ForceLogout(UserSession userSession, User user)
{
InvokeMethod(() => SessionProxy.TerminateSession(userSession, user));
}
#endregion
}
}
|
using UserManagementApplication.Client.Models.ServiceProxy;
using UserManagementApplication.Common.Security;
using UserManagementApplication.Remoting.Data;
using UserManagementApplication.Remoting.Data.Request;
namespace UserManagementApplication.Client.Models
{
public class SessionModel : ClientModel
{
#region Properties
protected string SessionToken { get; set; }
protected SessionServiceProxy SessionProxy { get; set; }
#endregion
#region Constructors
public SessionModel()
{
SessionProxy = new SessionServiceProxy();
}
#endregion
#region Methods
public UserSession Login(string username, string password)
{
LogonRequest logonRequest = new LogonRequest()
{
Username = username,
Password = new HashGenerator().GenerateHash(password)
};
return InvokeMethod(() => SessionProxy.Logon(logonRequest));
}
public void Logout(UserSession sessionToken)
{
InvokeMethod(() => SessionProxy.Logoff(sessionToken));
}
public void ForceLogout(UserSession userSession, User user)
{
InvokeMethod(() => SessionProxy.TerminateSession(userSession, user));
}
#endregion
}
}
|
mit
|
C#
|
91c1dbbae56fd5a5727c4992c8745773145b613e
|
Update GoogleAnalyticsPlatform.cs
|
KSemenenko/GoogleAnalyticsForXamarinForms,KSemenenko/Google-Analytics-for-Xamarin-Forms
|
Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.Android/GoogleAnalyticsPlatform.cs
|
Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.Android/GoogleAnalyticsPlatform.cs
|
using System;
using System.Threading;
using Android.Runtime;
namespace Plugin.GoogleAnalytics
{
public partial class GoogleAnalytics
{
static GoogleAnalytics()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
}
private static void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
if (!Current.Config.ReportUncaughtExceptions)
return;
Current.Tracker.SendException(e.Exception, true);
Thread.Sleep(1000); //delay
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!Current.Config.ReportUncaughtExceptions)
return;
Current.Tracker.SendException(e.ExceptionObject as Exception, true);
}
}
}
|
using System;
using System.Threading;
using Android.Runtime;
namespace Plugin.GoogleAnalytics
{
public partial class GoogleAnalytics
{
static GoogleAnalytics()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
}
private static void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
Current.Tracker.SendException(e.Exception, true);
Thread.Sleep(1000); //delay
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Current.Tracker.SendException(e.ExceptionObject as Exception, true);
}
}
}
|
mit
|
C#
|
b26d742092da9007bfb1b104799b8f2040407db3
|
Update SelectListBoxItemOnPointerMovedBehavior.cs
|
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
|
src/Avalonia.Xaml.Interactions/Custom/SelectListBoxItemOnPointerMovedBehavior.cs
|
src/Avalonia.Xaml.Interactions/Custom/SelectListBoxItemOnPointerMovedBehavior.cs
|
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// Sets <see cref="ListBoxItem.IsSelected"/> property to true of the associated <see cref="ListBoxItem"/> control on <see cref="InputElement.PointerMoved"/> event.
/// </summary>
public class SelectListBoxItemOnPointerMovedBehavior : Behavior<Control>
{
/// <summary>
/// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>.
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved += PointerMoved;
}
}
/// <summary>
/// Called when the behavior is being detached from its <see cref="Behavior.AssociatedObject"/>.
/// </summary>
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved -= PointerMoved;
}
}
private void PointerMoved(object? sender, PointerEventArgs args)
{
if (AssociatedObject is { Parent: ListBoxItem item })
{
item.IsSelected = true;
item.Focus();
}
}
}
|
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// Sets <see cref="ListBoxItem.IsSelected"/> property to true of the associated <see cref="ListBoxItem"/> control on <see cref="InputElement.PointerMoved"/> event.
/// </summary>
public class SelectListBoxItemOnPointerMovedBehavior : Behavior<Control>
{
/// <summary>
/// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>.
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved += PointerMoved;
}
}
/// <summary>
/// Called when the behavior is being detached from its <see cref="Behavior.AssociatedObject"/>.
/// </summary>
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved -= PointerMoved;
}
}
private void PointerMoved(object? sender, PointerEventArgs args)
{
if (AssociatedObject is { } && AssociatedObject.Parent is ListBoxItem item)
{
item.IsSelected = true;
item.Focus();
}
}
}
|
mit
|
C#
|
385f863c44b2b4a289b224bd21ab06942e588698
|
remove view engine
|
angel75013/SellAndBuy,angel75013/SellAndBuy,angel75013/SellAndBuy
|
SellAndBuy/SellAndBuy.Web/Global.asax.cs
|
SellAndBuy/SellAndBuy.Web/Global.asax.cs
|
using SellAndBuy.Data;
using SellAndBuy.Data.Migrations;
using SellAndBuy.Web.App_Start;
using System.Data.Entity;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace SellAndBuy.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SqlDbContext, Configuration>());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var mapper = new AutoMapperConfig();
mapper.Execute(Assembly.GetExecutingAssembly());
}
}
}
|
using SellAndBuy.Data;
using SellAndBuy.Data.Migrations;
using SellAndBuy.Web.App_Start;
using System.Data.Entity;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace SellAndBuy.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SqlDbContext, Configuration>());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var mapper = new AutoMapperConfig();
mapper.Execute(Assembly.GetExecutingAssembly());
}
}
}
|
mit
|
C#
|
c933cc2f631aa9ff1c19f620ec90a09dfc917df7
|
Add region to IndicatorControl
|
HavenDV/ImprovedControls,HavenDV/ImprovedControls,HavenDV/ImprovedControls,HavenDV/ImprovedControls
|
SliderControlLibrary/IndicatorControl.cs
|
SliderControlLibrary/IndicatorControl.cs
|
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace T3000Controls
{
public partial class IndicatorControl : UserControl
{
public string SliderName
{
get { return nameLabel.Text; }
set { nameLabel.Text = value; }
}
public string SliderValue
{
get { return valueLabel.Text; }
set { valueLabel.Text = value; }
}
public IndicatorControl()
{
InitializeComponent();
}
private void Slider_Paint(object sender, PaintEventArgs e)
{
var polygonWidth = Height;
var polygon = new Point[] {
new Point(0, 0),
new Point(Width - polygonWidth, 0),
new Point(Width, Height / 2),
new Point(Width - polygonWidth, Height - 1),
new Point(0, Height - 1),
};
using (var brush = new SolidBrush(Color.GreenYellow))
{
e.Graphics.FillPolygon(brush, polygon);
}
using (var pen = new Pen(Color.Black, 1))
{
e.Graphics.DrawPolygon(pen, polygon);
}
for (var i = 2; i < polygon.Length; ++i)
{
polygon[i].Y += 1;
}
for (var i = 1; i < 4; ++i)
{
polygon[i].X += 1;
}
var path = new GraphicsPath();
path.AddPolygon(polygon);
Region = new Region(path);
}
}
}
|
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace T3000Controls
{
public partial class IndicatorControl : UserControl
{
public string SliderName
{
get { return nameLabel.Text; }
set { nameLabel.Text = value; }
}
public string SliderValue
{
get { return valueLabel.Text; }
set { valueLabel.Text = value; }
}
public IndicatorControl()
{
InitializeComponent();
}
private void Slider_Paint(object sender, PaintEventArgs e)
{
var polygonWidth = Height;
var polygon = new Point[] {
new Point(0, 0),
new Point(Width - polygonWidth, 0),
new Point(Width, Height / 2),
new Point(Width - polygonWidth, Height - 1),
new Point(0, Height - 1),
};
using (var brush = new SolidBrush(Color.GreenYellow))
{
e.Graphics.FillPolygon(brush, polygon);
}
using (var pen = new Pen(Color.Black, 1))
{
e.Graphics.DrawPolygon(pen, polygon);
}
}
}
}
|
lgpl-2.1
|
C#
|
fa28a0a6710a788e0b72dccb99c7d96051285a9b
|
Disable the CC0020 code fix when it would cause a syntax error
|
gerryaobrien/code-cracker,dlsteuer/code-cracker,jhancock93/code-cracker,adraut/code-cracker,dmgandini/code-cracker,jwooley/code-cracker,akamud/code-cracker,carloscds/code-cracker,AlbertoMonteiro/code-cracker,andrecarlucci/code-cracker,eirielson/code-cracker,baks/code-cracker,code-cracker/code-cracker,giggio/code-cracker,kindermannhubert/code-cracker,ElemarJR/code-cracker,modulexcite/code-cracker,code-cracker/code-cracker,carloscds/code-cracker,thorgeirk11/code-cracker,robsonalves/code-cracker,eriawan/code-cracker,f14n/code-cracker,GuilhermeSa/code-cracker,caioadz/code-cracker,thomaslevesque/code-cracker
|
src/CodeCracker/ConvertSimpleLambdaExpressionToMethodInvocationFixProvider.cs
|
src/CodeCracker/ConvertSimpleLambdaExpressionToMethodInvocationFixProvider.cs
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace CodeCracker
{
[ExportCodeFixProvider("ConvertSimpleLambdaExpressionToMethodInvocationFixProvider", LanguageNames.CSharp), Shared]
public class ConvertSimpleLambdaExpressionToMethodInvocationFixProvider
:CodeFixProvider
{
public sealed override ImmutableArray<string> GetFixableDiagnosticIds()
{
return ImmutableArray.Create(ConvertSimpleLambdaExpressionToMethodInvocationAnalizer.DiagnosticId);
}
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task ComputeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var lambda = root.FindToken(diagnosticSpan.Start).Parent
.AncestorsAndSelf().OfType<SimpleLambdaExpressionSyntax>().First();
var methodInvoke = lambda.Body as InvocationExpressionSyntax;
var methodName = methodInvoke.Expression as IdentifierNameSyntax;
root = root.ReplaceNode(lambda as ExpressionSyntax, methodName as ExpressionSyntax);
var newDocument = context.Document.WithSyntaxRoot(root);
// verify that the conversion is correct
var newSemanticModel = await newDocument.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
var newRoot = await newDocument.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var identifierToken = newRoot.FindToken(diagnosticSpan.Start);
var newDiagnostics = newSemanticModel.Compilation.GetDiagnostics(context.CancellationToken);
var diagnosticErrors = newDiagnostics.WhereAsArray(i => i.Severity == DiagnosticSeverity.Error);
if (diagnosticErrors.Any(error => LocationOverlapsIdentifierName(identifierToken.Parent, error)))
return;
context.RegisterFix(CodeAction.Create(
"Use method name instead of lambda expression when signatures match",
newDocument), diagnostic);
}
private bool LocationOverlapsIdentifierName(SyntaxNode node, Diagnostic error)
{
var errorLocation = error.Location;
if (errorLocation == null)
return false;
var nodeLocation = node.GetLocation();
if (nodeLocation == null)
return false;
if (errorLocation.SourceTree != nodeLocation.SourceTree)
return false;
return nodeLocation.SourceSpan.OverlapsWith(errorLocation.SourceSpan);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace CodeCracker
{
[ExportCodeFixProvider("ConvertSimpleLambdaExpressionToMethodInvocationFixProvider", LanguageNames.CSharp), Shared]
public class ConvertSimpleLambdaExpressionToMethodInvocationFixProvider
:CodeFixProvider
{
public sealed override ImmutableArray<string> GetFixableDiagnosticIds()
{
return ImmutableArray.Create(ConvertSimpleLambdaExpressionToMethodInvocationAnalizer.DiagnosticId);
}
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task ComputeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var lambda = root.FindToken(diagnosticSpan.Start).Parent
.AncestorsAndSelf().OfType<SimpleLambdaExpressionSyntax>().First();
var methodInvoke = lambda.Body as InvocationExpressionSyntax;
var methodName = methodInvoke.Expression as IdentifierNameSyntax;
root = root.ReplaceNode(lambda as ExpressionSyntax, methodName as ExpressionSyntax);
var newDocument = context.Document.WithSyntaxRoot(root);
context.RegisterFix(CodeAction.Create(
"Use method name instead of lambda expression when signatures match",
newDocument), diagnostic);
}
}
}
|
apache-2.0
|
C#
|
fa702ff6ef53ce483c7b87fb6720911fe6267ccc
|
Update AddSignalRCore to respect user registered services (#2434)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Microsoft.AspNetCore.SignalR.Core/SignalRDependencyInjectionExtensions.cs
|
src/Microsoft.AspNetCore.SignalR.Core/SignalRDependencyInjectionExtensions.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for <see cref="IServiceCollection"/>.
/// </summary>
public static class SignalRDependencyInjectionExtensions
{
/// <summary>
/// Adds the minimum essential SignalR services to the specified <see cref="IServiceCollection" />. Additional services
/// must be added separately using the <see cref="ISignalRServerBuilder"/> returned from this method.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <returns>An <see cref="ISignalRServerBuilder"/> that can be used to further configure the SignalR services.</returns>
public static ISignalRServerBuilder AddSignalRCore(this IServiceCollection services)
{
services.AddSingleton<SignalRCoreMarkerService>();
services.TryAddSingleton(typeof(HubLifetimeManager<>), typeof(DefaultHubLifetimeManager<>));
services.TryAddSingleton(typeof(IHubProtocolResolver), typeof(DefaultHubProtocolResolver));
services.TryAddSingleton(typeof(IHubContext<>), typeof(HubContext<>));
services.TryAddSingleton(typeof(IHubContext<,>), typeof(HubContext<,>));
services.TryAddSingleton(typeof(HubConnectionHandler<>), typeof(HubConnectionHandler<>));
services.TryAddSingleton(typeof(IUserIdProvider), typeof(DefaultUserIdProvider));
services.TryAddSingleton(typeof(HubDispatcher<>), typeof(DefaultHubDispatcher<>));
services.TryAddScoped(typeof(IHubActivator<>), typeof(DefaultHubActivator<>));
services.AddAuthorization();
var builder = new SignalRServerBuilder(services);
builder.AddJsonProtocol();
return builder;
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Internal;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for <see cref="IServiceCollection"/>.
/// </summary>
public static class SignalRDependencyInjectionExtensions
{
/// <summary>
/// Adds the minimum essential SignalR services to the specified <see cref="IServiceCollection" />. Additional services
/// must be added separately using the <see cref="ISignalRServerBuilder"/> returned from this method.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <returns>An <see cref="ISignalRServerBuilder"/> that can be used to further configure the SignalR services.</returns>
public static ISignalRServerBuilder AddSignalRCore(this IServiceCollection services)
{
services.AddSingleton<SignalRCoreMarkerService>();
services.AddSingleton(typeof(HubLifetimeManager<>), typeof(DefaultHubLifetimeManager<>));
services.AddSingleton(typeof(IHubProtocolResolver), typeof(DefaultHubProtocolResolver));
services.AddSingleton(typeof(IHubContext<>), typeof(HubContext<>));
services.AddSingleton(typeof(IHubContext<,>), typeof(HubContext<,>));
services.AddSingleton(typeof(HubConnectionHandler<>), typeof(HubConnectionHandler<>));
services.AddSingleton(typeof(IUserIdProvider), typeof(DefaultUserIdProvider));
services.AddSingleton(typeof(HubDispatcher<>), typeof(DefaultHubDispatcher<>));
services.AddScoped(typeof(IHubActivator<>), typeof(DefaultHubActivator<>));
services.AddAuthorization();
var builder = new SignalRServerBuilder(services);
builder.AddJsonProtocol();
return builder;
}
}
}
|
apache-2.0
|
C#
|
4c61047e9b29497f01633c579cfb2dc7a2784428
|
Fix large notification HTML overflowing CEF buffer and silently crashing
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Browser/Handling/ResourceHandlerNotification.cs
|
Browser/Handling/ResourceHandlerNotification.cs
|
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using CefSharp;
namespace TweetDuck.Browser.Handling{
sealed class ResourceHandlerNotification : IResourceHandler{
private readonly NameValueCollection headers = new NameValueCollection(0);
private MemoryStream dataIn;
public void SetHTML(string html){
dataIn?.Dispose();
dataIn = ResourceHandler.GetMemoryStream(html, Encoding.UTF8);
}
public void Dispose(){
if (dataIn != null){
dataIn.Dispose();
dataIn = null;
}
}
bool IResourceHandler.ProcessRequest(IRequest request, ICallback callback){
callback.Continue();
return true;
}
void IResourceHandler.GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl){
redirectUrl = null;
response.MimeType = "text/html";
response.StatusCode = 200;
response.StatusText = "OK";
response.ResponseHeaders = headers;
responseLength = dataIn?.Length ?? -1;
}
bool IResourceHandler.ReadResponse(Stream dataOut, out int bytesRead, ICallback callback){
callback.Dispose();
try{
byte[] buffer = new byte[Math.Min(dataIn.Length, dataOut.Length)];
int length = buffer.Length;
dataIn.Read(buffer, 0, length);
dataOut.Write(buffer, 0, length);
bytesRead = length;
return true;
}catch{ // catch IOException, possibly NullReferenceException if dataIn is null
bytesRead = 0;
return false;
}
}
bool IResourceHandler.CanGetCookie(Cookie cookie){
return true;
}
bool IResourceHandler.CanSetCookie(Cookie cookie){
return true;
}
void IResourceHandler.Cancel(){}
}
}
|
using System.Collections.Specialized;
using System.IO;
using System.Text;
using CefSharp;
namespace TweetDuck.Browser.Handling{
sealed class ResourceHandlerNotification : IResourceHandler{
private readonly NameValueCollection headers = new NameValueCollection(0);
private MemoryStream dataIn;
public void SetHTML(string html){
dataIn?.Dispose();
dataIn = ResourceHandler.GetMemoryStream(html, Encoding.UTF8);
}
public void Dispose(){
if (dataIn != null){
dataIn.Dispose();
dataIn = null;
}
}
bool IResourceHandler.ProcessRequest(IRequest request, ICallback callback){
callback.Continue();
return true;
}
void IResourceHandler.GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl){
redirectUrl = null;
response.MimeType = "text/html";
response.StatusCode = 200;
response.StatusText = "OK";
response.ResponseHeaders = headers;
responseLength = dataIn?.Length ?? -1;
}
bool IResourceHandler.ReadResponse(Stream dataOut, out int bytesRead, ICallback callback){
callback.Dispose();
try{
int length = (int)dataIn.Length;
dataIn.CopyTo(dataOut, length);
bytesRead = length;
return true;
}catch{ // catch IOException, possibly NullReferenceException if dataIn is null
bytesRead = 0;
return false;
}
}
bool IResourceHandler.CanGetCookie(Cookie cookie){
return true;
}
bool IResourceHandler.CanSetCookie(Cookie cookie){
return true;
}
void IResourceHandler.Cancel(){}
}
}
|
mit
|
C#
|
fc7f3b13a6c5aba23aa910917d9700e39e780889
|
add task attributes
|
exercism/xcsharp,exercism/xcsharp
|
exercises/concept/log-levels/LogLevelsTests.cs
|
exercises/concept/log-levels/LogLevelsTests.cs
|
using Xunit;
using Exercism.Tests;
public class LogLineTests
{
[Fact]
[Task(1)]
public void Error_message()
{
Assert.Equal("Stack overflow", LogLine.Message("[ERROR]: Stack overflow"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(1)]
public void Warning_message()
{
Assert.Equal("Disk almost full", LogLine.Message("[WARNING]: Disk almost full"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(1)]
public void Info_message()
{
Assert.Equal("File moved", LogLine.Message("[INFO]: File moved"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(1)]
public void Message_with_leading_and_trailing_white_space()
{
Assert.Equal("Timezone not set", LogLine.Message("[WARNING]: \tTimezone not set \r\n"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(2)]
public void Error_log_level()
{
Assert.Equal("error", LogLine.LogLevel("[ERROR]: Disk full"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(2)]
public void Warning_log_level()
{
Assert.Equal("warning", LogLine.LogLevel("[WARNING]: Unsafe password"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(2)]
public void Info_log_level()
{
Assert.Equal("info", LogLine.LogLevel("[INFO]: Timezone changed"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(3)]
public void Error_reformat()
{
Assert.Equal("Segmentation fault (error)", LogLine.Reformat("[ERROR]: Segmentation fault"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(3)]
public void Warning_reformat()
{
Assert.Equal("Decreased performance (warning)", LogLine.Reformat("[WARNING]: Decreased performance"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(3)]
public void Info_reformat()
{
Assert.Equal("Disk defragmented (info)", LogLine.Reformat("[INFO]: Disk defragmented"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
[Task(3)]
public void Reformat_with_leading_and_trailing_white_space()
{
Assert.Equal("Corrupt disk (error)", LogLine.Reformat("[ERROR]: \t Corrupt disk\t \t \r\n"));
}
}
|
using Xunit;
using Exercism.Tests;
public class LogLineTests
{
[Fact]
public void Error_message()
{
Assert.Equal("Stack overflow", LogLine.Message("[ERROR]: Stack overflow"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Warning_message()
{
Assert.Equal("Disk almost full", LogLine.Message("[WARNING]: Disk almost full"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Info_message()
{
Assert.Equal("File moved", LogLine.Message("[INFO]: File moved"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Message_with_leading_and_trailing_white_space()
{
Assert.Equal("Timezone not set", LogLine.Message("[WARNING]: \tTimezone not set \r\n"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Error_log_level()
{
Assert.Equal("error", LogLine.LogLevel("[ERROR]: Disk full"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Warning_log_level()
{
Assert.Equal("warning", LogLine.LogLevel("[WARNING]: Unsafe password"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Info_log_level()
{
Assert.Equal("info", LogLine.LogLevel("[INFO]: Timezone changed"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Error_reformat()
{
Assert.Equal("Segmentation fault (error)", LogLine.Reformat("[ERROR]: Segmentation fault"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Warning_reformat()
{
Assert.Equal("Decreased performance (warning)", LogLine.Reformat("[WARNING]: Decreased performance"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Info_reformat()
{
Assert.Equal("Disk defragmented (info)", LogLine.Reformat("[INFO]: Disk defragmented"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Reformat_with_leading_and_trailing_white_space()
{
Assert.Equal("Corrupt disk (error)", LogLine.Reformat("[ERROR]: \t Corrupt disk\t \t \r\n"));
}
}
|
mit
|
C#
|
8a3742b1f955509d72806e1e686a98570f164135
|
Add virtual methods to basicPage.cs for overriding.
|
wangjun/windows-app,wangjun/windows-app
|
wallabag/wallabag.Shared/Common/basicPage.cs
|
wallabag/wallabag.Shared/Common/basicPage.cs
|
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace wallabag.Common
{
public class basicPage : Page
{
public NavigationHelper navigationHelper;
private const string ViewModelPageKey = "ViewModel";
public basicPage()
{
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState.Add(ViewModelPageKey, this.DataContext);
SaveState(e);
}
void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
if (e.PageState != null && e.PageState.ContainsKey(ViewModelPageKey))
{
this.DataContext = e.PageState[ViewModelPageKey];
}
LoadState(e);
}
protected virtual void LoadState(LoadStateEventArgs e) { }
protected virtual void SaveState(SaveStateEventArgs e) { }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
}
}
|
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace wallabag.Common
{
public class basicPage : Page
{
public NavigationHelper navigationHelper;
private const string ViewModelPageKey = "ViewModel";
public basicPage()
{
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState.Add(ViewModelPageKey, this.DataContext);
}
void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
if (e.PageState != null && e.PageState.ContainsKey(ViewModelPageKey))
{
this.DataContext = e.PageState[ViewModelPageKey];
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
}
}
|
mit
|
C#
|
b6c2e13fe7e4eb2b6b6e65683778fb80d9a8d2b1
|
Update assembly info
|
Hertizch/FactorioSupervisor
|
FactorioSupervisor/Properties/AssemblyInfo.cs
|
FactorioSupervisor/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("Factorio Supervisor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Factorio Supervisor")]
[assembly: AssemblyCopyright("MIT")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.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("Factorio Supervisor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FactorioSupervisor")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//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.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
6fee280aafe087464988321e5b87fdd2d3d1a17a
|
Enable normal tests again.
|
tgiphil/Cosmos,trivalik/Cosmos,fanoI/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,trivalik/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,tgiphil/Cosmos,trivalik/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos
|
Users/Matthijs/DebugCompiler/MyEngine.cs
|
Users/Matthijs/DebugCompiler/MyEngine.cs
|
using System;
using System.IO;
using Cosmos.Build.Common;
using Cosmos.TestRunner.Core;
using NUnit.Framework;
namespace DebugCompiler
{
[TestFixture]
public class RunKernels
{
[TestCaseSource(typeof(MySource), nameof(MySource.ProvideData))]
public void Test(Type kernelToRun)
{
Environment.CurrentDirectory = Path.GetDirectoryName(typeof(RunKernels).Assembly.Location);
var xEngine = new Engine();
// Sets the time before an error is registered. For example if set to 60 then if a kernel runs for more than 60 seconds then
// that kernel will be marked as a failure and terminated
xEngine.AllowedSecondsInKernel = 300;
// If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are run.
xEngine.RunTargets.Add(RunTargetEnum.Bochs);
//xEngine.StartBochsDebugGui = false;
//xEngine.RunWithGDB = true;
// If you're working on the compiler (or other lower parts), you can choose to run the compiler in process
// one thing to keep in mind though, is that this only works with 1 kernel at a time!
xEngine.RunIL2CPUInProcess = true;
xEngine.TraceAssembliesLevel = TraceAssemblies.User;
xEngine.EnableStackCorruptionChecks = true;
xEngine.StackCorruptionChecksLevel = StackCorruptionDetectionLevel.AllInstructions;
// Select kernels to be tested by adding them to the engine
xEngine.AddKernel(kernelToRun.Assembly.Location);
xEngine.OutputHandler = new TestOutputHandler();
Assert.IsTrue(xEngine.Execute());
}
private class TestOutputHandler : OutputHandlerFullTextBase
{
protected override void Log(string message)
{
TestContext.WriteLine(String.Concat(DateTime.Now.ToString("hh:mm:ss.ffffff "), new String(' ', mLogLevel * 2), message));
}
}
}
}
|
using System;
using System.IO;
using Cosmos.Build.Common;
using Cosmos.TestRunner.Core;
using NUnit.Framework;
namespace DebugCompiler
{
[TestFixture]
public class RunKernels
{
[TestCaseSource(typeof(MySource), nameof(MySource.ProvideData))]
public void Test(Type kernelToRun)
{
Assert.Fail();
Environment.CurrentDirectory = Path.GetDirectoryName(typeof(RunKernels).Assembly.Location);
var xEngine = new Engine();
// Sets the time before an error is registered. For example if set to 60 then if a kernel runs for more than 60 seconds then
// that kernel will be marked as a failure and terminated
xEngine.AllowedSecondsInKernel = 300;
// If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are run.
xEngine.RunTargets.Add(RunTargetEnum.Bochs);
//xEngine.StartBochsDebugGui = false;
//xEngine.RunWithGDB = true;
// If you're working on the compiler (or other lower parts), you can choose to run the compiler in process
// one thing to keep in mind though, is that this only works with 1 kernel at a time!
xEngine.RunIL2CPUInProcess = true;
xEngine.TraceAssembliesLevel = TraceAssemblies.User;
xEngine.EnableStackCorruptionChecks = true;
xEngine.StackCorruptionChecksLevel = StackCorruptionDetectionLevel.AllInstructions;
// Select kernels to be tested by adding them to the engine
xEngine.AddKernel(kernelToRun.Assembly.Location);
xEngine.OutputHandler = new TestOutputHandler();
Assert.IsTrue(xEngine.Execute());
}
private class TestOutputHandler : OutputHandlerFullTextBase
{
protected override void Log(string message)
{
TestContext.WriteLine(String.Concat(DateTime.Now.ToString("hh:mm:ss.ffffff "), new String(' ', mLogLevel * 2), message));
}
}
}
}
|
bsd-3-clause
|
C#
|
d239e8d1468062908f9251e3e96f780da727d182
|
remove unused script
|
IdentityServer/IdentityServer2,IdentityServer/IdentityServer2,rfavillejr/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,kjnilsson/Thinktecture.IdentityServer.v2,kjnilsson/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2
|
src/OnPremise/WebSite/Areas/Admin/Views/IP/IP.cshtml
|
src/OnPremise/WebSite/Areas/Admin/Views/IP/IP.cshtml
|
@model Thinktecture.IdentityServer.Models.IdentityProvider
@using Thinktecture.IdentityServer.Web.Utility
@{
if (Model.ID == 0)
{
ViewBag.Title = "New Identity Provider";
}
else
{
ViewBag.Title = "Identity Provider : " + Model.Name;
}
}
@{
var action = Model.ID == 0 ? "Create" : "Update";
}
@using (Html.BeginForm(action, "IP", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary("Error updating identity provider")
<fieldset class="editor">
<legend>@ViewBag.Title</legend>
@Html.EditorForModel()
<div class="buttons">
@if (Model.ID > 0)
{
<button type="submit" name="action" value="save">Save Changes</button>
<button type="submit" name="action" value="delete">Delete</button>
}
else
{
<button type="submit" name="action" value="create">Create</button>
}
<button type="reset">Cancel</button>
</div>
</fieldset>
}
|
@model Thinktecture.IdentityServer.Models.IdentityProvider
@using Thinktecture.IdentityServer.Web.Utility
@{
if (Model.ID == 0)
{
ViewBag.Title = "New Identity Provider";
}
else
{
ViewBag.Title = "Identity Provider : " + Model.Name;
}
}
@{
var action = Model.ID == 0 ? "Create" : "Update";
}
@using (Html.BeginForm(action, "IP", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary("Error updating identity provider")
<fieldset class="editor">
<legend>@ViewBag.Title</legend>
@Html.EditorForModel()
<div class="buttons">
@if (Model.ID > 0)
{
<button type="submit" name="action" value="save">Save Changes</button>
<button type="submit" name="action" value="delete">Delete</button>
}
else
{
<button type="submit" name="action" value="create">Create</button>
}
<button type="reset">Cancel</button>
</div>
</fieldset>
}
@section scripts{
<script src="~/Areas/Admin/Scripts/RP.js"></script>
}
|
bsd-3-clause
|
C#
|
e48cc1d98698ec999d916f672ee430d186a70616
|
Fix SideBar Ninject bindings.
|
alastairs/cgowebsite,alastairs/cgowebsite
|
src/CGO.Web/NinjectModules/SideBarModule.cs
|
src/CGO.Web/NinjectModules/SideBarModule.cs
|
using System.Web;
using System.Web.Mvc;
using CGO.Web.Controllers;
using Ninject.Modules;
using Ninject.Web.Common;
namespace CGO.Web.NinjectModules
{
public class SideBarModule : NinjectModule
{
public override void Load()
{
const string concertsControllerName = "Concerts";
Kernel.Bind<ISideBarFactory>()
.To<DefaultSideBarFactory>()
.InRequestScope();
Kernel.Rebind<ISideBarFactory>()
.To<ConcertsSideBarFactory>()
.When(_ => RequestedControllerIs(concertsControllerName))
.InRequestScope();
}
private static bool RequestedControllerIs(string controllerName)
{
const string controllerRouteKey = "controller";
var mvcHandler = (MvcHandler)HttpContext.Current.Handler;
var routeValues = mvcHandler.RequestContext.RouteData.Values;
object requestedControllerName;
if (routeValues.TryGetValue(controllerRouteKey, out requestedControllerName))
{
return requestedControllerName.ToString().ToUpper() == controllerName.ToUpper();
}
return false;
}
}
}
|
using CGO.Web.Controllers;
using Ninject.Modules;
using Ninject.Web.Common;
namespace CGO.Web.NinjectModules
{
public class SideBarModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<ISideBarFactory>()
.To<ConcertsSideBarFactory>()
.WhenInjectedInto<SideBarController>()
.InRequestScope();
Kernel.Bind<ISideBarFactory>().To<DefaultSideBarFactory>().InRequestScope();
}
}
}
|
mit
|
C#
|
186c6c602fe12b1f9dc5d4ffc16d9de079e6c1f6
|
Update AccessAllNamedRanges.cs
|
asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/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,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/CSharp/Data/AddOn/NamedRanges/AccessAllNamedRanges.cs
|
Examples/CSharp/Data/AddOn/NamedRanges/AccessAllNamedRanges.cs
|
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Data.AddOn.NamedRanges
{
public class AccessAllNamedRanges
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Getting all named ranges
Range[] range = workbook.Worksheets.GetNamedRanges();
if(range != null)
Console.WriteLine("Total Number of Named Ranges: " + range.Length);
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Data.AddOn.NamedRanges
{
public class AccessAllNamedRanges
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Getting all named ranges
Range[] range = workbook.Worksheets.GetNamedRanges();
if(range != null)
Console.WriteLine("Total Number of Named Ranges: " + range.Length);
}
}
}
|
mit
|
C#
|
651a58b77fccbb4e4fe5019664b5951f465b91ec
|
fix facade
|
fabiosilvalima/FSL.eBook.RWP.DesignPatterns,fabiosilvalima/FSL.eBook.RWP.DesignPatterns,fabiosilvalima/FSL.eBook.RWP.DesignPatterns
|
FSL.eBook.RWP.DesignPatterns/FacadeChapter/FacadeController.cs
|
FSL.eBook.RWP.DesignPatterns/FacadeChapter/FacadeController.cs
|
using System.Web.Mvc;
namespace FSL.eBook.RWP.DesignPatterns.FacadeChapter
{
public class FacadeController : Controller
{
public ActionResult WithoutFacade()
{
var logger = new Logger();
var payment = new Payment();
var securityInfo = new SecurityInfo();
var transaction = new Trasaction();
logger.Log("Payment Start");
var result = false;
var userId = "3434343";
var securityId = securityInfo.GetFromUserId(userId);
logger.Log($"Security id {securityId} for user id {userId}");
transaction.Start();
transaction.Do(() =>
{
var amount = 45.400;
result = payment.Pay(securityId, amount);
logger.Log($"Paying {amount} for security id {securityId}");
});
transaction.End();
logger.Log("transaction end");
logger.Log($"payment result {result}");
payment.Dispose();
transaction.Dispose();
securityInfo.Dispose();
logger.Dispose();
return Content("WithoutFacade");
}
public ActionResult WithFacade()
{
var facade = new Facade();
var result = facade.Pay("3434343", 45.400);
return Content("WithFacade");
}
}
}
|
using System.Web.Mvc;
namespace FSL.eBook.RWP.DesignPatterns.FacadeChapter
{
public class FacadeController : Controller
{
public ActionResult WithoutFacade()
{
var logger = new Logger();
var payment = new Payment();
var securityInfo = new SecurityInfo();
var transaction = new Trasaction();
logger.Log("Payment Start");
var result = false;
var userId = "3434343";
var securityId = securityInfo.GetFromUserId(userId);
logger.Log($"Security id {securityId} for user id {userId}");
transaction.Start();
transaction.Do(() =>
{
var amount = 45.400;
result = payment.Pay(securityId, amount);
logger.Log($"Paying {amount} for security id {securityId}");
});
transaction.End();
logger.Log("transaction end");
logger.Log($"payment result {result}");
payment.Dispose();
transaction.Dispose();
securityInfo.Dispose();
logger.Dispose();
return Content("Facade");
}
public ActionResult WithFacade()
{
var facade = new Facade();
var result = facade.Pay("3434343", 45.400);
return Content("Facade");
}
}
}
|
mit
|
C#
|
bff4ca27e9e6a9063be8abeb3a3c1de3bd900e84
|
Update DIPSbotHost.cs
|
Sankra/DIPSbot,Sankra/DIPSbot
|
src/Hjerpbakk.DIPSbot.Runner/DIPSbotHost.cs
|
src/Hjerpbakk.DIPSbot.Runner/DIPSbotHost.cs
|
using LightInject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hjerpbakk.DIPSbot.Services;
using SlackConnector;
namespace Hjerpbakk.DIPSbot.Runner {
class DIPSbotHost {
DIPSbotImplementation DIPSbot;
public void Start() {
var serviceContainer = CompositionRoot();
DIPSbot = serviceContainer.GetInstance<DIPSbotImplementation>();
DIPSbot
.Connect()
.ContinueWith(task => {
if (!task.IsCompleted || task.IsFaulted) {
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop() {
Console.WriteLine("Disconnecting...");
DIPSbot.Dispose();
DIPSbot = null;
}
static IServiceContainer CompositionRoot() {
var serviceContainer = new ServiceContainer();
serviceContainer.RegisterInstance("");
serviceContainer.Register<ISlackConnector, SlackConnector.SlackConnector>(new PerContainerLifetime());
serviceContainer.Register<ISlackIntegration, SlackIntegration>(new PerContainerLifetime());
serviceContainer.Register<IOrganizationService, FileOrganizationService>(new PerContainerLifetime());
serviceContainer.Register<DIPSbotImplementation>();
return serviceContainer;
}
}
}
|
using LightInject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hjerpbakk.DIPSbot.Services;
using SlackConnector;
namespace Hjerpbakk.DIPSbot.Runner {
class DIPSbotHost {
DIPSbotImplementation DIPSbot;
public void Start() {
var serviceContainer = CompositionRoot();
DIPSbot = serviceContainer.GetInstance<DIPSbotImplementation>();
DIPSbot
.Connect()
.ContinueWith(task => {
if (!task.IsCompleted || task.IsFaulted) {
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop() {
Console.WriteLine("Disconnecting...");
DIPSbot.Dispose();
DIPSbot = null;
}
static IServiceContainer CompositionRoot() {
var serviceContainer = new ServiceContainer();
serviceContainer.RegisterInstance("xoxb-74447052882-CjgPJUCBXfPydIZ9dMD5V3Ey");
serviceContainer.Register<ISlackConnector, SlackConnector.SlackConnector>(new PerContainerLifetime());
serviceContainer.Register<ISlackIntegration, SlackIntegration>(new PerContainerLifetime());
serviceContainer.Register<IOrganizationService, FileOrganizationService>(new PerContainerLifetime());
serviceContainer.Register<DIPSbotImplementation>();
return serviceContainer;
}
}
}
|
mit
|
C#
|
f8196df48c94b8bf590160cf378342c48bee2d85
|
Convert an null reference to VlcInstance to IntPtr.Zero
|
ZeBobo5/Vlc.DotNet,jeremyVignelles/Vlc.DotNet
|
src/Vlc.DotNet.Core.Interops/VlcInstance.cs
|
src/Vlc.DotNet.Core.Interops/VlcInstance.cs
|
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed class VlcInstance : InteropObjectInstance
{
private readonly VlcManager myManager;
internal VlcInstance(VlcManager manager, IntPtr pointer) : base(pointer)
{
myManager = manager;
}
protected override void Dispose(bool disposing)
{
if (Pointer != IntPtr.Zero)
myManager.ReleaseInstance(this);
base.Dispose(disposing);
}
public static implicit operator IntPtr(VlcInstance instance)
{
if (instance == null)
return IntPtr.Zero;
return instance.Pointer;
}
}
}
|
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed class VlcInstance : InteropObjectInstance
{
private readonly VlcManager myManager;
internal VlcInstance(VlcManager manager, IntPtr pointer) : base(pointer)
{
myManager = manager;
}
protected override void Dispose(bool disposing)
{
if (Pointer != IntPtr.Zero)
myManager.ReleaseInstance(this);
base.Dispose(disposing);
}
public static implicit operator IntPtr(VlcInstance instance)
{
return instance.Pointer;
}
}
}
|
mit
|
C#
|
054f8046c5160e1f2df569f3cf48f815b4d2a5c7
|
fix null reference
|
SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk
|
SnapMD.ConnectedCare.ApiModels/PatientMedicalHistoryProfile.cs
|
SnapMD.ConnectedCare.ApiModels/PatientMedicalHistoryProfile.cs
|
// Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
namespace SnapMD.ConnectedCare.ApiModels
{
public class PatientMedicalHistoryProfile : IPatientMedicalHistoryProfile
{
public PatientMedicalHistoryProfile()
{
MedicalConditions = new List<CustomCode>();
InfantData = new NewbornRecord();
MedicationAllergies = new List<CustomCode>();
Surgeries = new List<SurgeryRecord>();
Medications = new List<CustomCode>();
}
public List<CustomCode> MedicationAllergies { get; set; }
public List<SurgeryRecord> Surgeries { get; set; }
public List<CustomCode> MedicalConditions { get; set; }
public List<CustomCode> Medications { get; set; }
public NewbornRecord InfantData { get; set; }
public int PatientId { get; set; }
}
}
|
// Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
namespace SnapMD.ConnectedCare.ApiModels
{
public class PatientMedicalHistoryProfile : IPatientMedicalHistoryProfile
{
public PatientMedicalHistoryProfile()
{
MedicalConditions = new List<CustomCode>();
InfantData = new NewbornRecord();
MedicalConditions = new List<CustomCode>();
Surgeries = new List<SurgeryRecord>();
Medications = new List<CustomCode>();
}
public List<CustomCode> MedicationAllergies { get; set; }
public List<SurgeryRecord> Surgeries { get; set; }
public List<CustomCode> MedicalConditions { get; set; }
public List<CustomCode> Medications { get; set; }
public NewbornRecord InfantData { get; set; }
public int PatientId { get; set; }
}
}
|
apache-2.0
|
C#
|
74ab6d43437e3976d0d538a9403645213a063bb3
|
Implement activating game objects
|
bartlomiejwolk/ActivateGameObject
|
ActivateGameObject.cs
|
ActivateGameObject.cs
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ActivateGameObjectEx {
public sealed class ActivateGameObject : MonoBehaviour {
#region CONSTANTS
public const string Version = "v0.1.0";
public const string Extension = "ActivateGameObject";
#endregion
#region DELEGATES
#endregion
#region EVENTS
#endregion
#region FIELDS
/// <summary>
/// Allows identify component in the scene file when reading it with
/// text editor.
/// </summary>
#pragma warning disable 0414
[SerializeField]
private string componentName = "ActivateGameObject";
#pragma warning restore0414
#endregion
#region INSPECTOR FIELDS
[SerializeField]
private string description = "Description";
/// <summary>
/// List of game object to activate. Game objects will be activate
/// in list order.
/// </summary>
[SerializeField]
private List<GameObject> gameObjects;
#endregion
#region PROPERTIES
/// <summary>
/// Optional text to describe purpose of this instance of the component.
/// </summary>
public string Description {
get { return description; }
set { description = value; }
}
public List<GameObject> GameObjects {
get { return gameObjects; }
set { gameObjects = value; }
}
#endregion
#region UNITY MESSAGES
private void Awake() { }
private void FixedUpdate() { }
private void LateUpdate() { }
private void OnEnable() { }
private void Reset() { }
private void Start() { }
private void Update() { }
private void OnValidate() { }
#endregion
#region EVENT INVOCATORS
#endregion
#region EVENT HANDLERS
#endregion
#region METHODS
/// <summary>
/// Activate all game object in list order.
/// </summary>
public void Activate() {
foreach (var GO in GameObjects) {
GO.SetActive(true);
}
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ActivateGameObjectEx {
public sealed class ActivateGameObject : MonoBehaviour {
#region CONSTANTS
public const string Version = "v0.1.0";
public const string Extension = "ActivateGameObject";
#endregion
#region DELEGATES
#endregion
#region EVENTS
#endregion
#region FIELDS
/// <summary>
/// Allows identify component in the scene file when reading it with
/// text editor.
/// </summary>
#pragma warning disable 0414
[SerializeField]
private string componentName = "ActivateGameObject";
#pragma warning restore0414
#endregion
#region INSPECTOR FIELDS
[SerializeField]
private string description = "Description";
/// <summary>
/// List of game object to activate. Game objects will be activate
/// in list order.
/// </summary>
[SerializeField]
private List<GameObject> gameObjects;
#endregion
#region PROPERTIES
/// <summary>
/// Optional text to describe purpose of this instance of the component.
/// </summary>
public string Description {
get { return description; }
set { description = value; }
}
public List<GameObject> GameObjects {
get { return gameObjects; }
set { gameObjects = value; }
}
#endregion
#region UNITY MESSAGES
private void Awake() { }
private void FixedUpdate() { }
private void LateUpdate() { }
private void OnEnable() { }
private void Reset() { }
private void Start() { }
private void Update() { }
private void OnValidate() { }
#endregion
#region EVENT INVOCATORS
#endregion
#region EVENT HANDLERS
#endregion
#region METHODS
public void Activate() {
}
#endregion
}
}
|
mit
|
C#
|
d0cf43fc2efa02d19a60005a4f6347a9ebf6b02c
|
Add tests for PascalCaseToSpacedString extensions
|
entelect/Entelect
|
test/Entelect.Tests/Strings/StringExtensionsTests.cs
|
test/Entelect.Tests/Strings/StringExtensionsTests.cs
|
using System;
using NUnit.Framework;
using Entelect.Extensions;
namespace Entelect.Tests.Strings
{
[TestFixture]
public class StringExtensionsTests
{
[Test]
public void ContainsIgnoringCase()
{
var doesContain = "asd".Contains("S",StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
[Test]
public void ListContainsIgnoringCase()
{
var list = new[] {"asd", "qwe", "zxc"};
var doesContain = list.Contains("ASD", StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
[Test]
public void PascalCaseToSpacedString()
{
const string input = "SomePascalCasedString";
const string expectedOutput = "Some Pascal Cased String";
var actualOutput = input.PascalToSpacedString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[Test]
public void PascalCaseToSpacedStringArray()
{
const string input = "SomePascalCasedString";
var expectedOutput = new []{"Some", "Pascal", "Cased","String"};
var actualOutput = input.PascalToSpacedStringArray();
Assert.That(expectedOutput, Is.EquivalentTo(actualOutput));
}
}
}
|
using System;
using NUnit.Framework;
using Entelect.Extensions;
namespace Entelect.Tests.Strings
{
[TestFixture]
public class StringExtensionsTests
{
[Test]
public void ContainsIgnoringCase()
{
var doesContain = "asd".Contains("S",StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
[Test]
public void ListContainsIgnoringCase()
{
var list = new[] {"asd", "qwe", "zxc"};
var doesContain = list.Contains("ASD", StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
}
}
|
mit
|
C#
|
ca9489c90706ebf2ef09be9f72375f43169115ce
|
Fix InBetweenInspector
|
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity
|
Assets/MixedRealityToolkit.SDK/Inspectors/Utilities/Solvers/InBetweenInspector.cs
|
Assets/MixedRealityToolkit.SDK/Inspectors/Utilities/Solvers/InBetweenInspector.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Solvers;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor.Solvers
{
[CustomEditor(typeof(InBetween))]
public class InBetweenEditor : UnityEditor.Editor
{
private SerializedProperty trackedObjectProperty;
private SerializedProperty transformTargetProperty;
private InBetween solverInBetween;
private static readonly string[] fieldsToExclude = new string[] { "m_Script" };
private void OnEnable()
{
trackedObjectProperty = serializedObject.FindProperty("trackedObjectForSecondTransform");
transformTargetProperty = serializedObject.FindProperty("secondTransformOverride");
solverInBetween = target as InBetween;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.Space();
bool trackedObjectChanged = false;
if (transformTargetProperty.objectReferenceValue == null)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(trackedObjectProperty);
trackedObjectChanged = EditorGUI.EndChangeCheck();
}
EditorGUILayout.PropertyField(transformTargetProperty);
DrawPropertiesExcluding(serializedObject, fieldsToExclude);
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying && trackedObjectChanged)
{
solverInBetween.AttachSecondTransformToNewTrackedObject();
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Solvers;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor.Solvers
{
[CustomEditor(typeof(InBetween))]
public class InBetweenEditor : UnityEditor.Editor
{
private SerializedProperty trackedObjectProperty;
private SerializedProperty secondTrackedHandJointProperty;
private SerializedProperty transformTargetProperty;
private InBetween solverInBetween;
private static readonly string[] fieldsToExclude = new string[] { "m_Script" };
private void OnEnable()
{
trackedObjectProperty = serializedObject.FindProperty("trackedObjectForSecondTransform");
secondTrackedHandJointProperty = serializedObject.FindProperty("secondTrackedHandJoint");
transformTargetProperty = serializedObject.FindProperty("secondTransformOverride");
solverInBetween = target as InBetween;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.Space();
bool trackedObjectChanged = false;
if (transformTargetProperty.objectReferenceValue == null)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(trackedObjectProperty);
trackedObjectChanged = EditorGUI.EndChangeCheck();
if (trackedObjectProperty.intValue == (int)TrackedObjectType.HandJoint)
{
EditorGUILayout.PropertyField(secondTrackedHandJointProperty);
}
}
EditorGUILayout.PropertyField(transformTargetProperty);
DrawPropertiesExcluding(serializedObject, fieldsToExclude);
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying && trackedObjectChanged)
{
solverInBetween.AttachSecondTransformToNewTrackedObject();
}
}
}
}
|
mit
|
C#
|
084931db61d62f7e777b05163e6ff37d58c3f5da
|
Make GetUniqueName() virtual so it's possible to inject a customized version when extending the compiler
|
drslump/boo,drslump/boo,hmah/boo,KidFashion/boo,KingJiangNet/boo,KidFashion/boo,bamboo/boo,BitPuffin/boo,KingJiangNet/boo,KingJiangNet/boo,BITechnologies/boo,BitPuffin/boo,KingJiangNet/boo,drslump/boo,hmah/boo,rmboggs/boo,BillHally/boo,BITechnologies/boo,boo-lang/boo,BitPuffin/boo,drslump/boo,bamboo/boo,BITechnologies/boo,BitPuffin/boo,boo-lang/boo,BillHally/boo,rmboggs/boo,boo-lang/boo,KidFashion/boo,bamboo/boo,BillHally/boo,boo-lang/boo,drslump/boo,BITechnologies/boo,rmboggs/boo,KingJiangNet/boo,rmboggs/boo,hmah/boo,rmboggs/boo,bamboo/boo,drslump/boo,KidFashion/boo,bamboo/boo,BitPuffin/boo,KingJiangNet/boo,boo-lang/boo,KidFashion/boo,boo-lang/boo,hmah/boo,BITechnologies/boo,BITechnologies/boo,hmah/boo,bamboo/boo,BillHally/boo,BITechnologies/boo,BitPuffin/boo,KidFashion/boo,hmah/boo,BitPuffin/boo,boo-lang/boo,drslump/boo,BillHally/boo,BITechnologies/boo,boo-lang/boo,BillHally/boo,rmboggs/boo,hmah/boo,rmboggs/boo,hmah/boo,KingJiangNet/boo,BillHally/boo,KingJiangNet/boo,hmah/boo,KidFashion/boo,bamboo/boo,rmboggs/boo,BitPuffin/boo
|
src/Boo.Lang.Compiler/Services/UniqueNameProvider.cs
|
src/Boo.Lang.Compiler/Services/UniqueNameProvider.cs
|
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang.Compiler.Services
{
public class UniqueNameProvider
{
private int _localIndex;
///<summary>Generates a name that will be unique within the CompilerContext.</summary>
///<param name="components">Zero or more string(s) that will compose the generated name.</param>
///<returns>Returns the generated unique name.</returns>
public virtual string GetUniqueName(params string[] components)
{
var suffix = string.Concat("$", (++_localIndex).ToString());
if (components == null || components.Length == 0)
return suffix;
var sb = new System.Text.StringBuilder();
foreach (var component in components)
{
sb.Append("$");
sb.Append(component);
}
sb.Append(suffix);
return sb.ToString();
}
}
}
|
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang.Compiler.Services
{
public class UniqueNameProvider
{
private int _localIndex;
///<summary>Generates a name that will be unique within the CompilerContext.</summary>
///<param name="components">Zero or more string(s) that will compose the generated name.</param>
///<returns>Returns the generated unique name.</returns>
public string GetUniqueName(params string[] components)
{
var suffix = string.Concat("$", (++_localIndex).ToString());
if (components == null || components.Length == 0)
return suffix;
var sb = new System.Text.StringBuilder();
foreach (var component in components)
{
sb.Append("$");
sb.Append(component);
}
sb.Append(suffix);
return sb.ToString();
}
}
}
|
bsd-3-clause
|
C#
|
638fd0bf8e4fc24b10d1b8cf0358331da56b3ec2
|
Document OriginAttractionForce API
|
drewnoakes/boing
|
Boing/Forces/OriginAttractionForce.cs
|
Boing/Forces/OriginAttractionForce.cs
|
#region License
// Copyright 2015-2017 Drew Noakes, Krzysztof Dul
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace Boing
{
/// <summary>
/// A force that attracts all non-pinned point masses towards the origin of the coordinate system.
/// </summary>
public sealed class OriginAttractionForce : IForce
{
/// <summary>
/// Gets and sets the magnitude of the force.
/// </summary>
/// <remarks>
/// Positive values cause attraction to the origin, while negative values
/// cause repulsion from it. Larger values cause larger forces, and a zero
/// value effectively disables this force.
/// </remarks>
public float Stiffness { get; set; }
/// <summary>
/// Initialises a new instance of <see cref="OriginAttractionForce"/>.
/// </summary>
/// <param name="stiffness"></param>
public OriginAttractionForce(float stiffness = 40)
{
Stiffness = stiffness;
}
/// <inheritdoc />
void IForce.ApplyTo(Simulation simulation)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (Stiffness == 0)
return;
var f = -Stiffness;
foreach (var pointMass in simulation.PointMasses)
{
if (pointMass.IsPinned)
continue;
pointMass.ApplyForce(f*pointMass.Position);
}
}
}
}
|
#region License
// Copyright 2015-2017 Drew Noakes, Krzysztof Dul
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace Boing
{
/// <summary>
/// An attraction towards the system's origin.
/// </summary>
public sealed class OriginAttractionForce : IForce
{
public float Stiffness { get; set; }
public OriginAttractionForce(float stiffness = 40)
{
Stiffness = stiffness;
}
/// <inheritdoc />
void IForce.ApplyTo(Simulation simulation)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (Stiffness == 0)
return;
var f = -Stiffness;
foreach (var pointMass in simulation.PointMasses)
{
if (pointMass.IsPinned)
continue;
pointMass.ApplyForce(f*pointMass.Position);
}
}
}
}
|
apache-2.0
|
C#
|
d1dbfcc3a087ad4a4c1f99687c0d0839150287a8
|
Fix wrong filesystem in docstring
|
drebrez/DiscUtils
|
Library/DiscUtils.Ext/ExtFileSystemOptions.cs
|
Library/DiscUtils.Ext/ExtFileSystemOptions.cs
|
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System.Text;
namespace DiscUtils.Ext
{
/// <summary>
/// EXT file system options.
/// </summary>
public sealed class ExtFileSystemOptions : DiscFileSystemOptions
{
internal ExtFileSystemOptions()
{
FileNameEncoding = Encoding.UTF8;
}
internal ExtFileSystemOptions(FileSystemParameters parameters)
{
if (parameters != null && parameters.FileNameEncoding != null)
{
FileNameEncoding = parameters.FileNameEncoding;
}
else
{
FileNameEncoding = Encoding.UTF8;
}
}
/// <summary>
/// Gets or sets the character encoding used for file names.
/// </summary>
public Encoding FileNameEncoding { get; set; }
}
}
|
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System.Text;
namespace DiscUtils.Ext
{
/// <summary>
/// FAT file system options.
/// </summary>
public sealed class ExtFileSystemOptions : DiscFileSystemOptions
{
internal ExtFileSystemOptions()
{
FileNameEncoding = Encoding.UTF8;
}
internal ExtFileSystemOptions(FileSystemParameters parameters)
{
if (parameters != null && parameters.FileNameEncoding != null)
{
FileNameEncoding = parameters.FileNameEncoding;
}
else
{
FileNameEncoding = Encoding.UTF8;
}
}
/// <summary>
/// Gets or sets the character encoding used for file names.
/// </summary>
public Encoding FileNameEncoding { get; set; }
}
}
|
mit
|
C#
|
b4e204834e4dc0e37fc3d548965189cf9a698ea7
|
Update RequestPostProcessorBehavior.cs
|
jbogard/MediatR
|
src/MediatR/Pipeline/RequestPostProcessorBehavior.cs
|
src/MediatR/Pipeline/RequestPostProcessorBehavior.cs
|
namespace MediatR.Pipeline
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// Behavior for executing all <see cref="IRequestPostProcessor{TRequest,TResponse}"/> instances after handling the request
/// </summary>
/// <typeparam name="TRequest">Request type</typeparam>
/// <typeparam name="TResponse">Response type</typeparam>
public class RequestPostProcessorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IEnumerable<IRequestPostProcessor<TRequest, TResponse>> _postProcessors;
public RequestPostProcessorBehavior(IEnumerable<IRequestPostProcessor<TRequest, TResponse>> postProcessors)
{
_postProcessors = postProcessors;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
var response = await next().ConfigureAwait(false);
await Task.WhenAll(_postProcessors.Select(p => p.Process(request, response))).ConfigureAwait(false);
return response;
}
}
}
|
.namespace MediatR.Pipeline
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// Behavior for executing all <see cref="IRequestPostProcessor{TRequest,TResponse}"/> instances after handling the request
/// </summary>
/// <typeparam name="TRequest">Request type</typeparam>
/// <typeparam name="TResponse">Response type</typeparam>
public class RequestPostProcessorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IEnumerable<IRequestPostProcessor<TRequest, TResponse>> _postProcessors;
public RequestPostProcessorBehavior(IEnumerable<IRequestPostProcessor<TRequest, TResponse>> postProcessors)
{
_postProcessors = postProcessors;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
var response = await next().ConfigureAwait(false);
await Task.WhenAll(_postProcessors.Select(p => p.Process(request, response))).ConfigureAwait(false);
return response;
}
}
}
|
apache-2.0
|
C#
|
6651647cf4a2f401dcef3c964e6fd436071da318
|
Fix commit 17455f50d29919a38a48a666faf80c3c2cf4aae1
|
StockSharp/StockSharp
|
Samples/Connectors/SampleConnection/OrdersWindow.xaml.cs
|
Samples/Connectors/SampleConnection/OrdersWindow.xaml.cs
|
namespace SampleConnection
{
using Ecng.Common;
using Ecng.Xaml;
using StockSharp.Algo;
using StockSharp.BusinessEntities;
using StockSharp.Localization;
using StockSharp.Xaml;
public partial class OrdersWindow
{
public OrdersWindow()
{
InitializeComponent();
}
private static Connector Connector => MainWindow.Instance.MainPanel.Connector;
private void OrderGrid_OnOrderCanceling(Order order)
{
Connector.CancelOrder(order);
}
private void OrderGrid_OrderReRegistering(Order order)
{
var window = new OrderWindow
{
Title = LocalizedStrings.Str2976Params.Put(order.TransactionId),
Order = order.ReRegisterClone(newVolume: order.Balance),
SecurityEnabled = false,
PortfolioEnabled = false,
OrderTypeEnabled = false,
}.Init(Connector);
if (!window.ShowModal(this))
return;
if (Connector.IsOrderEditable(order) == true)
Connector.EditOrder(order, window.Order);
else
Connector.ReRegisterOrder(order, window.Order);
}
}
}
|
namespace SampleConnection
{
using Ecng.Common;
using Ecng.Xaml;
using StockSharp.Algo;
using StockSharp.BusinessEntities;
using StockSharp.Localization;
using StockSharp.Xaml;
public partial class OrdersWindow
{
public OrdersWindow()
{
InitializeComponent();
}
private static Connector Connector => MainWindow.Instance.MainPanel.Connector;
private void OrderGrid_OnOrderCanceling(Order order)
{
Connector.CancelOrder(order);
}
private void OrderGrid_OrderReRegistering(Order order)
{
var window = new OrderWindow
{
Title = LocalizedStrings.Str2976Params.Put(order.TransactionId),
Order = order.ReRegisterClone(newVolume: order.Balance),
SecurityEnabled = false,
PortfolioEnabled = false,
OrderTypeEnabled = false,
}.Init(Connector);
if (window.ShowModal(this))
Connector.ReRegisterOrder(order, window.Order);
}
}
}
|
apache-2.0
|
C#
|
f26ed9455c6887b0181dbcd4e0e95ce004c4a271
|
fix creating listview columns
|
punker76/simple-music-player
|
SimpleMusicPlayer/SimpleMusicPlayer/Base/BaseListView.cs
|
SimpleMusicPlayer/SimpleMusicPlayer/Base/BaseListView.cs
|
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace SimpleMusicPlayer.Base
{
public class BaseListView : ListView
{
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {
base.OnPropertyChanged(e);
if (e.Property.Name == "ItemsSource" && e.OldValue != e.NewValue && e.NewValue != null) {
CreateColumns(this);
}
}
private static void CreateColumns(BaseListView lv) {
var gridView = new GridView();
gridView.AllowsColumnReorder = true;
var properties = lv.DataType.GetProperties();
foreach (var pi in properties) {
var browsable = pi.GetCustomAttributes(true).FirstOrDefault(a => a is BrowsableAttribute) as BrowsableAttribute;
if (browsable != null && !browsable.Browsable) {
continue;
}
var binding = new Binding { Path = new PropertyPath(pi.Name), Mode = BindingMode.OneWay };
var gridViewColumn = new GridViewColumn() { Header = pi.Name, DisplayMemberBinding = binding };
gridView.Columns.Add(gridViewColumn);
}
lv.View = gridView;
}
public Type DataType { get; set; }
}
}
|
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace SimpleMusicPlayer.Base
{
public class BaseListView : ListView
{
public BaseListView() {
ItemsSourceProperty.AddOwner(typeof(BaseListView), new FrameworkPropertyMetadata(null, OnItemsSourcePropertyChanged));
}
private static void OnItemsSourcePropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) {
if (e.OldValue != e.NewValue && e.NewValue != null) {
var lv = (BaseListView)dependencyObject;
var gridView = new GridView();
gridView.AllowsColumnReorder = true;
var properties = lv.DataType.GetProperties();
foreach (var pi in properties) {
var browsable = pi.GetCustomAttributes(true).FirstOrDefault(a => a is BrowsableAttribute) as BrowsableAttribute;
if (browsable != null && !browsable.Browsable) {
continue;
}
var binding = new Binding {Path = new PropertyPath(pi.Name), Mode = BindingMode.OneWay};
var gridViewColumn = new GridViewColumn() {Header = pi.Name, DisplayMemberBinding = binding};
gridView.Columns.Add(gridViewColumn);
}
lv.View = gridView;
}
}
public Type DataType { get; set; }
}
}
|
mit
|
C#
|
554ad46eeb5d29da37b125425cba76e3837fb047
|
Correct lat/long
|
CB17Echo/DroneSafety,CB17Echo/DroneSafety,CB17Echo/DroneSafety
|
AzureFunctions/WiFiGatherer/run.csx
|
AzureFunctions/WiFiGatherer/run.csx
|
#load "../Models/WiFi.csx"
using Microsoft.Azure.Documents.Spatial;
using System;
using System.Collections.Generic;
static Random RNG = new Random();
public static int MinsToConnections(int mins, double modifier)
{
//An empirical model of number of connections based on time of day
double trueConnections = -0.0913*Math.Pow(mins/60.0, 3)
+ 2.4725*Math.Pow(mins/60.0, 2)
- 4.8756*mins/60.0 - 2.3972;
return (int)Math.Round(trueConnections*modifier);
}
public static int GetRandomModifier()
{
return RNG.Next(-50, 50);
}
public static int GetConnections(DateTime time, double modifier, TraceWriter log)
{
int baseConnections = MinsToConnections(time.Hour * 60 + time.Minute, modifier);
int realConnections = Math.Max(0, GetRandomModifier() + baseConnections);
Console.Write($"Calculated {realConnections} from base {baseConnections}");
return realConnections;
}
public static void Run(TimerInfo myTimer, out WiFi[] datapoints, TraceWriter log)
{
log.Info($"C# WiFi Timer trigger function executed at: {DateTime.Now}");
DateTime time = DateTime.Now;
datapoints = new WiFi[] {
new WiFi {
Location = new Point(0.119219, 52.205576), //Waffle man, Market
Connections = GetConnections(time, 1.1, log),
Time = time
},
new WiFi {
Location = new Point(0.122259, 52.201987), //Downing site
Connections = GetConnections(time, 0.9, log),
Time = time
},
new WiFi {
Location = new Point(0.1168093, 52.20485), //King's chapel
Connections = GetConnections(time, 0.5, log),
Time = time
},
};
}
|
#load "../Models/WiFi.csx"
using Microsoft.Azure.Documents.Spatial;
using System;
using System.Collections.Generic;
static Random RNG = new Random();
public static int MinsToConnections(int mins, double modifier)
{
//An empirical model of number of connections based on time of day
double trueConnections = -0.0913*Math.Pow(mins/60.0, 3)
+ 2.4725*Math.Pow(mins/60.0, 2)
- 4.8756*mins/60.0 - 2.3972;
return (int)Math.Round(trueConnections*modifier);
}
public static int GetRandomModifier()
{
return RNG.Next(-50, 50);
}
public static int GetConnections(DateTime time, double modifier, TraceWriter log)
{
int baseConnections = MinsToConnections(time.Hour * 60 + time.Minute, modifier);
int realConnections = Math.Max(0, GetRandomModifier() + baseConnections);
Console.Write($"Calculated {realConnections} from base {baseConnections}");
return realConnections;
}
public static void Run(TimerInfo myTimer, out WiFi[] datapoints, TraceWriter log)
{
log.Info($"C# WiFi Timer trigger function executed at: {DateTime.Now}");
DateTime time = DateTime.Now;
datapoints = new WiFi[] {
new WiFi {
Location = new Point(52.205576, 0.119219), //Waffle man, Market
Connections = GetConnections(time, 1.1, log),
Time = time
},
new WiFi {
Location = new Point(52.201987, 0.122259), //Downing site
Connections = GetConnections(time, 0.9, log),
Time = time
},
new WiFi {
Location = new Point(52.204853, 0.116809), //King's chapel
Connections = GetConnections(time, 0.5, log),
Time = time
},
};
}
|
apache-2.0
|
C#
|
d38dc56123bfb1ea5c96cff3fd92a7f3b8f7bd05
|
Implement the StandardAjax Platform API
|
RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake
|
Snowflake.StandardAjax/StandardAjax.Platform.cs
|
Snowflake.StandardAjax/StandardAjax.Platform.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Ajax;
using Snowflake.Platform;
using Snowflake.Emulator.Input;
namespace Snowflake.StandardAjax
{
public partial class StandardAjax
{
[AjaxMethod(MethodPrefix = "Platform")]
[AjaxMethodParameter(ParameterName = "platform", ParameterType = AjaxMethodParameterType.StringParameter)]
public IJSResponse GetPreferences(IJSRequest request)
{
IPlatformInfo platform = this.CoreInstance.LoadedPlatforms[request.GetParameter("platform")];
return new JSResponse(request, this.CoreInstance.PlatformPreferenceDatabase.GetPreferences(platform));
}
[AjaxMethod(MethodPrefix = "Platform")]
[AjaxMethodParameter(ParameterName = "platform", ParameterType = AjaxMethodParameterType.StringParameter)]
[AjaxMethodParameter(ParameterName = "preference", ParameterType = AjaxMethodParameterType.StringParameter)]
[AjaxMethodParameter(ParameterName = "value", ParameterType = AjaxMethodParameterType.StringParameter)]
public IJSResponse SetPreference(IJSRequest request)
{
IPlatformInfo platform = this.CoreInstance.LoadedPlatforms[request.GetParameter("platform")];
string preference = request.GetParameter("preference");
string value = request.GetParameter("value");
switch (preference)
{
case "emulator":
if (this.CoreInstance.PluginManager.LoadedEmulators.ContainsKey(value))
{
this.CoreInstance.PlatformPreferenceDatabase.SetEmulator(platform, value);
return new JSResponse(request, "Emulator set to " + value, true);
}
else
{
return new JSResponse(request, "Error: Emulator not installed", false);
}
case "scraper":
if (this.CoreInstance.PluginManager.LoadedEmulators.ContainsKey(value))
{
this.CoreInstance.PlatformPreferenceDatabase.SetScraper(platform, value);
return new JSResponse(request, "Scraper set to " + value, true);
}
else
{
return new JSResponse(request, "Error: Scraper not installed", false);
}
default:
return new JSResponse(request, "Error: unknown preference type", false);
}
}
[AjaxMethod(MethodPrefix = "Platform")]
public IJSResponse GetPlatforms(IJSRequest request)
{
return new JSResponse(request, this.CoreInstance.LoadedPlatforms);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Ajax;
using Snowflake.Platform;
using Snowflake.Emulator.Input;
namespace Snowflake.StandardAjax
{
public partial class StandardAjax
{
[AjaxMethod(MethodPrefix = "Platform")]
public IJSResponse GetPreferences(IJSRequest request)
{
return new JSResponse(request, null);
}
[AjaxMethod(MethodPrefix = "Platform")]
public IJSResponse SetPreference(IJSRequest request)
{
return new JSResponse(request, null);
}
[AjaxMethod(MethodPrefix = "Platform")]
public IJSResponse SetInputDevice(IJSRequest request)
{
return new JSResponse(request, null);
}
[AjaxMethod(MethodPrefix = "Platform")]
public IJSResponse GetPlatforms(IJSRequest request)
{
return new JSResponse(request, null);
}
}
}
|
mpl-2.0
|
C#
|
b92ae5550f435bd21edfbe099d82c9d34606e2d1
|
clean code
|
tabby336/Solution1,tabby336/Solution1,tabby336/Solution1,tabby336/Solution1
|
Solution1/DataAccess/Repositories/Repository.cs
|
Solution1/DataAccess/Repositories/Repository.cs
|
using DataAccess.Repositories.Interfaces;
using DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DataAccess.Repositories
{
public abstract class Repository<T> : IRepository<T>
where T : BaseModel
{
protected readonly PlatformManagement context;
protected Repository(PlatformManagement platformManagement)
{
context = platformManagement;
}
public void Create(T p)
{
context.Add(p);
context.SaveChanges();
}
public void Update(T p)
{
context.Update(p);
context.SaveChanges();
}
public void Delete(T p)
{
context.Remove(p);
context.SaveChanges();
}
public IEnumerable<T> GetById(Guid id)
{
var queryResult = from R in context.Set<T>()
where R.Id == id
select R;
return queryResult;
}
public IEnumerable<T> GetAll()
{
var queryResult = from R in context.Set<T>()
select R;
return queryResult;
}
}
}
|
using DataAccess.Repositories.Interfaces;
using DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DataAccess.Repositories
{
public abstract class Repository<T> : IRepository<T>
where T : BaseModel
{
protected readonly PlatformManagement context;
protected Repository(PlatformManagement platformManagement)
{
context = platformManagement;
}
public void Create(T p)
{
context.Add(p);
context.SaveChanges();
}
public void Update(T p)
{
context.Update(p);
context.SaveChanges();
}
public void Delete(T p)
{
context.Remove(p);
context.SaveChanges();
}
public IEnumerable<T> GetById(Guid id)
{
var queryResult = from R in context.Set<T>()
where R.Id == id
select R;
return queryResult;
}
public IEnumerable<T> GetAll()
{
var queryResult = from R in context.Set<T>()
select R;
return queryResult;
}
}
}
|
mit
|
C#
|
5cccb424aad867abd1e0e540f0c30ce02707a6a1
|
Store the user when authenticating
|
flagbug/Espera,punker76/Espera
|
Espera/Espera.Core/Analytics/BuddyAnalyticsEndpoint.cs
|
Espera/Espera.Core/Analytics/BuddyAnalyticsEndpoint.cs
|
using Buddy;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
namespace Espera.Core.Analytics
{
public class BuddyAnalyticsEndpoint : IAnalyticsEndpoint
{
private readonly BuddyClient client;
private AuthenticatedUser storedUser;
public BuddyAnalyticsEndpoint()
{
this.client = new BuddyClient("Espera", "EC60C045-B432-44A6-A4E0-15B4BF607105", autoRecordDeviceInfo: false);
}
public async Task AuthenticateUserAsync(string analyticsToken)
{
this.storedUser = await this.client.LoginAsync(analyticsToken);
}
public async Task<string> CreateUserAsync()
{
string throwAwayToken = Guid.NewGuid().ToString();
AuthenticatedUser user = await this.client.CreateUserAsync(throwAwayToken, throwAwayToken);
this.storedUser = user;
return user.Token;
}
public Task RecordDeviceInformationAsync()
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return this.client.Device.RecordInformationAsync(Environment.OSVersion.VersionString, "Desktop", this.storedUser, version);
}
public Task RecordErrorAsync(string message, string logId, string stackTrace = null)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return this.client.Device.RecordCrashAsync(message, Environment.OSVersion.VersionString, "Desktop", this.storedUser, stackTrace, version, metadata: logId);
}
public Task RecordMetaDataAsync(string key, string value)
{
return this.storedUser.Metadata.SetAsync(key, value);
}
public async Task<string> SendBlobAsync(string name, string mimeType, Stream data)
{
Blob blob = await this.storedUser.Blobs.AddAsync(name, mimeType, String.Empty, 0, 0, data);
return blob.BlobID.ToString(CultureInfo.InvariantCulture);
}
public Task UpdateUserEmailAsync(string email)
{
AuthenticatedUser user = this.storedUser;
return user.UpdateAsync(user.Email, String.Empty, user.Gender, user.Age, email, // email is the only field we change here
user.Status, user.LocationFuzzing, user.CelebrityMode, user.ApplicationTag);
}
}
}
|
using Buddy;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
namespace Espera.Core.Analytics
{
public class BuddyAnalyticsEndpoint : IAnalyticsEndpoint
{
private readonly BuddyClient client;
private AuthenticatedUser storedUser;
public BuddyAnalyticsEndpoint()
{
this.client = new BuddyClient("Espera", "EC60C045-B432-44A6-A4E0-15B4BF607105", autoRecordDeviceInfo: false);
}
public Task AuthenticateUserAsync(string analyticsToken)
{
return this.client.LoginAsync(analyticsToken);
}
public async Task<string> CreateUserAsync()
{
string throwAwayToken = Guid.NewGuid().ToString();
AuthenticatedUser user = await this.client.CreateUserAsync(throwAwayToken, throwAwayToken);
this.storedUser = user;
return user.Token;
}
public Task RecordDeviceInformationAsync()
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return this.client.Device.RecordInformationAsync(Environment.OSVersion.VersionString, "Desktop", this.storedUser, version);
}
public Task RecordErrorAsync(string message, string logId, string stackTrace = null)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return this.client.Device.RecordCrashAsync(message, Environment.OSVersion.VersionString, "Desktop", this.storedUser, stackTrace, version, metadata: logId);
}
public Task RecordMetaDataAsync(string key, string value)
{
return this.storedUser.Metadata.SetAsync(key, value);
}
public async Task<string> SendBlobAsync(string name, string mimeType, Stream data)
{
Blob blob = await this.storedUser.Blobs.AddAsync(name, mimeType, String.Empty, 0, 0, data);
return blob.BlobID.ToString(CultureInfo.InvariantCulture);
}
public Task UpdateUserEmailAsync(string email)
{
AuthenticatedUser user = this.storedUser;
return user.UpdateAsync(user.Email, String.Empty, user.Gender, user.Age, email, // email is the only field we change here
user.Status, user.LocationFuzzing, user.CelebrityMode, user.ApplicationTag);
}
}
}
|
mit
|
C#
|
66c7436476ae3665db85cb195d24ea6067293827
|
add comment
|
breakds/monster-avengers,breakds/monster-avengers,breakds/monster-avengers,breakds/monster-avengers,breakds/monster-avengers,breakds/monster-avengers,breakds/monster-avengers
|
csharp/winbind_wrapper/winbind_wrapper/Program.cs
|
csharp/winbind_wrapper/winbind_wrapper/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using winbind_wrapper.armor_up_wrapper;
namespace winbind_wrapper
{
class Program
{
static void Main(string[] args)
{
// Wrapper.Initialize should be called only once for the whole lifetime
// of your program. Do not call it every time when you do a search :)
//
// The parameter to Initialize() is the path to the dataset file.
Wrapper.Initialize("d:/pf/projects/monster-avengers/dataset/MH4GDEX");
// Wrapper.Search is the entry point of the wrapper. It returns a list of
// ArmorSet objects as result. Please See definition of ArmorSet for details.
List<ArmorSet> result = Wrapper.Search("(:weapon-holes 2) (:skill 25 15)");
// Iterate over the answers, and print them.
foreach (ArmorSet answer in result) {
answer.DebugPrint();
Console.WriteLine("--------------------");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using winbind_wrapper.armor_up_wrapper;
namespace winbind_wrapper
{
class Program
{
static void Main(string[] args)
{
// Wrapper.Initialize should be called only once for the whole lifetime
// of your program. Do not call it every time when you do a search :)
Wrapper.Initialize("d:/pf/projects/monster-avengers/dataset/MH4GU");
// Wrapper.Search is the entry point of the wrapper. It returns a list of
// ArmorSet objects as result. Please See definition of ArmorSet for details.
List<ArmorSet> result = Wrapper.Search("(:weapon-holes 2) (:skill 25 15)");
// Iterate over the answers, and print them.
foreach (ArmorSet answer in result) {
answer.DebugPrint();
Console.WriteLine("--------------------");
}
}
}
}
|
mit
|
C#
|
116f05edb813f013ce6e44e94db26b65f86df5c7
|
Add support for Unmarried/Never married death date
|
ShammyLevva/FTAnalyzer,ShammyLevva/FTAnalyzer,ShammyLevva/FTAnalyzer
|
FTAnalyser/SharedAssemblyVersion.cs
|
FTAnalyser/SharedAssemblyVersion.cs
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.eabc2527")]
[assembly: System.Reflection.AssemblyVersion("1.2.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.2.0")]
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.f8952b97")]
[assembly: System.Reflection.AssemblyVersion("1.2.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.2.0")]
|
apache-2.0
|
C#
|
35148a610f1cd157a7ce8e74944ea66a2545fa79
|
refactor tests
|
mdsol/Medidata.ZipkinTracerModule
|
Medidata.ZipkinTracerModule.Test/ZipkinClientTests.cs
|
Medidata.ZipkinTracerModule.Test/ZipkinClientTests.cs
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using Rhino.Mocks;
namespace Medidata.ZipkinTracerModule.Test
{
[TestClass]
public class ZipkinClientTests
{
private IFixture fixture;
[TestInitialize]
public void Init()
{
fixture = new Fixture();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CTOR_WithNullZipkinServer()
{
var zipkinConfigStub = MockRepository.GenerateStub<IZipkinConfig>();
zipkinConfigStub.Expect(x => x.ZipkinServerName()).Return(null);
var zipkinClient = new ZipkinClient(zipkinConfigStub);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CTOR_WithNullZipkinPort()
{
var zipkinConfigStub = MockRepository.GenerateStub<IZipkinConfig>();
zipkinConfigStub.Expect(x => x.ZipkinServerName()).Return(fixture.Create<string>());
zipkinConfigStub.Expect(x => x.ZipkinServerPort()).Return(null);
var zipkinClient = new ZipkinClient(zipkinConfigStub);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CTOR_WithNonIntegerZipkinPort()
{
var zipkinConfigStub = MockRepository.GenerateStub<IZipkinConfig>();
zipkinConfigStub.Expect(x => x.ZipkinServerName()).Return(fixture.Create<string>());
zipkinConfigStub.Expect(x => x.ZipkinServerPort()).Return(fixture.Create<string>());
var zipkinClient = new ZipkinClient(zipkinConfigStub);
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using Rhino.Mocks;
namespace Medidata.ZipkinTracerModule.Test
{
[TestClass]
public class ZipkinClientTests
{
private IFixture fixture;
[TestInitialize]
public void Init()
{
fixture = new Fixture();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CTOR_WithNullZipkinServer()
{
var zipkinConfigStub = MockRepository.GenerateStub<IZipkinConfig>();
zipkinConfigStub.Expect(x => x.ZipkinServerName()).Return(null);
var zipkinClient = new ZipkinClient(zipkinConfigStub);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CTOR_WithNullZipkinPort()
{
var zipkinConfigStub = MockRepository.GenerateStub<IZipkinConfig>();
zipkinConfigStub.Expect(x => x.ZipkinServerName()).Return("hi");
zipkinConfigStub.Expect(x => x.ZipkinServerPort()).Return(null);
var zipkinClient = new ZipkinClient(zipkinConfigStub);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CTOR_WithNonIntegerZipkinPort()
{
var zipkinConfigStub = MockRepository.GenerateStub<IZipkinConfig>();
zipkinConfigStub.Expect(x => x.ZipkinServerName()).Return("hi");
zipkinConfigStub.Expect(x => x.ZipkinServerPort()).Return("abc");
var zipkinClient = new ZipkinClient(zipkinConfigStub);
}
}
}
|
mit
|
C#
|
4817dfe5c25b94c1bb11830d13c06113c516a31d
|
Return DisposableAction.Noop for the null profiler instead of creating new objects for every step.
|
duncansmart/kudu,kenegozi/kudu,juoni/kudu,dev-enthusiast/kudu,puneet-gupta/kudu,kali786516/kudu,sitereactor/kudu,bbauya/kudu,dev-enthusiast/kudu,WeAreMammoth/kudu-obsolete,chrisrpatterson/kudu,puneet-gupta/kudu,WeAreMammoth/kudu-obsolete,shanselman/kudu,uQr/kudu,sitereactor/kudu,juvchan/kudu,oliver-feng/kudu,YOTOV-LIMITED/kudu,dev-enthusiast/kudu,mauricionr/kudu,mauricionr/kudu,shrimpy/kudu,mauricionr/kudu,shibayan/kudu,chrisrpatterson/kudu,kenegozi/kudu,projectkudu/kudu,dev-enthusiast/kudu,badescuga/kudu,juvchan/kudu,shanselman/kudu,bbauya/kudu,shibayan/kudu,projectkudu/kudu,puneet-gupta/kudu,projectkudu/kudu,juvchan/kudu,uQr/kudu,duncansmart/kudu,projectkudu/kudu,MavenRain/kudu,kali786516/kudu,barnyp/kudu,EricSten-MSFT/kudu,YOTOV-LIMITED/kudu,barnyp/kudu,oliver-feng/kudu,barnyp/kudu,kali786516/kudu,MavenRain/kudu,kenegozi/kudu,bbauya/kudu,MavenRain/kudu,juoni/kudu,juoni/kudu,shrimpy/kudu,oliver-feng/kudu,projectkudu/kudu,mauricionr/kudu,YOTOV-LIMITED/kudu,EricSten-MSFT/kudu,shrimpy/kudu,badescuga/kudu,kenegozi/kudu,shanselman/kudu,shibayan/kudu,juvchan/kudu,EricSten-MSFT/kudu,badescuga/kudu,uQr/kudu,duncansmart/kudu,YOTOV-LIMITED/kudu,badescuga/kudu,sitereactor/kudu,puneet-gupta/kudu,bbauya/kudu,chrisrpatterson/kudu,sitereactor/kudu,shibayan/kudu,uQr/kudu,kali786516/kudu,duncansmart/kudu,puneet-gupta/kudu,badescuga/kudu,shrimpy/kudu,EricSten-MSFT/kudu,barnyp/kudu,sitereactor/kudu,MavenRain/kudu,oliver-feng/kudu,juoni/kudu,WeAreMammoth/kudu-obsolete,juvchan/kudu,shibayan/kudu,chrisrpatterson/kudu,EricSten-MSFT/kudu
|
Kudu.Core/Performance/NullProfiler.cs
|
Kudu.Core/Performance/NullProfiler.cs
|
using System;
using Kudu.Contracts;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Performance
{
public class NullProfiler : IProfiler
{
public static IProfiler Instance = new NullProfiler();
private NullProfiler()
{
}
public IDisposable Step(string value)
{
return DisposableAction.Noop;
}
}
}
|
using System;
using Kudu.Contracts;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Performance
{
public class NullProfiler : IProfiler
{
public static IProfiler Instance = new NullProfiler();
private NullProfiler()
{
}
public IDisposable Step(string value)
{
return new DisposableAction(() => { });
}
}
}
|
apache-2.0
|
C#
|
daa35cc7cab1a1eca09410a68e3b9008dc59ad58
|
remove unused usings
|
IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework
|
test/IdentityServer4.EntityFramework.UnitTests/Mappers/ApiResourceMappersTests.cs
|
test/IdentityServer4.EntityFramework.UnitTests/Mappers/ApiResourceMappersTests.cs
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Linq;
using FluentAssertions;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using Xunit;
using ApiResource = IdentityServer4.Models.ApiResource;
namespace IdentityServer4.EntityFramework.UnitTests.Mappers
{
public class ApiResourceMappersTests
{
[Fact]
public void AutomapperConfigurationIsValid()
{
ApiResourceMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid<ApiResourceMapperProfile>();
}
[Fact]
public void Can_Map()
{
var model = new ApiResource();
var mappedEntity = model.ToEntity();
var mappedModel = mappedEntity.ToModel();
Assert.NotNull(mappedModel);
Assert.NotNull(mappedEntity);
}
[Fact]
public void Properties_Map()
{
var model = new ApiResource()
{
Description = "description",
DisplayName = "displayname",
Name = "foo",
Scopes = { new Scope("foo1"), new Scope("foo2") },
Enabled = false
};
var mappedEntity = model.ToEntity();
mappedEntity.Scopes.Count.Should().Be(2);
var foo1 = mappedEntity.Scopes.FirstOrDefault(x => x.Name == "foo1");
foo1.Should().NotBeNull();
var foo2 = mappedEntity.Scopes.FirstOrDefault(x => x.Name == "foo2");
foo2.Should().NotBeNull();
var mappedModel = mappedEntity.ToModel();
mappedModel.Description.Should().Be("description");
mappedModel.DisplayName.Should().Be("displayname");
mappedModel.Enabled.Should().BeFalse();
mappedModel.Name.Should().Be("foo");
}
}
}
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Linq;
using FluentAssertions;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using Xunit;
using Client = IdentityServer4.Models.Client;
using ApiResource = IdentityServer4.Models.ApiResource;
namespace IdentityServer4.EntityFramework.UnitTests.Mappers
{
public class ApiResourceMappersTests
{
[Fact]
public void AutomapperConfigurationIsValid()
{
ApiResourceMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid<ApiResourceMapperProfile>();
}
[Fact]
public void Can_Map()
{
var model = new ApiResource();
var mappedEntity = model.ToEntity();
var mappedModel = mappedEntity.ToModel();
Assert.NotNull(mappedModel);
Assert.NotNull(mappedEntity);
}
[Fact]
public void Properties_Map()
{
var model = new ApiResource()
{
Description = "description",
DisplayName = "displayname",
Name = "foo",
Scopes = { new Scope("foo1"), new Scope("foo2") },
Enabled = false
};
var mappedEntity = model.ToEntity();
mappedEntity.Scopes.Count.Should().Be(2);
var foo1 = mappedEntity.Scopes.FirstOrDefault(x => x.Name == "foo1");
foo1.Should().NotBeNull();
var foo2 = mappedEntity.Scopes.FirstOrDefault(x => x.Name == "foo2");
foo2.Should().NotBeNull();
var mappedModel = mappedEntity.ToModel();
mappedModel.Description.Should().Be("description");
mappedModel.DisplayName.Should().Be("displayname");
mappedModel.Enabled.Should().BeFalse();
mappedModel.Name.Should().Be("foo");
}
}
}
|
apache-2.0
|
C#
|
87e1065681337f205837f5257e0bb215edf7a6c5
|
Adjust git cmd logging
|
michael-reichenauer/GitMind
|
GitMind/Utils/Git/Private/GitCmd.cs
|
GitMind/Utils/Git/Private/GitCmd.cs
|
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GitMind.ApplicationHandling;
using GitMind.Common.Tracking;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitCmd : IGitCmd
{
// git config --list --show-origin
private static readonly string CredentialsConfig =
@"-c credential.helper=!GitMind.exe";
private readonly ICmd2 cmd;
private readonly IGitEnvironmentService gitEnvironmentService;
private readonly WorkingFolderPath workingFolder;
public GitCmd(
ICmd2 cmd,
IGitEnvironmentService gitEnvironmentService,
WorkingFolderPath workingFolder)
{
this.cmd = cmd;
this.gitEnvironmentService = gitEnvironmentService;
this.workingFolder = workingFolder;
}
private string GitCmdPath => gitEnvironmentService.GetGitCmdPath();
public async Task<CmdResult2> RunAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
return await CmdAsync(gitArgs, options, ct);
}
public async Task<CmdResult2> RunAsync(string gitArgs, CancellationToken ct)
{
return await CmdAsync(gitArgs, new CmdOptions(), ct);
}
public async Task<CmdResult2> RunAsync(
string gitArgs, Action<string> outputLines, CancellationToken ct)
{
CmdOptions options = new CmdOptions
{
OutputLines = outputLines,
IsOutputDisabled = true,
};
return await CmdAsync(gitArgs, options, ct);
}
private async Task<CmdResult2> CmdAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
AdjustOptions(options);
// Enable credentials handling
gitArgs = $"{CredentialsConfig} {gitArgs}";
Timing t = Timing.StartNew();
CmdResult2 result = await cmd.RunAsync(GitCmdPath, gitArgs, options, ct);
Log.Debug($"{t.ElapsedMs}ms: {result.ToStringShort()}");
Track.Event("git", $"{t.ElapsedMs}ms: {result.ToStringShort()}");
return result;
}
private void AdjustOptions(CmdOptions options)
{
options.WorkingDirectory = options.WorkingDirectory ?? workingFolder;
// Used to enable credentials handling
options.EnvironmentVariables = environment =>
{
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
environment["Path"] = $"{dir};{environment["Path"]}";
};
}
}
}
|
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GitMind.ApplicationHandling;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitCmd : IGitCmd
{
// git config --list --show-origin
private static readonly string CredentialsConfig =
@"-c credential.helper=!GitMind.exe";
private readonly ICmd2 cmd;
private readonly IGitEnvironmentService gitEnvironmentService;
private readonly WorkingFolderPath workingFolder;
public GitCmd(
ICmd2 cmd,
IGitEnvironmentService gitEnvironmentService,
WorkingFolderPath workingFolder)
{
this.cmd = cmd;
this.gitEnvironmentService = gitEnvironmentService;
this.workingFolder = workingFolder;
}
private string GitCmdPath => gitEnvironmentService.GetGitCmdPath();
public async Task<CmdResult2> RunAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
return await CmdAsync(gitArgs, options, ct);
}
public async Task<CmdResult2> RunAsync(string gitArgs, CancellationToken ct)
{
return await CmdAsync(gitArgs, new CmdOptions(), ct);
}
public async Task<CmdResult2> RunAsync(
string gitArgs, Action<string> outputLines, CancellationToken ct)
{
CmdOptions options = new CmdOptions
{
OutputLines = outputLines,
IsOutputDisabled = true,
};
return await CmdAsync(gitArgs, options, ct);
}
private async Task<CmdResult2> CmdAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
AdjustOptions(options);
// Enable credentials handling
gitArgs = $"{CredentialsConfig} {gitArgs}";
Timing t = Timing.StartNew();
CmdResult2 result = await cmd.RunAsync(GitCmdPath, gitArgs, options, ct);
Log.Usage($"{t.ElapsedMs}ms: {result.ToStringShort()}");
return result;
}
private void AdjustOptions(CmdOptions options)
{
options.WorkingDirectory = options.WorkingDirectory ?? workingFolder;
// Used to enable credentials handling
options.EnvironmentVariables = environment =>
{
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
environment["Path"] = $"{dir};{environment["Path"]}";
};
}
}
}
|
mit
|
C#
|
36c5951ba91dd5bfb2e776e562b21dafe9dd9f07
|
Rename TestCase
|
umm-projects/animationevent_dispatcher
|
Assets/Tests/Scripts/UnityModule/AnimationEventDispatcher/GeneralDispatcherTest.cs
|
Assets/Tests/Scripts/UnityModule/AnimationEventDispatcher/GeneralDispatcherTest.cs
|
using System.Collections;
using NUnit.Framework;
using UniRx;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using UnityModule.AnimationEventDispatcher;
namespace Tests.UnityModule {
public class GeneralDispatcherTest {
[UnityTest]
public IEnumerator OnDispatchAsObservableTest() {
SceneManager.LoadScene("Tests/Scenes/Test");
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
GameObject go = GameObject.Find("General");
GeneralDispatcher dispatcher = go.GetComponent<GeneralDispatcher>();
bool result = false;
yield return dispatcher
.OnDispatchAsObservable("Test")
.Timeout(System.TimeSpan.FromSeconds(5))
.First()
.StartAsCoroutine(
(_) => {
result = true;
},
(e) => {
}
);
Assert.IsTrue(result, "Dispatch されたかどうか");
}
}
}
|
using System.Collections;
using NUnit.Framework;
using UniRx;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using UnityModule.AnimationEventDispatcher;
namespace Tests.UnityModule {
public class AnimationEventDispatcherTest {
[UnityTest]
public IEnumerator OnDispatchAsObservableTest() {
SceneManager.LoadScene("Tests/Scenes/Test");
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
GameObject go = GameObject.Find("General");
GeneralDispatcher dispatcher = go.GetComponent<GeneralDispatcher>();
bool result = false;
yield return dispatcher
.OnDispatchAsObservable("Test")
.Timeout(System.TimeSpan.FromSeconds(5))
.First()
.StartAsCoroutine(
(_) => {
result = true;
},
(e) => {
}
);
Assert.IsTrue(result, "Dispatch されたかどうか");
}
}
}
|
mit
|
C#
|
0dc7bbb9380f9557a70e9729aab2de0527e9288f
|
Fix issue #261
|
arleyandrada/PushSharp,volkd/PushSharp,richardvaldivieso/PushSharp,rucila/PushSharp,profporridge/PushSharp,ingljo/PushSharp,rucila/PushSharp,wanglj7525/PushSharp,agran/PushSharp,cnbin/PushSharp,fhchina/PushSharp,volkd/PushSharp,rolltechrick/PushSharp,tianhang/PushSharp,kouweizhong/PushSharp,FragCoder/PushSharp,tianhang/PushSharp,rolltechrick/PushSharp,kouweizhong/PushSharp,yuejunwu/PushSharp,cafeburger/PushSharp,sskodje/PushSharp,ZanoMano/PushSharp,JeffCertain/PushSharp,sumalla/PushSharp,richardvaldivieso/PushSharp,chaoscope/PushSharp,arleyandrada/PushSharp,kouweizhong/PushSharp,chaoscope/PushSharp,volkd/PushSharp,chaoscope/PushSharp,yuejunwu/PushSharp,bberak/PushSharp,codesharpdev/PushSharp,has-taiar/PushSharp.Web,fanpan26/PushSharp,cafeburger/PushSharp,18098924759/PushSharp,richardvaldivieso/PushSharp,sskodje/PushSharp,mao1350848579/PushSharp,mao1350848579/PushSharp,bberak/PushSharp,cnbin/PushSharp,zoser0506/PushSharp,JeffCertain/PushSharp,SuPair/PushSharp,ingljo/PushSharp,zoser0506/PushSharp,sskodje/PushSharp,bobqian1130/PushSharp,tianhang/PushSharp,18098924759/PushSharp,sumalla/PushSharp,has-taiar/PushSharp.Web,SuPair/PushSharp,wanglj7525/PushSharp,rolltechrick/PushSharp,fanpan26/PushSharp,fhchina/PushSharp,wanglj7525/PushSharp,ZanoMano/PushSharp,agran/PushSharp,codesharpdev/PushSharp,agran/PushSharp,bobqian1130/PushSharp,bobqian1130/PushSharp,ingljo/PushSharp,cnbin/PushSharp,18098924759/PushSharp,sumalla/PushSharp,cafeburger/PushSharp,JeffCertain/PushSharp,zoser0506/PushSharp,SuPair/PushSharp,rucila/PushSharp,fhchina/PushSharp,yuejunwu/PushSharp,profporridge/PushSharp,FragCoder/PushSharp,ZanoMano/PushSharp,mao1350848579/PushSharp,codesharpdev/PushSharp,FragCoder/PushSharp,profporridge/PushSharp,fanpan26/PushSharp
|
PushSharp.Blackberry/BlackberryPushChannelSettings.cs
|
PushSharp.Blackberry/BlackberryPushChannelSettings.cs
|
using System;
using PushSharp.Core;
namespace PushSharp.Blackberry
{
public class BlackberryPushChannelSettings : IPushChannelSettings
{
public string ApplicationId { get; set; }
public string Password { get; set; }
public string Boundary { get { return "ASDFaslkdfjasfaSfdasfhpoiurwqrwm"; } }
private const string SEND_URL = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";
public BlackberryPushChannelSettings()
{
SendUrl = SEND_URL;
}
public BlackberryPushChannelSettings(string applicationId, string password)
{
ApplicationId = applicationId;
Password = password;
SendUrl = SEND_URL;
}
/// <summary>
/// Push Proxy Gateway (PPG) Url is used for submitting push requests
/// Default value is BIS PPG evaluation url
/// https://pushapi.eval.blackberry.com/mss/PD_pushRequest
/// </summary>
public string SendUrl { get; private set; }
/// <summary>
/// Overrides SendUrl with any PPG url: BIS or BES
/// </summary>
/// <param name="url">Push Proxy Gateway (PPG) Url,
/// For BIS,it's PPG production url is in format: http://cpxxx.pushapi.na.blackberry.com
/// where xxx should be replaced with CPID (Content Provider ID)</param>
public void OverrideSendUrl(string url)
{
if (!string.IsNullOrWhiteSpace(url))
{
if (url.EndsWith("pushapi.na.blackberry.com", StringComparison.InvariantCultureIgnoreCase) ||
url.EndsWith("pushapi.eval.blackberry.com", StringComparison.InvariantCultureIgnoreCase))
url = url + @"/mss/PD_pushRequest";
}
SendUrl = url;
}
}
}
|
using PushSharp.Core;
namespace PushSharp.Blackberry
{
public class BlackberryPushChannelSettings : IPushChannelSettings
{
public string ApplicationId { get; set; }
public string Password { get; set; }
public string Boundary { get { return "ASDFaslkdfjasfaSfdasfhpoiurwqrwm"; } }
private const string SEND_URL = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";
public BlackberryPushChannelSettings()
{
SendUrl = SEND_URL;
}
public BlackberryPushChannelSettings(string applicationId, string password)
{
ApplicationId = applicationId;
Password = password;
SendUrl = SEND_URL;
}
/// <summary>
/// Push Proxy Gateway (PPG) Url is used for submitting push requests
/// Default value is BIS PPG evaluation url
/// https://pushapi.eval.blackberry.com/mss/PD_pushRequest
/// </summary>
public string SendUrl { get; private set; }
/// <summary>
/// Overrides SendUrl with any PPG url: BIS or BES
/// </summary>
/// <param name="url">Push Proxy Gateway (PPG) Url,
/// For BIS,it's PPG production url is in format: http://cpxxx.pushapi.na.blackberry.com
/// where xxx should be replaced with CPID (Content Provider ID)</param>
public void OverrideSendUrl(string url)
{
if (!string.IsNullOrWhiteSpace(url))
{
if (url.EndsWith("pushapi.na.blackberry.com", StringComparison.InvariantCultureIgnoreCase) ||
url.EndsWith("pushapi.eval.blackberry.com", StringComparison.InvariantCultureIgnoreCase))
url = url + @"/mss/PD_pushRequest";
}
SendUrl = url;
}
}
}
|
apache-2.0
|
C#
|
31d17e5e9d3c545c5f68a545ba41ae36196cadce
|
Split out extensions for Entity Framework, Azure Storage, and Mongo. These are now separate projects (and NuGet packages) that all reference the Tables project (which again references the core service project). New NuGet packages are creates and references added.
|
Azure/azure-mobile-services-quickstarts,brettsam/azure-mobile-services-quickstarts,Azure/azure-mobile-apps-quickstarts,soninaren/azure-mobile-services-quickstarts,aziel/azure-mobile-services-quickstarts,Azure/azure-mobile-services-quickstarts,Azure/azure-mobile-apps-quickstarts,jwallra/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-apps-quickstarts,soninaren/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-services-quickstarts,phvannor/azure-mobile-services-quickstarts,brettsam/azure-mobile-services-quickstarts,fabiocav/azure-mobile-services-quickstarts,soninaren/azure-mobile-services-quickstarts,fabiocav/azure-mobile-services-quickstarts,Azure/azure-mobile-services-quickstarts,fabiocav/azure-mobile-services-quickstarts,jwallra/azure-mobile-services-quickstarts,aziel/azure-mobile-services-quickstarts,jwallra/azure-mobile-services-quickstarts,aziel/azure-mobile-services-quickstarts,Azure/azure-mobile-apps-quickstarts,shrishrirang/azure-mobile-apps-quickstarts,Azure/azure-mobile-services-quickstarts,lindydonna/azure-mobile-apps-quickstarts,lindydonna/azure-mobile-apps-quickstarts,Azure/azure-mobile-apps-quickstarts,brettsam/azure-mobile-services-quickstarts,fabiocav/azure-mobile-services-quickstarts,soninaren/azure-mobile-services-quickstarts,phvannor/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-apps-quickstarts,shrishrirang/azure-mobile-apps-quickstarts,aziel/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-services-quickstarts,phvannor/azure-mobile-services-quickstarts,phvannor/azure-mobile-services-quickstarts,lindydonna/azure-mobile-apps-quickstarts,brettsam/azure-mobile-services-quickstarts,Azure/azure-mobile-services-quickstarts,Azure/azure-mobile-apps-quickstarts,jwallra/azure-mobile-services-quickstarts,lindydonna/azure-mobile-apps-quickstarts,shrishrirang/azure-mobile-apps-quickstarts,aziel/azure-mobile-services-quickstarts,aziel/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-apps-quickstarts,shrishrirang/azure-mobile-services-quickstarts,fabiocav/azure-mobile-services-quickstarts,soninaren/azure-mobile-services-quickstarts,brettsam/azure-mobile-services-quickstarts,phvannor/azure-mobile-services-quickstarts,fabiocav/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-services-quickstarts,shrishrirang/azure-mobile-services-quickstarts,jwallra/azure-mobile-services-quickstarts,Azure/azure-mobile-apps-quickstarts,Azure/azure-mobile-services-quickstarts,phvannor/azure-mobile-services-quickstarts,brettsam/azure-mobile-services-quickstarts,jwallra/azure-mobile-services-quickstarts,soninaren/azure-mobile-services-quickstarts,lindydonna/azure-mobile-apps-quickstarts,lindydonna/azure-mobile-apps-quickstarts
|
Quickstart/ZUMOAPPNAMEService/DataObjects/TodoItem.cs
|
Quickstart/ZUMOAPPNAMEService/DataObjects/TodoItem.cs
|
using Microsoft.WindowsAzure.Mobile.Service;
namespace ZUMOAPPNAMEService.DataObjects
{
public class TodoItem : EntityData
{
public string Text { get; set; }
public bool Complete { get; set; }
}
}
|
using Microsoft.WindowsAzure.Mobile.Service;
namespace ZUMOAPPNAMEService.DataObjects
{
public class TodoItem : TableData
{
public string Text { get; set; }
public bool Complete { get; set; }
}
}
|
apache-2.0
|
C#
|
8b68b2e4f7a2156b35e93811f476df565c525e1f
|
Bump version to 3.3
|
robv8r/FluentValidation,cecilphillip/FluentValidation,roend83/FluentValidation,regisbsb/FluentValidation,mgmoody42/FluentValidation,deluxetiky/FluentValidation,IRlyDontKnow/FluentValidation,ruisebastiao/FluentValidation,GDoronin/FluentValidation,pacificIT/FluentValidation,olcayseker/FluentValidation,roend83/FluentValidation,glorylee/FluentValidation
|
src/CommonAssemblyInfo.cs
|
src/CommonAssemblyInfo.cs
|
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2011")]
[assembly : ComVisible(false)]
[assembly : AssemblyVersion("3.3.0.0")]
[assembly : AssemblyFileVersion("3.3.0.0")]
[assembly: CLSCompliant(true)]
#if !SILVERLIGHT
[assembly: AllowPartiallyTrustedCallers]
#endif
|
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2011")]
[assembly : ComVisible(false)]
[assembly : AssemblyVersion("3.2.0.0")]
[assembly : AssemblyFileVersion("3.2.0.0")]
[assembly: CLSCompliant(true)]
#if !SILVERLIGHT
[assembly: AllowPartiallyTrustedCallers]
#endif
|
apache-2.0
|
C#
|
6df9a71818c8ca7a59b079f575a3081d2969e282
|
fix style
|
ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework
|
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
|
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new AudioCollectionManager<AdjustableAudioComponent>();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());
// in a seperate thread start processing the queue
new Thread(() => manager.Update()).Start();
// wait a little for beginning of the update to start
Thread.Sleep(4);
Assert.DoesNotThrow(() => manager.Dispose());
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
private class TestingAdjustableAudioComponent : AdjustableAudioComponent {}
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new AudioCollectionManager<AdjustableAudioComponent>();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());
// in a seperate thread start processing the queue
new Thread(() => manager.Update()).Start();
// wait a little for beginning of the update to start
Thread.Sleep(4);
Assert.DoesNotThrow(() => manager.Dispose());
}
}
}
|
mit
|
C#
|
73d09328db749b4d6f114a7ac714863eb5ccd1d6
|
Fix for crash when using dot syntax for read count when target doesn't exist
|
inkle/ink,ghostpattern/ink,ghostpattern/ink,inkle/ink,ivaylo5ev/ink,ivaylo5ev/ink
|
inklecate/ParsedHierarchy/VariableReference.cs
|
inklecate/ParsedHierarchy/VariableReference.cs
|
using System.Collections.Generic;
namespace Inklewriter.Parsed
{
internal class VariableReference : Expression
{
public string name {
get {
if (path != null && path.Count == 1)
return path [0];
else
return null;
}
}
public List<string> path;
public VariableReference (List<string> path)
{
this.path = path;
}
public override void GenerateIntoContainer (Runtime.Container container)
{
_runtimeVarRef = new Runtime.VariableReference (name);
container.AddContent(_runtimeVarRef);
}
public override void ResolveReferences (Story context)
{
base.ResolveReferences (context);
// Is it a read count?
var parsedPath = new Path (path);
var targetForReadCount = parsedPath.ResolveFromContext (this);
if (targetForReadCount) {
_runtimeVarRef.pathForVisitCount = targetForReadCount.runtimePath;
_runtimeVarRef.name = null;
return;
}
// Definitely a read count, but wasn't found?
else if (path.Count > 1) {
Error ("Could not find target for read count: " + parsedPath);
return;
}
if (!context.ResolveVariableWithName (this.name, fromNode: this)) {
var forcedResolveObject = parsedPath.ResolveFromContext (this, forceSearchAnywhere:true);
if (forcedResolveObject) {
var suggestedDotSepReadPath = forcedResolveObject.PathRelativeTo (this).dotSeparatedComponents;
Error ("Unresolved variable: " + this.ToString () + ". Did you mean '" + suggestedDotSepReadPath + "' (as a read count)?");
} else {
Error("Unresolved variable: "+this.ToString()+" after searching: "+this.descriptionOfScope, this);
}
}
}
public override string ToString ()
{
return string.Join(".", path);
}
Runtime.VariableReference _runtimeVarRef;
}
}
|
using System.Collections.Generic;
namespace Inklewriter.Parsed
{
internal class VariableReference : Expression
{
public string name {
get {
if (path != null && path.Count == 1)
return path [0];
else
return null;
}
}
public List<string> path;
public VariableReference (List<string> path)
{
this.path = path;
}
public override void GenerateIntoContainer (Runtime.Container container)
{
_runtimeVarRef = new Runtime.VariableReference (name);
container.AddContent(_runtimeVarRef);
}
public override void ResolveReferences (Story context)
{
base.ResolveReferences (context);
// Is it a read count?
var parsedPath = new Path (path);
var targetForReadCount = parsedPath.ResolveFromContext (this);
if (targetForReadCount) {
_runtimeVarRef.pathForVisitCount = targetForReadCount.runtimePath;
_runtimeVarRef.name = null;
return;
}
if (!context.ResolveVariableWithName (this.name, fromNode: this)) {
var forcedResolveObject = parsedPath.ResolveFromContext (this, forceSearchAnywhere:true);
if (forcedResolveObject) {
var suggestedDotSepReadPath = forcedResolveObject.PathRelativeTo (this).dotSeparatedComponents;
Error ("Unresolved variable: " + this.ToString () + ". Did you mean '" + suggestedDotSepReadPath + "' (as a read count)?");
} else {
Error("Unresolved variable: "+this.ToString()+" after searching: "+this.descriptionOfScope, this);
}
}
}
public override string ToString ()
{
return string.Join(".", path);
}
Runtime.VariableReference _runtimeVarRef;
}
}
|
mit
|
C#
|
6ae3430ca3f502d1e6460ed5ae85ccb52b0d1943
|
Move feature ideas to GitHub issue tracker
|
DanRigby/ChatRelay
|
ChatRelay/Program.cs
|
ChatRelay/Program.cs
|
using System;
namespace ChatRelay
{
class Program
{
private static readonly Relay relay = new Relay();
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
Run();
}
public static void Run()
{
relay.Stop();
try
{
relay.Start();
}
catch (Exception ex) when (ex.GetType() == typeof(RelayConfigurationException))
{
Console.WriteLine($"ERROR: {ex.Message}");
return;
}
while (true)
{
char command = Console.ReadKey(true).KeyChar;
if (command == 'q')
{
Console.WriteLine("Quitting...");
relay.Stop();
return;
}
if (command == 'r')
{
Console.WriteLine("Restarting...");
relay.Stop();
relay.Start();
}
}
}
private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine($"EXCEPTION: {e.ExceptionObject}");
Run();
}
}
}
|
using System;
namespace ChatRelay
{
class Program
{
private static readonly Relay relay = new Relay();
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
Run();
}
public static void Run()
{
relay.Stop();
try
{
relay.Start();
}
catch (Exception ex) when (ex.GetType() == typeof(RelayConfigurationException))
{
Console.WriteLine($"ERROR: {ex.Message}");
return;
}
while (true)
{
char command = Console.ReadKey(true).KeyChar;
if (command == 'q')
{
Console.WriteLine("Quitting...");
relay.Stop();
return;
}
if (command == 'r')
{
Console.WriteLine("Restarting...");
relay.Stop();
relay.Start();
}
}
}
private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine($"EXCEPTION: {e.ExceptionObject}");
Run();
}
}
}
// TODO: The adapters use a Connect() Disconnect() naming convention,
// but right now they don't support reconnecting as Disconnect() is treated as more of a Dispose.
// Should probably change the naming structure or code layout to fix this. Maybe Connect/Open and Dispose?
// Alternatively, actually support disconnecting and reconnecting though more error handling is required.
// TODO: Relay emotes.
// TODO: Bot commands.
// Request that the bot tell you who is in the room in another service (reply via DM).
// Request information on the other services, mainly URL.
// Tell you how many people are on the other services (status?).
// TODO: Test on Mono.
// TODO: Logging. Would be good to basically have two log providers, rotating file on disk and console output.
// Ex, replace Console.WriteLine calls with logging calls.
// TODO: Connection monitoring. Heartbeat? IRC has Ping/Pong.
// TODO: Really think through error handling and resiliency in terms of disconnects/reconnects.
// May have to look for an alternative to the Slack API library we're using as it doesn't handling things like this well.
|
mit
|
C#
|
9a69d9869f0381849df937baf2a36e3f81f7ae40
|
Increase version to 2.4.2
|
Azure/amqpnetlite
|
src/Properties/Version.cs
|
src/Properties/Version.cs
|
// ------------------------------------------------------------------------------------
// 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 *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.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.1.0")]
[assembly: AssemblyFileVersion("2.4.2")]
[assembly: AssemblyInformationalVersion("2.4.2")]
|
// ------------------------------------------------------------------------------------
// 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 *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.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.1.0")]
[assembly: AssemblyFileVersion("2.4.1")]
[assembly: AssemblyInformationalVersion("2.4.1")]
|
apache-2.0
|
C#
|
cc6c24977067ee91e4275cebd1d6a79286b3d04e
|
Remove foo() method
|
henriqueprj/infixtopostfix
|
test/MathParser.Tests/InfixToPostfixConverterTest.cs
|
test/MathParser.Tests/InfixToPostfixConverterTest.cs
|
using System;
using FluentAssertions;
using Xunit;
namespace MathParser.Tests
{
public class InfixToPostfixConverterTest
{
[Fact]
public void Soma_com_dois_operandos()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("2 + 2");
result.Should().Be("2 2 +");
}
[Fact]
public void Soma_e_multiplicacao()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("2 + 2 * 4");
result.Should().Be("2 2 4 * +");
}
[Fact]
public void Soma_com_parentesis_e_multiplicacao()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("(2 + 2) * 4");
result.Should().Be("2 2 + 4 *");
}
[Fact]
public void Maior_precedencia_com_associatividade_direita_para_esquerda()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("4 * 5 ^ 2");
result.Should().Be("4 5 2 ^ *");
}
[Fact]
public void Expressao_complexa()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3");
result.Should().Be("3 4 2 * 1 5 - 2 3 ^ ^ / +");
}
}
}
|
using System;
using FluentAssertions;
using Xunit;
namespace MathParser.Tests
{
public class InfixToPostfixConverterTest
{
[Fact]
public void Soma_com_dois_operandos()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("2 + 2");
result.Should().Be("2 2 +");
}
[Fact]
public void Soma_e_multiplicacao()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("2 + 2 * 4");
result.Should().Be("2 2 4 * +");
}
[Fact]
public void Soma_com_parentesis_e_multiplicacao()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("(2 + 2) * 4");
result.Should().Be("2 2 + 4 *");
}
[Fact]
public void Maior_precedencia_com_associatividade_direita_para_esquerda()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("4 * 5 ^ 2");
result.Should().Be("4 5 2 ^ *");
}
[Fact]
public void Expressao_complexa()
{
var converter = new InfixToPostfixConverter();
var result = converter.Convert("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3");
result.Should().Be("3 4 2 * 1 5 - 2 3 ^ ^ / +");
}
private string Foo()
{
return "Bar";
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.