source
stringclasses 1
value | id
stringlengths 40
40
| language
stringclasses 2
values | date
stringclasses 1
value | author
stringclasses 1
value | url
stringclasses 1
value | title
stringclasses 1
value | extra
stringlengths 528
1.53k
| quality_signals
stringlengths 139
178
| text
stringlengths 6
1.05M
|
---|---|---|---|---|---|---|---|---|---|
TheStack | b5dde8ac44b6f3b7bbba0e3d13f0fed0be234b5e | C#code:C# | {"size": 7862, "ext": "cs", "max_stars_repo_path": "PRI.Messaging.Patterns.Analyzer/PRI.Messaging.Patterns.Analyzer/Utility/Utilities.cs", "max_stars_repo_name": "peteraritchie/Messaging.Patterns", "max_stars_repo_stars_event_min_datetime": "2016-05-21T16:12:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T23:07:23.000Z", "max_issues_repo_path": "PRI.Messaging.Patterns.Analyzer/PRI.Messaging.Patterns.Analyzer/Utility/Utilities.cs", "max_issues_repo_name": "peteraritchie/Messaging.Patterns", "max_issues_repo_issues_event_min_datetime": "2016-10-07T20:35:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-18T16:14:17.000Z", "max_forks_repo_path": "PRI.Messaging.Patterns.Analyzer/PRI.Messaging.Patterns.Analyzer/Utility/Utilities.cs", "max_forks_repo_name": "peteraritchie/Messaging.Patterns", "max_forks_repo_forks_event_min_datetime": "2016-06-16T15:38:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-12T16:40:27.000Z"} | {"max_stars_count": 7.0, "max_issues_count": 4.0, "max_forks_count": 4.0, "avg_line_length": 40.3179487179, "max_line_length": 219, "alphanum_fraction": 0.7760111931} | using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using PRI.Messaging.Primitives;
namespace PRI.Messaging.Patterns.Analyzer.Utility
{
internal static class Utilities
{
public static readonly string HandlerClassSuffix = "Handler";
public static readonly string CommandMessageClassSuffix = "Command";
public static bool IsRequestAsync(IMethodSymbol methodSymbolInfo)
{
if (methodSymbolInfo.Arity == 0 || !methodSymbolInfo.IsGenericMethod) return false;
var matchingMethod = Helpers.GetRequestAsyncInvocationMethodInfo(methodSymbolInfo);
if (matchingMethod != null)
{
return true;
}
return false;
}
public static ClassDeclarationSyntax MessageHandlerDeclaration(INamedTypeSymbol namedMessageTypeSymbol,
SyntaxGenerator generator, BlockSyntax handleBodyBlock, SyntaxToken handleMethodParameterName)
{
var messageTypeSyntax = namedMessageTypeSymbol.ToTypeSyntax(generator);
var eventHandlerDeclaration = SyntaxFactory.ClassDeclaration($"{namedMessageTypeSymbol.Name}{HandlerClassSuffix}")
.WithModifiers(
SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.WithBaseList(
SyntaxFactory.BaseList(
SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(
SyntaxFactory.SimpleBaseType(
SyntaxFactory.GenericName($"{typeof(IConsumer<IMessage>).Namespace}.{nameof(IConsumer<IMessage>)}")
.WithTypeArgumentList(
SyntaxFactory.TypeArgumentList(
SyntaxFactory.SingletonSeparatedList(
messageTypeSyntax)))))));
if (namedMessageTypeSymbol.IsGenericType)
{
eventHandlerDeclaration =
eventHandlerDeclaration.WithTypeParameterList(
SyntaxFactory.TypeParameterList(
SyntaxFactory.SeparatedList(
namedMessageTypeSymbol.TypeParameters.Select(generator.TypeExpression)
.Select(e => SyntaxFactory.TypeParameter(e.GetFirstToken())))))
.AddConstraintClauses(
namedMessageTypeSymbol.TypeParameters.Select(typeParameterSymbol => SyntaxFactory.TypeParameterConstraintClause(
SyntaxFactory.IdentifierName(typeParameterSymbol.Name),
SyntaxFactory.SeparatedList(typeParameterSymbol.GetTypeParameterConstraints(generator)))).ToArray());
}
eventHandlerDeclaration = eventHandlerDeclaration
.WithMembers(
SyntaxFactory.SingletonList<MemberDeclarationSyntax>(
SyntaxFactory.MethodDeclaration(
SyntaxFactory.PredefinedType(
SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
SyntaxFactory.Identifier(nameof(IConsumer<IMessage>.Handle)))
.WithModifiers(
SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.WithParameterList(
SyntaxFactory.ParameterList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Parameter(handleMethodParameterName)
.WithType(messageTypeSyntax)
)))
.WithBody(handleBodyBlock)))
.WithAdditionalAnnotations(Formatter.Annotation);
return eventHandlerDeclaration;
}
public static void GetRequestAsyncInfo(MemberAccessExpressionSyntax requestAsyncMemberAccess, SemanticModel model, out INamedTypeSymbol messageType, out INamedTypeSymbol eventType, out INamedTypeSymbol errorEventType)
{
var methodSymbolInfo = model.GetSymbolInfo(requestAsyncMemberAccess).Symbol as IMethodSymbol;
if (methodSymbolInfo == null || methodSymbolInfo.TypeArguments.Length < 3)
{
throw new InvalidOperationException();
}
messageType = (INamedTypeSymbol) methodSymbolInfo.TypeArguments.ElementAt(0);
eventType = (INamedTypeSymbol) methodSymbolInfo.TypeArguments.ElementAt(1);
errorEventType = (INamedTypeSymbol) methodSymbolInfo.TypeArguments.ElementAt(2);
}
#if false
private static bool IsMember(SyntaxNode[] childNodes, SemanticModel semanticModel,
CancellationToken cancellationToken, Func<IMethodSymbol, MethodInfo> tryGetMatchingMethodInfo)
{
var methodExpression = childNodes.ElementAt(1);
var methodSymbolInfo = semanticModel
.GetSymbolInfo(methodExpression, cancellationToken)
.Symbol as IMethodSymbol;
if (methodSymbolInfo == null)
{
return false;
}
return tryGetMatchingMethodInfo(methodSymbolInfo) != null;
}
public static bool IsHandle(SyntaxNode[] childNodes, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return IsMember(childNodes, semanticModel, cancellationToken,
methodSymbolInfo => !methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity == 0
? Helpers.GetHandleInvocationMethodInfo(methodSymbolInfo)
: null);
}
public static bool IsRequestAsync(SyntaxNode[] childNodes, SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return IsMember(childNodes, semanticModel, cancellationToken,
methodSymbolInfo => methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity > 1
? Helpers.GetRequestAsyncInvocationMethodInfo(methodSymbolInfo)
: null);
}
public static bool IsSend(SyntaxNode[] childNodes, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return IsMember(childNodes, semanticModel, cancellationToken,
methodSymbolInfo => methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity == 1
? Helpers.GetSendInvocationMethodInfo(methodSymbolInfo)
: null);
}
public static bool IsPublish(SyntaxNode[] childNodes, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return IsMember(childNodes, semanticModel, cancellationToken,
methodSymbolInfo => methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity == 1
? Helpers.GetPublishInvocationMethodInfo(methodSymbolInfo)
: null);
}
#endif
public static bool IsMember(SimpleNameSyntax name, SemanticModel semanticModel, CancellationToken cancellationToken, Func<IMethodSymbol, MethodInfo> tryGetMatchingMethodInfo)
{
var methodSymbolInfo = semanticModel
.GetSymbolInfo(name, cancellationToken)
.Symbol as IMethodSymbol;
if (methodSymbolInfo == null)
{
return false;
}
return tryGetMatchingMethodInfo(methodSymbolInfo) != null;
}
public static bool IsMember(SimpleNameSyntax name, MethodInfo methodInfo, SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var methodSymbolInfo = semanticModel
.GetSymbolInfo(name, cancellationToken)
.Symbol as IMethodSymbol;
if (methodSymbolInfo == null)
{
return false;
}
return methodSymbolInfo.IsSymbolOf(methodInfo);
}
public static bool IsSend(SimpleNameSyntax name, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return IsMember(name, semanticModel, cancellationToken,
methodSymbolInfo => methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity == 1
? Helpers.GetSendInvocationMethodInfo(methodSymbolInfo)
: null);
}
public static bool IsHandle(SimpleNameSyntax name, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return IsMember(name, semanticModel, cancellationToken,
methodSymbolInfo => !methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity == 0
? Helpers.GetHandleInvocationMethodInfo(methodSymbolInfo)
: null);
}
public static bool IsPublish(SimpleNameSyntax name, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return IsMember(name, semanticModel, cancellationToken,
methodSymbolInfo => methodSymbolInfo.IsGenericMethod && methodSymbolInfo.Arity == 1
? Helpers.GetPublishInvocationMethodInfo(methodSymbolInfo)
: null);
}
}
} |
||||
TheStack | b5e1994cf91f1734c6d8f52d6fa0382433379162 | C#code:C# | {"size": 2291, "ext": "cs", "max_stars_repo_path": "src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/Schema/ClrNamespaceUriParser.cs", "max_stars_repo_name": "jonfortescue/wpf", "max_stars_repo_stars_event_min_datetime": "2021-05-02T19:53:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T09:13:09.000Z", "max_issues_repo_path": "src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/Schema/ClrNamespaceUriParser.cs", "max_issues_repo_name": "jonfortescue/wpf", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/Schema/ClrNamespaceUriParser.cs", "max_forks_repo_name": "jonfortescue/wpf", "max_forks_repo_forks_event_min_datetime": "2021-01-20T08:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T08:04:57.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 32.7285714286, "max_line_length": 113, "alphanum_fraction": 0.5517241379} | // 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.Xaml.MS.Impl;
namespace System.Xaml.Schema
{
internal static class ClrNamespaceUriParser
{
public static string GetUri(string clrNs, string assemblyName)
{
return string.Format(TypeConverterHelper.InvariantEnglishUS, KnownStrings.UriClrNamespace + ":{0};" +
KnownStrings.UriAssembly + "={1}", clrNs, assemblyName);
}
public static bool TryParseUri(string uriInput, out string clrNs, out string assemblyName)
{
clrNs = null;
assemblyName = null;
// xmlns:foo="clr-namespace:System.Windows;assembly=myassemblyname"
// xmlns:bar="clr-namespace:MyAppsNs"
// xmlns:spam="clr-namespace:MyAppsNs;assembly="
int colonIdx = KS.IndexOf(uriInput, ':');
if (colonIdx == -1)
{
return false;
}
string keyword = uriInput.Substring(0, colonIdx);
if (!KS.Eq(keyword, KnownStrings.UriClrNamespace))
{
return false;
}
int clrNsStartIdx = colonIdx + 1;
int semicolonIdx = KS.IndexOf(uriInput, ';');
if (semicolonIdx == -1)
{
clrNs = uriInput.Substring(clrNsStartIdx);
assemblyName = null;
return true;
}
else
{
int clrnsLength = semicolonIdx - clrNsStartIdx;
clrNs = uriInput.Substring(clrNsStartIdx, clrnsLength);
}
int assemblyKeywordStartIdx = semicolonIdx+1;
int equalIdx = KS.IndexOf(uriInput, '=');
if (equalIdx == -1)
{
return false;
}
keyword = uriInput.Substring(assemblyKeywordStartIdx, equalIdx - assemblyKeywordStartIdx);
if (!KS.Eq(keyword, KnownStrings.UriAssembly))
{
return false;
}
assemblyName = uriInput.Substring(equalIdx + 1);
return true;
}
}
}
|
||||
TheStack | b5e385dfa190828875009b02debaf336a31219c1 | C#code:C# | {"size": 2531, "ext": "cs", "max_stars_repo_path": "src/Cake.Kubectl/Set/Resources/Kubectl.Alias.SetResources.cs", "max_stars_repo_name": "cake-contrib/Cake.Kubectl", "max_stars_repo_stars_event_min_datetime": "2019-12-11T21:27:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T21:27:13.000Z", "max_issues_repo_path": "src/Cake.Kubectl/Set/Resources/Kubectl.Alias.SetResources.cs", "max_issues_repo_name": "cake-contrib/Cake.Kubernetes", "max_issues_repo_issues_event_min_datetime": "2020-01-16T16:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-14T12:39:54.000Z", "max_forks_repo_path": "src/Cake.Kubectl/Set/Resources/Kubectl.Alias.SetResources.cs", "max_forks_repo_name": "cake-contrib/Cake.Kubectl", "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:00:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T00:44:27.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 2.0, "max_forks_count": 2.0, "avg_line_length": 45.1964285714, "max_line_length": 233, "alphanum_fraction": 0.7376531015} | using Cake.Core;
using Cake.Core.Annotations;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Cake.Kubectl
{
partial class KubectlAliases
{
/// <summary>
/// Specify compute resource requirements (cpu, memory) for any resource that defines a pod template. If a pod is successfully scheduled, it is guaranteed the amount of resource requested, but may burst up to its specified limits.
///
///
/// for each compute resource, if a limit is specified and a request is omitted, the request will default to the limit.
///
/// Possible resources include (case insensitive): Use "kubectl api-resources" for a complete list of supported resources..
/// </summary>
/// <param name="context">The context.</param>
/// <param name="settings">The settings.</param>
[CakeMethodAlias]
public static void KubectlSetResources(this ICakeContext context, KubectlSetResourcesSettings settings)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var arguments = new string[0];
var runner = new GenericRunner<KubectlSetResourcesSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
runner.Run("set resources", settings ?? new KubectlSetResourcesSettings(), arguments);
}
/// <summary>
/// Specify compute resource requirements (cpu, memory) for any resource that defines a pod template. If a pod is successfully scheduled, it is guaranteed the amount of resource requested, but may burst up to its specified limits.
///
///
/// for each compute resource, if a limit is specified and a request is omitted, the request will default to the limit.
///
/// Possible resources include (case insensitive): Use "kubectl api-resources" for a complete list of supported resources..
/// </summary>
/// <param name="context">The context.</param>
/// <param name="settings">The settings.</param>
/// <returns>Output lines.</returns>
[CakeMethodAlias]
public static IEnumerable<string> KubectlSetResourcesWithResult(this ICakeContext context, KubectlSetResourcesSettings settings)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var arguments = new string[0];
var runner = new GenericRunner<KubectlSetResourcesSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
return runner.RunWithResult("set resources", settings ?? new KubectlSetResourcesSettings(), arguments);
}
}
}
|
||||
TheStack | b5e3a65ec244410b9dfdf841ad9f295839724d02 | C#code:C# | {"size": 1210, "ext": "cs", "max_stars_repo_path": "docs/vs-2015/snippets/csharp/VS_Snippets_Wpf/HostingAxInWpf/CSharp/HostingAxInWpf/window1.xaml.cs", "max_stars_repo_name": "wyossi/visualstudio-docs", "max_stars_repo_stars_event_min_datetime": "2019-04-06T02:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-06T02:01:40.000Z", "max_issues_repo_path": "docs/vs-2015/snippets/csharp/VS_Snippets_Wpf/HostingAxInWpf/CSharp/HostingAxInWpf/window1.xaml.cs", "max_issues_repo_name": "wyossi/visualstudio-docs", "max_issues_repo_issues_event_min_datetime": "2018-10-08T17:51:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-08T17:51:50.000Z", "max_forks_repo_path": "docs/vs-2015/snippets/csharp/VS_Snippets_Wpf/HostingAxInWpf/CSharp/HostingAxInWpf/window1.xaml.cs", "max_forks_repo_name": "wyossi/visualstudio-docs", "max_forks_repo_forks_event_min_datetime": "2020-01-29T16:31:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T07:00:15.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": 3.0, "avg_line_length": 28.8095238095, "max_line_length": 86, "alphanum_fraction": 0.6214876033} | //<snippet10>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;
namespace HostingAxInWpf
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//<snippet11>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Create the interop host control.
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
// Create the ActiveX control.
AxWMPLib.AxWindowsMediaPlayer axWmp = new AxWMPLib.AxWindowsMediaPlayer();
// Assign the ActiveX control as the host control's child.
host.Child = axWmp;
// Add the interop host control to the Grid
// control's collection of child controls.
this.grid1.Children.Add(host);
// Play a .wav file with the ActiveX control.
axWmp.URL = @"C:\Windows\Media\tada.wav";
}
//</snippet11>
}
}
//</snippet10> |
||||
TheStack | b5e3c8fc22f0e3d15bc95b7ecfec67355a3b0e9b | C#code:C# | {"size": 16200, "ext": "cs", "max_stars_repo_path": "Assets/Example/8.CustomWidgets/4.GradientCircularProgressIndicator/GradientCircularProgressIndicatorExample.cs", "max_stars_repo_name": "liangxiegame/QF.UIWidgets", "max_stars_repo_stars_event_min_datetime": "2019-04-29T08:15:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T06:04:01.000Z", "max_issues_repo_path": "Assets/Example/8.CustomWidgets/4.GradientCircularProgressIndicator/GradientCircularProgressIndicatorExample.cs", "max_issues_repo_name": "liangxiegame/QF.UIWidgets", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Example/8.CustomWidgets/4.GradientCircularProgressIndicator/GradientCircularProgressIndicatorExample.cs", "max_forks_repo_name": "liangxiegame/QF.UIWidgets", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 8.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 42.4083769634, "max_line_length": 117, "alphanum_fraction": 0.3328395062} | using System;
using System.Collections;
using System.Collections.Generic;
using Unity.UIWidgets.animation;
using Unity.UIWidgets.engine;
using Unity.UIWidgets.material;
using Unity.UIWidgets.painting;
using Unity.UIWidgets.rendering;
using Unity.UIWidgets.scheduler;
using Unity.UIWidgets.ui;
using Unity.UIWidgets.widgets;
namespace LearnUIWidgets
{
public class GradientCircularProgressIndicatorExample : UIWidgetsPanel
{
protected override Widget createWidget()
{
return new MaterialApp(
home: new Scaffold(
body: new GradientCircularProgressRoute()));
}
class GradientCircularProgressRoute : StatefulWidget
{
public override State createState()
{
return new GradientCircularProgressState();
}
}
class GradientCircularProgressState : State<GradientCircularProgressRoute>
,TickerProvider
{
private AnimationController _animationController;
public override void initState()
{
base.initState();
_animationController = new AnimationController(vsync: this, duration: TimeSpan.FromSeconds(3));
bool isForward = true;
_animationController.addStatusListener((status) =>
{
if (status == AnimationStatus.forward)
{
isForward = true;
}
else if (status == AnimationStatus.completed ||
status == AnimationStatus.dismissed)
{
if (isForward)
{
_animationController.reverse();
}
else
{
_animationController.forward();
}
}
else if (status == AnimationStatus.reverse)
{
isForward = false;
}
});
_animationController.forward();
}
public override void dispose()
{
_animationController.dispose();
_animationController = null;
base.dispose();
}
public override Widget build(BuildContext context)
{
return new SingleChildScrollView(
child: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: new List<Widget>()
{
new AnimatedBuilder(
animation:_animationController,
builder:((buildContext, child) =>
{
return new Padding(
padding: EdgeInsets.symmetric(vertical: 16.0f),
child: new Column(
children: new List<Widget>()
{
new Wrap(
spacing: 10.0f,
runSpacing: 16.0f,
children: new List<Widget>()
{
new GradientCircularProgressIndicator(
// No gradient
colors: new List<Color>() {Colors.blue, Colors.blue},
radius: 50.0f,
strokeWidth: 3.0f,
value: _animationController.value
),
new GradientCircularProgressIndicator(
colors: new List<Color> {Colors.red, Colors.orange},
radius: 50.0f,
strokeWidth: 3.0f,
value: _animationController.value
),
new GradientCircularProgressIndicator(
colors: new List<Color>
{Colors.red, Colors.orange, Colors.red},
radius: 50.0f,
strokeWidth: 3.0f,
value: _animationController.value
),
new GradientCircularProgressIndicator(
colors: new List<Color> {Colors.teal, Colors.cyan},
radius: 50.0f,
strokeWidth: 5.0f,
strokeCapRound: true,
value: new CurvedAnimation(
parent: _animationController,
curve: Curves.decelerate)
.value
),
new TurnBox(
turns: 1.0f / 8.0f,
child: new GradientCircularProgressIndicator(
colors: new List<Color>
{Colors.red, Colors.orange, Colors.red},
radius: 50.0f,
strokeWidth: 5.0f,
strokeCapRound: true,
backgroundColor: Colors.red[50],
totalAngle: (float) (1.5 * Math.PI),
value: new CurvedAnimation(
parent: _animationController,
curve: Curves.ease)
.value)
),
// new RotatedBox(
// quarterTurns: 1,
// child: GradientCircularProgressIndicator(
// colors: [Colors.blue[700], Colors.blue[200]],
// radius: 50.0,
// stokeWidth: 3.0,
// strokeCapRound: true,
// backgroundColor: Colors.transparent,
// value: _animationController.value),
// ),
new GradientCircularProgressIndicator(
colors: new List<Color>
{
Colors.red,
Colors.amber,
Colors.cyan,
Colors.green[200],
Colors.blue,
Colors.red
},
radius: 50.0f,
strokeWidth: 5.0f,
strokeCapRound: true,
value: _animationController.value
)
}
)
}
)
);
})
)
}
)
)
);
}
public Ticker createTicker(TickerCallback onTick)
{
return new Ticker(onTick);
}
}
}
public class GradientCircularProgressIndicator : StatelessWidget
{
public GradientCircularProgressIndicator(
float radius,
List<Color> colors,
float value,
float strokeWidth = 2.0f,
List<float> stops = null,
bool strokeCapRound = false,
Color backgroundColor = null,
float totalAngle = float.MinValue
)
{
mColors = colors;
mStrokeWidth = strokeWidth;
mRadius = radius;
mStrokeCapRound = strokeCapRound;
mStops = stops;
this.mBackgroundColor = backgroundColor ?? new Color(0xFFEEEEEE);
this.mValue = value;
this.mTotalAngle = totalAngle == float.MinValue ? (float)(Math.PI * 2) : totalAngle;
}
///粗细
private float mStrokeWidth;
/// 圆的半径
private float mRadius;
///两端是否为圆角
private bool mStrokeCapRound;
/// 当前进度,取值范围 [0.0-1.0]
private float mValue;
/// 进度条背景色
private Color mBackgroundColor;
/// 进度条的总弧度,2*PI为整圆,小于2*PI则不是整圆
private float mTotalAngle;
/// 渐变色数组
private List<Color> mColors;
/// 渐变色的终止点,对应colors属性
private List<float> mStops;
public override Widget build(BuildContext context)
{
float offset = 0;
if (mStrokeCapRound)
{
offset = (float) Math.Asin(mStrokeWidth / (mRadius * 2 - mStrokeWidth));
}
var _colors = mColors;
if (_colors == null)
{
Color color = Theme
.of(context)
.accentColor;
_colors = new List<Color>(){color, color};
}
return Transform.rotate(
degree: (float) (-Math.PI / 2.0f - offset),
child: new CustomPaint(
size: Size.fromRadius(mRadius),
painter: new GradientCircularProgressPainter(
stokeWidth: mStrokeWidth,
strokeCapRound: mStrokeCapRound,
backgroundColor: mBackgroundColor,
value: mValue,
total: mTotalAngle,
radius: mRadius,
colors: _colors
)
));
}
class GradientCircularProgressPainter : AbstractCustomPainter
{
public GradientCircularProgressPainter(
float value,
float radius,
List<Color> colors,
float stokeWidth = 10.0f,
bool strokeCapRound = false,
Color backgroundColor = null,
float total = float.MinValue
)
{
this.value = value;
this.radius = radius;
this.colors = colors;
this.stokeWidth = stokeWidth;
this.strokeCapRound = strokeCapRound;
this.backgroundColor = backgroundColor ?? new Color(0xFFEEEEEE);
this.total = total == float.MinValue ? (float) (Math.PI * 2) : total;
}
float stokeWidth;
bool strokeCapRound;
float? value;
Color backgroundColor;
List<Color> colors;
float total;
float radius;
List<float> stops;
public override void paint(Canvas canvas, Size size)
{
if (radius != null)
{
size = Size.fromRadius(radius);
}
float _offset = stokeWidth / 2.0f;
float _value = (value ?? 0.0f);
_value = _value.clamp(0.0f, 1.0f) * total;
float _start = 0.0f;
if (strokeCapRound)
{
_start = (float) Math.Asin(stokeWidth / (size.width - stokeWidth));
}
Rect rect = new Offset(_offset, _offset) & new Size(
size.width - stokeWidth,
size.height - stokeWidth
);
var paint = new Paint
{
strokeCap = strokeCapRound ? StrokeCap.round : StrokeCap.butt,
style = PaintingStyle.stroke,
strokeWidth = stokeWidth
};
// 先画背景
if (backgroundColor != Colors.transparent)
{
paint.color = backgroundColor;
canvas.drawArc(
rect,
_start,
total,
false,
paint
);
}
// 再画前景,应用渐变
if (_value > 0)
{
paint.shader = new SweepGradient(
startAngle: 0.0f,
endAngle: _value,
colors: colors,
stops: stops
).createShader(rect);
canvas.drawArc(
rect,
_start,
_value,
false,
paint
);
}
}
public override bool shouldRepaint(CustomPainter oldDelegate)
{
return true;
}
}
}
} |
||||
TheStack | b5e44ab117dbe065463d7ef59b149f4e09bbd9a7 | C#code:C# | {"size": 6409, "ext": "cs", "max_stars_repo_path": "src/Gemini.Modules.CodeEditor/LanguageDefinitionManager.cs", "max_stars_repo_name": "Aberro/gemini", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Gemini.Modules.CodeEditor/LanguageDefinitionManager.cs", "max_issues_repo_name": "Aberro/gemini", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gemini.Modules.CodeEditor/LanguageDefinitionManager.cs", "max_forks_repo_name": "Aberro/gemini", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 48.1879699248, "max_line_length": 189, "alphanum_fraction": 0.5818380403} | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Xml;
using Caliburn.Micro;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
namespace Gemini.Modules.CodeEditor
{
public static class CodeEditorDefaultLanguageDefinitions
{
[Export] public static ILanguageDefinition CSharp = new DefaultLanguageDefinition("C#", new[] {".cs"});
[Export] public static ILanguageDefinition JavaScript = new DefaultLanguageDefinition("JavaScript", new[] {".js"});
[Export] public static ILanguageDefinition HTML = new DefaultLanguageDefinition("HTML", new[] {".htm", ".html"});
[Export] public static ILanguageDefinition ASP = new DefaultLanguageDefinition("ASP/XHTML",
new[] {".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master"});
[Export] public static ILanguageDefinition Boo = new DefaultLanguageDefinition("Boo", new[] {".boo"});
[Export] public static ILanguageDefinition Coco = new DefaultLanguageDefinition("Coco", new[] {".atg"});
[Export] public static ILanguageDefinition CSS = new DefaultLanguageDefinition("CSS", new[] {".css"});
[Export] public static ILanguageDefinition CPP = new DefaultLanguageDefinition("C++", new[] {".c", ".h", ".cc", ".cpp", ".hpp"});
[Export] public static ILanguageDefinition Java = new DefaultLanguageDefinition("Java", new[] {".java"});
[Export] public static ILanguageDefinition Patch = new DefaultLanguageDefinition("Patch", new[] {".patch", ".diff"});
[Export] public static ILanguageDefinition PowerShell = new DefaultLanguageDefinition("PowerShell", new[] {".ps1", ".psm1", ".psd1"});
[Export] public static ILanguageDefinition PHP = new DefaultLanguageDefinition("PHP", new[] {".php"});
[Export] public static ILanguageDefinition TeX = new DefaultLanguageDefinition("TeX", new[] {".tex"});
[Export] public static ILanguageDefinition VBNET = new DefaultLanguageDefinition("VBNET", new[] {".vb"});
[Export] public static ILanguageDefinition XML = new DefaultLanguageDefinition("XML", (".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;" +
".xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;" +
".booproj;.build;.xfrm;.targets;.xaml;.xpt;" +
".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'));
[Export] public static ILanguageDefinition MarkDown = new DefaultLanguageDefinition("MarkDown", new[] {".md"});
}
[Export(typeof (LanguageDefinitionManager))]
public class LanguageDefinitionManager
{
private List<ILanguageDefinition> _languageDefinitions;
public List<ILanguageDefinition> LanguageDefinitions
{
get
{
if (_languageDefinitions == null)
{
_languageDefinitions = Initialize();
}
return _languageDefinitions;
}
}
public ILanguageDefinition GetDefinitionByExtension(string extension)
{
return LanguageDefinitions.FirstOrDefault(l => l.FileExtensions.Contains(extension));
}
private List<ILanguageDefinition> Initialize()
{
// Create built in language definitions
var languageDefinitions = new List<ILanguageDefinition>();
// Add imported definitions
foreach (ILanguageDefinition importedLanguage in IoC.GetAll<ILanguageDefinition>().Except(IoC.GetAll<ExcludeLanguageDefinition>().SelectMany(e => e.ExcludedLanguageDefinition)))
{
ILanguageDefinition defaultLanguage =
languageDefinitions.FirstOrDefault(
l => string.Equals(l.Name, importedLanguage.Name, StringComparison.InvariantCultureIgnoreCase));
if (defaultLanguage != null)
{
// Relace default language definition
languageDefinitions.Remove(defaultLanguage);
}
languageDefinitions.Add(importedLanguage);
}
// Scan SyntaxHighlighting folder for more languages
string path = Path.Combine(Directory.GetCurrentDirectory(), "SyntaxHighlighting");
if (!Directory.Exists(path))
return languageDefinitions;
List<string> highlightingFiles = Directory.GetFiles(path, "*.xshd").ToList();
char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
Dictionary<string, ILanguageDefinition> definitions = languageDefinitions.ToDictionary(l =>
{
char[] nameChars = l.Name.ToCharArray();
nameChars = nameChars.Except(invalidFileNameChars).ToArray();
return new string(nameChars);
}, l => l);
foreach (string highlightingFile in highlightingFiles)
{
string fileName = Path.GetFileNameWithoutExtension(highlightingFile);
if (string.IsNullOrEmpty(fileName))
{
continue;
}
ILanguageDefinition definition;
if (definitions.TryGetValue(fileName, out definition))
{
// Set custom highlighting file for existing language
definition.CustomSyntaxHighlightingFileName = highlightingFile;
}
else
{
try
{
XshdSyntaxDefinition syntaxDefinition;
using (var reader = new XmlTextReader(highlightingFile))
syntaxDefinition = HighlightingLoader.LoadXshd(reader);
// Create language based on highlighting file.
languageDefinitions.Add(new DefaultLanguageDefinition(syntaxDefinition));
}
catch
{
continue;
}
}
}
return languageDefinitions;
}
}
}
|
||||
TheStack | b5e52fa7c64f4b893061546bc741165139ccc876 | C#code:C# | {"size": 2826, "ext": "cs", "max_stars_repo_path": "source/tests/MyCouch.UnitTests.Net45/HttpRequestFactories/GetDocumentHttpRequestFactoryTests.cs", "max_stars_repo_name": "curit/mycouch", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/tests/MyCouch.UnitTests.Net45/HttpRequestFactories/GetDocumentHttpRequestFactoryTests.cs", "max_issues_repo_name": "curit/mycouch", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/tests/MyCouch.UnitTests.Net45/HttpRequestFactories/GetDocumentHttpRequestFactoryTests.cs", "max_forks_repo_name": "curit/mycouch", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.4827586207, "max_line_length": 117, "alphanum_fraction": 0.5725406936} | using System;
using FluentAssertions;
using MyCouch.HttpRequestFactories;
using MyCouch.Net;
using MyCouch.Requests;
using MyCouch.Testing;
using Xunit;
namespace MyCouch.UnitTests.HttpRequestFactories
{
public class GetDocumentHttpRequestFactoryTests : UnitTestsOf<GetDocumentHttpRequestFactory>
{
protected const string FakeId = "someId";
public GetDocumentHttpRequestFactoryTests()
{
SUT = new GetDocumentHttpRequestFactory();
}
[Fact]
public void When_configured_with_id_rev_and_other_param_It_yields_correct_url()
{
const string fakeRev = "someRev";
var request = CreateRequest(rev: fakeRev);
request.Conflicts = true;
WithHttpRequestFor(
request,
req =>
{
req.RelativeUrl.ToTestUriFromRelative().AbsolutePath.Should().EndWith("/" + FakeId);
req.RelativeUrl.ToTestUriFromRelative().Query.Should().Be("?rev=" + fakeRev + "&conflicts=true");
});
}
[Fact]
public void When_configured_with_id_It_yields_url_with_id()
{
var request = CreateRequest();
WithHttpRequestFor(
request,
req => req.RelativeUrl.ToTestUriFromRelative().AbsolutePath.Should().EndWith("/" + FakeId));
}
[Fact]
public void When_configured_with_rev_It_yields_url_with_rev()
{
const string fakeRev = "someRev";
var request = CreateRequest(rev: fakeRev);
WithHttpRequestFor(
request,
req =>
{
req.RelativeUrl.ToTestUriFromRelative().AbsolutePath.Should().EndWith("/" + FakeId);
req.RelativeUrl.ToTestUriFromRelative().Query.Should().Be("?rev=" + fakeRev);
});
}
[Fact]
public void When_configured_with_conflicts_It_yields_url_with_conflicts()
{
var request = CreateRequest();
request.Conflicts = true;
WithHttpRequestFor(
request,
req =>
{
req.RelativeUrl.ToTestUriFromRelative().AbsolutePath.Should().EndWith("/" + FakeId);
req.RelativeUrl.ToTestUriFromRelative().Query.Should().Be("?conflicts=true");
});
}
protected virtual GetDocumentRequest CreateRequest(string id = FakeId, string rev = null)
{
return new GetDocumentRequest(id, rev);
}
protected virtual void WithHttpRequestFor(GetDocumentRequest request, Action<HttpRequest> a)
{
var req = SUT.Create(request);
a(req);
}
}
} |
||||
TheStack | b5e673258b42da64a2f805718aeebb06cb79a985 | C#code:C# | {"size": 940, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Vignette.cs", "max_stars_repo_name": "KahVee/terrain-generator", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/Vignette.cs", "max_issues_repo_name": "KahVee/terrain-generator", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Vignette.cs", "max_forks_repo_name": "KahVee/terrain-generator", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.4848484848, "max_line_length": 89, "alphanum_fraction": 0.5063829787} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Vignette
{
public static float[,] GenerateEdges(int size, float a, float b) {
float[,] edgeArray = new float[size, size];
float sqrt2 = Mathf.Sqrt(2);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
float x = i / (float)size * 2 - 1;
float y = j / (float)size * 2 - 1;
//square vignette
//float k = Mathf.Max(Mathf.Abs(x), Mathf.Abs(y));
//circular vignette
float k = Mathf.Sqrt(x * x + y * y) / Mathf.Sqrt(2);
edgeArray[i, j] = Calculate(k, a, b);
}
}
return edgeArray;
}
static float Calculate(float value, float a, float b) {
return Mathf.Pow(value, a) / (Mathf.Pow(value, a) + Mathf.Pow(b - b * value, a));
}
}
|
||||
TheStack | b5e84d006145e21a60d0ef0340978e8db02be466 | C#code:C# | {"size": 245, "ext": "cs", "max_stars_repo_path": "Program.cs", "max_stars_repo_name": "Blue-Screen-Studios/AdminApp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Program.cs", "max_issues_repo_name": "Blue-Screen-Studios/AdminApp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Program.cs", "max_forks_repo_name": "Blue-Screen-Studios/AdminApp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.5, "max_line_length": 84, "alphanum_fraction": 0.5428571429} | using System;
namespace AdminApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Admin Test App Launched\nPress any key to close...");
Console.ReadKey();
}
}
}
|
||||
TheStack | b5e9ce7d43bc01b7d90bd8e6156de7712604fb79 | C#code:C# | {"size": 2252, "ext": "cs", "max_stars_repo_path": "FormBuilder/Validation/CredentialsValidatorAttribute.cs", "max_stars_repo_name": "burningice2866/CompositeC1Contrib.FormBuilder", "max_stars_repo_stars_event_min_datetime": "2016-09-20T11:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-04T17:26:47.000Z", "max_issues_repo_path": "FormBuilder/Validation/CredentialsValidatorAttribute.cs", "max_issues_repo_name": "burningice2866/CompositeC1Contrib.FormBuilder", "max_issues_repo_issues_event_min_datetime": "2016-07-13T16:50:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-12T12:23:07.000Z", "max_forks_repo_path": "FormBuilder/Validation/CredentialsValidatorAttribute.cs", "max_forks_repo_name": "burningice2866/CompositeC1Contrib.FormBuilder", "max_forks_repo_forks_event_min_datetime": "2020-05-06T16:45:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T16:45:08.000Z"} | {"max_stars_count": 4.0, "max_issues_count": 5.0, "max_forks_count": 1.0, "avg_line_length": 30.0266666667, "max_line_length": 102, "alphanum_fraction": 0.4777975133} | using System.Web.Security;
using Composite.C1Console.Security;
namespace CompositeC1Contrib.FormBuilder.Validation
{
public class CredentialsValidatorAttribute : FormValidationAttribute
{
private readonly string _passwordField;
public bool CheckUserName { get; set; }
public bool CheckEmail { get; set; }
public CredentialsValidatorAttribute(string passwordField) : this(null, passwordField) { }
public CredentialsValidatorAttribute(string message, string passwordField)
: base(message)
{
_passwordField = passwordField;
CheckUserName = false;
CheckEmail = true;
}
public override FormValidationRule CreateRule(FormField field)
{
var value = (string)field.Value;
var password = (string)field.OwningForm.Fields.Get(_passwordField).Value;
return CreateRule(field, new[] { field.Name, _passwordField }, () =>
{
var isValid = false;
if (!isValid && CheckUserName)
{
var user = Membership.GetUser(value);
isValid = IsValid(user);
}
if (!isValid && CheckEmail)
{
var username = Membership.GetUserNameByEmail(value);
if (username != null)
{
var user = Membership.GetUser(username);
if (user != null)
{
isValid = IsValid(user);
value = username;
}
}
}
if (!isValid)
{
return false;
}
return UserValidationFacade.IsLoggedIn() || Membership.ValidateUser(value, password);
});
}
private static bool IsValid(MembershipUser user)
{
if (user == null)
{
return false;
}
return user.IsApproved && !user.IsLockedOut;
}
}
}
|
||||
TheStack | b5ea72ff72e0902c681027d3624ccc756d2b64d2 | C#code:C# | {"size": 1023, "ext": "cs", "max_stars_repo_path": "CustomExcel/Program.cs", "max_stars_repo_name": "hawesome512/TripTester", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CustomExcel/Program.cs", "max_issues_repo_name": "hawesome512/TripTester", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CustomExcel/Program.cs", "max_forks_repo_name": "hawesome512/TripTester", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.0, "max_line_length": 268, "alphanum_fraction": 0.6803519062} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Data;
namespace CustomExcel
{
class Program
{
static void Main(string[] args)
{
Application excelApp = new Application();
Workbooks excelBooks = excelApp.Workbooks;
Workbook excelBook = excelBooks.Add(Missing.Value);
Worksheet excelSheet = excelBook.Sheets.get_Item(2);
excelSheet.Cells[1, 1] = "aaa";
excelBook.SaveAs(@"E:\My Work\手持编程器项目\TripTester\CustomExcel\bin\Debug\d", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelApp = null;
}
}
}
|
||||
TheStack | b5ebafe93e67c349fe49ec5b4990a7bebe6d6e53 | C#code:C# | {"size": 1616, "ext": "cs", "max_stars_repo_path": "Managed/main/GravitasPedestalConfig.cs", "max_stars_repo_name": "undancer/oni-data", "max_stars_repo_stars_event_min_datetime": "2021-12-09T16:08:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T16:08:20.000Z", "max_issues_repo_path": "Managed/main/GravitasPedestalConfig.cs", "max_issues_repo_name": "undancer/oni-data", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Managed/main/GravitasPedestalConfig.cs", "max_forks_repo_name": "undancer/oni-data", "max_forks_repo_forks_event_min_datetime": "2021-11-06T08:29:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T08:37:24.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 34.3829787234, "max_line_length": 283, "alphanum_fraction": 0.7896039604} | using System.Collections.Generic;
using TUNING;
using UnityEngine;
public class GravitasPedestalConfig : IBuildingConfig
{
public const string ID = "GravitasPedestal";
public override string[] GetDlcIds()
{
return DlcManager.AVAILABLE_EXPANSION1_ONLY;
}
public override BuildingDef CreateBuildingDef()
{
BuildingDef obj = BuildingTemplates.CreateBuildingDef("GravitasPedestal", 1, 2, "gravitas_pedestal_nice_kanim", 10, 30f, BUILDINGS.CONSTRUCTION_MASS_KG.TIER2, MATERIALS.RAW_MINERALS, 800f, BuildLocationRule.OnFloor, noise: NOISE_POLLUTION.NONE, decor: BUILDINGS.DECOR.BONUS.TIER0);
obj.DefaultAnimState = "pedestal_nice";
obj.Floodable = false;
obj.Overheatable = false;
obj.ViewMode = OverlayModes.Decor.ID;
obj.AudioCategory = "Glass";
obj.AudioSize = "small";
return obj;
}
public override void ConfigureBuildingTemplate(GameObject go, Tag prefab_tag)
{
go.AddOrGet<Storage>().SetDefaultStoredItemModifiers(new List<Storage.StoredItemModifier>(new Storage.StoredItemModifier[2]
{
Storage.StoredItemModifier.Seal,
Storage.StoredItemModifier.Preserve
}));
Prioritizable.AddRef(go);
SingleEntityReceptacle singleEntityReceptacle = go.AddOrGet<SingleEntityReceptacle>();
singleEntityReceptacle.AddDepositTag(GameTags.PedestalDisplayable);
singleEntityReceptacle.occupyingObjectRelativePosition = new Vector3(0f, 1.2f, -1f);
go.AddOrGet<DecorProvider>();
go.AddOrGet<ItemPedestal>();
go.AddOrGet<PedestalArtifactSpawner>();
go.GetComponent<KPrefabID>().AddTag(GameTags.Decoration);
}
public override void DoPostConfigureComplete(GameObject go)
{
}
}
|
||||
TheStack | b5ebc96921fcf49effd2be6861325882d5ebee1f | C#code:C# | {"size": 1392, "ext": "cs", "max_stars_repo_path": "NDB.Covid19/NDB.Covid19.iOS/Views/AuthenticationFlow/QuestionnaireCountries/CountryTableViewSource.cs", "max_stars_repo_name": "Sundhedsdatastyrelsen/Smittestop.Mobile", "max_stars_repo_stars_event_min_datetime": "2021-09-03T08:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T12:20:22.000Z", "max_issues_repo_path": "NDB.Covid19/NDB.Covid19.iOS/Views/AuthenticationFlow/QuestionnaireCountries/CountryTableViewSource.cs", "max_issues_repo_name": "Sundhedsdatastyrelsen/Smittestop.Mobile", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NDB.Covid19/NDB.Covid19.iOS/Views/AuthenticationFlow/QuestionnaireCountries/CountryTableViewSource.cs", "max_forks_repo_name": "Sundhedsdatastyrelsen/Smittestop.Mobile", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.6363636364, "max_line_length": 119, "alphanum_fraction": 0.6795977011} | using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using NDB.Covid19.ViewModels;
using UIKit;
namespace NDB.Covid19.iOS.Views.AuthenticationFlow.QuestionnaireCountries
{
public class CountryTableViewSource : UITableViewSource
{
private readonly List<CountryDetailsViewModel> _models = new List<CountryDetailsViewModel>();
public CountryTableViewSource(List<CountryDetailsViewModel> items)
{
_models = items;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
CountryTableCell cell = tableView.DequeueReusableCell(CountryTableCell.Key, indexPath) as CountryTableCell;
CountryDetailsViewModel model = _models[indexPath.Row];
cell.UpdateCell(model);
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return _models.Count();
}
public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
return CountryTableCell.ROW_HEIGHT;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
_models[indexPath.Row].Checked = !_models[indexPath.Row].Checked;
tableView.ReloadData();
}
}
} |
||||
TheStack | b5ec20670d40254114ecda4f2d8ad9332de5d328 | C#code:C# | {"size": 549, "ext": "cs", "max_stars_repo_path": "src/StackExchange.Redis/Utils.cs", "max_stars_repo_name": "tombatron/StackExchange.Redis", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StackExchange.Redis/Utils.cs", "max_issues_repo_name": "tombatron/StackExchange.Redis", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StackExchange.Redis/Utils.cs", "max_forks_repo_name": "tombatron/StackExchange.Redis", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.45, "max_line_length": 143, "alphanum_fraction": 0.6757741348} | using System;
using System.Reflection;
namespace StackExchange.Redis;
internal static class Utils
{
private static string _libVersion;
internal static string GetLibVersion()
{
if (_libVersion == null)
{
var assembly = typeof(ConnectionMultiplexer).Assembly;
_libVersion = ((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyFileVersionAttribute)))?.Version
?? assembly.GetName().Version.ToString();
}
return _libVersion;
}
}
|
||||
TheStack | b5ec84d6402d5bc46f7864943c8688db4c159848 | C#code:C# | {"size": 5194, "ext": "cs", "max_stars_repo_path": "Sqloogle/Libs/DBDiff.Schema/SqlServer2005/Generates/GenerateDatabase.cs", "max_stars_repo_name": "dalenewman/SQLoogle", "max_stars_repo_stars_event_min_datetime": "2015-07-27T18:32:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T20:13:38.000Z", "max_issues_repo_path": "Sqloogle/Libs/DBDiff.Schema/SqlServer2005/Generates/GenerateDatabase.cs", "max_issues_repo_name": "dalenewman/SQLoogle", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sqloogle/Libs/DBDiff.Schema/SqlServer2005/Generates/GenerateDatabase.cs", "max_forks_repo_name": "dalenewman/SQLoogle", "max_forks_repo_forks_event_min_datetime": "2016-01-18T22:58:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T05:25:36.000Z"} | {"max_stars_count": 19.0, "max_issues_count": null, "max_forks_count": 6.0, "avg_line_length": 39.9538461538, "max_line_length": 172, "alphanum_fraction": 0.4980747016} | #region license
// Sqloogle
// Copyright 2013-2017 Dale Newman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Data.SqlClient;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates.SQLCommands;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Options;
#if DEBUG
using System.Runtime.InteropServices;
#endif
namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates
{
public class GenerateDatabase
{
private string connectioString;
private SqlOption objectFilter;
/// <summary>
/// Constructor de la clase.
/// </summary>
/// <param name="connectioString">Connection string de la base</param>
public GenerateDatabase(string connectioString, SqlOption filter)
{
this.connectioString = connectioString;
this.objectFilter = filter;
}
public DatabaseInfo Get(Database database)
{
DatabaseInfo item = new DatabaseInfo();
using (SqlConnection conn = new SqlConnection(connectioString))
{
using (SqlCommand command = new SqlCommand(DatabaseSQLCommand.GetVersion(database), conn))
{
conn.Open();
item.Server = conn.DataSource;
item.Database = conn.Database;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string versionValue = reader["Version"] as string;
try
{
// used to use the decimal as well when Azure was 10.25
var version = new Version(versionValue);
item.VersionNumber = float.Parse(String.Format("{0}.{1}", version.Major, version.Minor), System.Globalization.CultureInfo.InvariantCulture);
int? edition = null;
if (reader.FieldCount > 1 && !reader.IsDBNull(1))
{
int validEdition;
string editionValue = reader[1].ToString();
if (!String.IsNullOrEmpty(editionValue) && int.TryParse(editionValue, out validEdition))
{
edition = validEdition;
}
}
item.SetEdition(edition);
}
catch (Exception notAGoodIdeaToCatchAllErrors)
{
bool useDefaultVersion = false;
//#if DEBUG
// useDefaultVersion = IsKeyPushedDown(System.Windows.Forms.Keys.LShiftKey)
// && IsKeyPushedDown(System.Windows.Forms.Keys.RShiftKey);
//#endif
var exception = new DBDiff.Schema.Misc.SchemaException(
String.Format("Error parsing ProductVersion. ({0})", versionValue ?? "[null]")
, notAGoodIdeaToCatchAllErrors);
if (!useDefaultVersion)
{
throw exception;
}
}
}
}
}
using (SqlCommand command = new SqlCommand(DatabaseSQLCommand.Get(item.Version, database), conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
item.Collation = reader["Collation"].ToString();
item.HasFullTextEnabled = ((int)reader["IsFulltextEnabled"]) == 1;
}
}
}
}
return item;
}
//#if DEBUG
// // http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html
// [DllImport("user32.dll")]
// static extern ushort GetAsyncKeyState(int vKey);
// public static bool IsKeyPushedDown(System.Windows.Forms.Keys vKey)
// {
// return 0 != (GetAsyncKeyState((int)vKey) & 0x8000);
// }
//#endif
}
}
|
||||
TheStack | b5ed9b07a84c96acd790ab2548cd55a80bc84a95 | C#code:C# | {"size": 624, "ext": "cs", "max_stars_repo_path": "src/Shouldly/MessageGenerators/ShouldBeInOrderMessageGenerator.cs", "max_stars_repo_name": "stop-cran/shouldly", "max_stars_repo_stars_event_min_datetime": "2015-01-05T18:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:37:39.000Z", "max_issues_repo_path": "src/Shouldly/MessageGenerators/ShouldBeInOrderMessageGenerator.cs", "max_issues_repo_name": "Mohammad-Haris/shouldly", "max_issues_repo_issues_event_min_datetime": "2015-01-07T10:44:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:29:17.000Z", "max_forks_repo_path": "src/Shouldly/MessageGenerators/ShouldBeInOrderMessageGenerator.cs", "max_forks_repo_name": "Mohammad-Haris/shouldly", "max_forks_repo_forks_event_min_datetime": "2015-01-09T05:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T21:49:08.000Z"} | {"max_stars_count": 1628.0, "max_issues_count": 505.0, "max_forks_count": 483.0, "avg_line_length": 32.8421052632, "max_line_length": 86, "alphanum_fraction": 0.6987179487} | namespace Shouldly.MessageGenerators
{
internal class ShouldBeInOrderMessageGenerator : ShouldlyMessageGenerator
{
public override bool CanProcess(IShouldlyAssertionContext context)
{
return context.ShouldMethod == "ShouldBeInOrder";
}
public override string GenerateErrorMessage(IShouldlyAssertionContext context)
{
return
$@"{context.CodePart}
should be in {context.SortDirection.ToString().ToLower()} order but was not.
The first out-of-order item was found at index {context.OutOfOrderIndex}:
{context.OutOfOrderObject}";
}
}
} |
||||
TheStack | b5edc03e68cbe41d1d8515e434f73ba47aaa15b0 | C#code:C# | {"size": 7006, "ext": "cs", "max_stars_repo_path": "src/SterlingSln/Wintellect.Sterling.IsolatedStorageUpgrade/Upgrade.cs", "max_stars_repo_name": "JeremyLikness/SterlingNoSQL", "max_stars_repo_stars_event_min_datetime": "2017-08-24T09:48:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T01:10:20.000Z", "max_issues_repo_path": "src/SterlingSln/Wintellect.Sterling.IsolatedStorageUpgrade/Upgrade.cs", "max_issues_repo_name": "JeremyLikness/SterlingNoSQL", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SterlingSln/Wintellect.Sterling.IsolatedStorageUpgrade/Upgrade.cs", "max_forks_repo_name": "JeremyLikness/SterlingNoSQL", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 16.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.0471698113, "max_line_length": 112, "alphanum_fraction": 0.459606052} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using Path = System.IO.Path;
namespace Wintellect.Sterling.IsolatedStorageUpgrade
{
public static class Upgrade
{
private static BackgroundWorker _upgradeWorker;
private const string STERLING_ROOT = @"Sterling\";
private const string DATABASES = "db.dat";
private const string TYPES = "types.dat";
private static IsolatedStorageFile _iso;
public static bool CancelUpgrade()
{
if (_upgradeWorker != null)
{
_upgradeWorker.CancelAsync();
return true;
}
return false;
}
public static void DoUpgrade(Action upgradeCompleted)
{
if (_upgradeWorker != null)
{
throw new Exception("Upgrade already in progress.");
}
_iso = IsolatedStorageFile.GetUserStoreForApplication();
var path = string.Format("{0}{1}", STERLING_ROOT, DATABASES);
if (!_iso.FileExists(path))
{
upgradeCompleted();
return;
}
_upgradeWorker = new BackgroundWorker {WorkerSupportsCancellation = true};
_upgradeWorker.DoWork += _UpgradeWorkerDoWork;
_upgradeWorker.RunWorkerCompleted += (o, e) =>
{
_upgradeWorker = null;
upgradeCompleted();
};
_upgradeWorker.RunWorkerAsync();
}
private static void _UpgradeWorkerDoWork(object sender, DoWorkEventArgs e)
{
_iso = IsolatedStorageFile.GetUserStoreForApplication();
e.Cancel = !_IterateDatabases();
_iso.Dispose();
_iso = null;
}
private static bool _IterateDatabases()
{
var path = string.Format("{0}{1}", STERLING_ROOT, DATABASES);
if (!_iso.FileExists(path))
{
return true;
}
using (var br = new BinaryReader(_iso.OpenFile(path, FileMode.Open, FileAccess.Read)))
{
br.ReadInt32(); // next database
br.ReadInt32(); // next table
var count = br.ReadInt32();
for (var i = 0; i < count; i++)
{
if (_upgradeWorker.CancellationPending)
{
return false;
}
var dbName = br.ReadString();
var dbIndex = br.ReadInt32();
if (!_ProcessDatabase(dbIndex, dbName))
{
return false;
}
}
}
_purgeQueue.Enqueue(PurgeEntry.CreateEntry(false, path));
_purgeQueue.Enqueue(PurgeEntry.CreateEntry(false, string.Format("@{0}{1}", STERLING_ROOT, TYPES)));
if (!_Purge())
{
return false;
}
return true;
}
private static bool _ProcessDatabase(int dbIndex, string dbName)
{
var dbPath = string.Format("{0}{1}", STERLING_ROOT, dbIndex);
var newDbPath = string.Format("{0}{1}", STERLING_ROOT, dbName.GetHashCode());
if (!_iso.DirectoryExists(dbPath))
{
return true;
}
if (!_iso.DirectoryExists(newDbPath))
{
_iso.CreateDirectory(newDbPath);
}
var typeSource = string.Format("{0}{1}", STERLING_ROOT, TYPES);
var typeTarget = string.Format(@"{0}\{1}", newDbPath, TYPES);
_iso.CopyFile(typeSource, typeTarget, true);
_purgeQueue.Clear();
if (!_Copy(dbPath, newDbPath, dbPath))
{
return false;
}
return _Purge();
}
private static readonly Queue<PurgeEntry> _purgeQueue = new Queue<PurgeEntry>();
private static bool _Copy(string root, string targetRoot, string path)
{
// already copied
if (!_iso.DirectoryExists(path))
{
return true;
}
var targetDirectory = path.Replace(root, targetRoot);
if (!_iso.DirectoryExists(targetDirectory))
{
_iso.CreateDirectory(targetDirectory);
}
// clear the sub directories)
foreach (var dir in _iso.GetDirectoryNames(Path.Combine(path, "*")))
{
if (_upgradeWorker.CancellationPending)
{
return false;
}
if (!_Copy(root, targetRoot, Path.Combine(path, dir)))
{
return false;
}
}
// clear the files - don't use a where clause because we want to get closer to the delete operation
// with the filter
foreach (var filePath in
_iso.GetFileNames(Path.Combine(path, "*"))
.Select(file => Path.Combine(path, file)))
{
if (_upgradeWorker.CancellationPending)
{
return false;
}
// ignore indexes
var target = filePath.Replace(root, targetRoot);
if (_iso.FileExists(filePath))
{
_iso.CopyFile(filePath, target, true);
}
_purgeQueue.Enqueue(PurgeEntry.CreateEntry(false, filePath));
}
var dirPath = path.TrimEnd('\\', '/');
_purgeQueue.Enqueue(PurgeEntry.CreateEntry(true, dirPath));
return true;
}
private static bool _Purge()
{
while(_purgeQueue.Count > 0)
{
if (_upgradeWorker.CancellationPending)
{
return false;
}
var entry = _purgeQueue.Dequeue();
if (entry.IsDirectory && _iso.DirectoryExists(entry.Path))
{
_iso.DeleteDirectory(entry.Path);
}
else if (_iso.FileExists(entry.Path))
{
_iso.DeleteFile(entry.Path);
}
}
return true;
}
}
} |
||||
TheStack | b5ee5bb7adeb389ceacebfa8292eb78d4f549bd1 | C#code:C# | {"size": 4337, "ext": "cs", "max_stars_repo_path": "Heyday-Website/Migrations/AppDb/20201013051117_Appinit.cs", "max_stars_repo_name": "hlz2516/Heyday-Website", "max_stars_repo_stars_event_min_datetime": "2020-10-01T16:41:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T16:41:33.000Z", "max_issues_repo_path": "Heyday-Website/Migrations/AppDb/20201013051117_Appinit.cs", "max_issues_repo_name": "hlz2516/Heyday-Website", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Heyday-Website/Migrations/AppDb/20201013051117_Appinit.cs", "max_forks_repo_name": "hlz2516/Heyday-Website", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.3879310345, "max_line_length": 74, "alphanum_fraction": 0.4655291676} | using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Heyday_Website.Migrations.AppDb
{
public partial class Appinit : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Bugs",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
SubmitterEmail = table.Column<string>(nullable: true),
Title = table.Column<string>(nullable: true),
Content = table.Column<string>(nullable: true),
BugState = table.Column<int>(nullable: false),
SubmitTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Bugs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CategoryName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Solutions",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
BugId = table.Column<Guid>(nullable: false),
Context = table.Column<string>(nullable: true),
Solver = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Solutions", x => x.Id);
table.ForeignKey(
name: "FK_Solutions_Bugs_BugId",
column: x => x.BugId,
principalTable: "Bugs",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Articles",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Title = table.Column<string>(nullable: true),
Content = table.Column<string>(nullable: true),
Author = table.Column<string>(nullable: true),
HasPublished = table.Column<bool>(nullable: false),
URL = table.Column<string>(nullable: true),
PublishTime = table.Column<DateTime>(nullable: false),
CategoryId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Articles", x => x.Id);
table.ForeignKey(
name: "FK_Articles_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Articles_CategoryId",
table: "Articles",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Articles_Title",
table: "Articles",
column: "Title",
unique: true,
filter: "[Title] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Solutions_BugId",
table: "Solutions",
column: "BugId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Articles");
migrationBuilder.DropTable(
name: "Solutions");
migrationBuilder.DropTable(
name: "Categories");
migrationBuilder.DropTable(
name: "Bugs");
}
}
}
|
||||
TheStack | b5f0138099d8092b497bb006584389a960d14a49 | C#code:C# | {"size": 1322, "ext": "cs", "max_stars_repo_path": "samples/SampleWebApi/Controllers/Issue92.cs", "max_stars_repo_name": "rayzhb/MicroElements.Swashbuckle.FluentValidation", "max_stars_repo_stars_event_min_datetime": "2018-03-26T02:26:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:11:28.000Z", "max_issues_repo_path": "samples/SampleWebApi/Controllers/Issue92.cs", "max_issues_repo_name": "rayzhb/MicroElements.Swashbuckle.FluentValidation", "max_issues_repo_issues_event_min_datetime": "2018-03-29T13:23:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T18:57:19.000Z", "max_forks_repo_path": "samples/SampleWebApi/Controllers/Issue92.cs", "max_forks_repo_name": "rayzhb/MicroElements.Swashbuckle.FluentValidation", "max_forks_repo_forks_event_min_datetime": "2018-03-29T16:51:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-20T02:02:54.000Z"} | {"max_stars_count": 246.0, "max_issues_count": 88.0, "max_forks_count": 50.0, "avg_line_length": 25.9215686275, "max_line_length": 94, "alphanum_fraction": 0.5786686838} | using FluentValidation;
using Microsoft.AspNetCore.Mvc;
namespace SampleWebApi.Controllers
{
/// <summary>
/// https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation/issues/92
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class Issue92 : Controller
{
[HttpPost("[action]")]
public ActionResult<Bookshelf> CreateBookshelf(CreateBookshelfCommand command)
{
return new ObjectResult(new Bookshelf { Books = command.Books })
{
StatusCode = 201
};
}
}
/// <summary>
/// Bookshelf domain model.
/// </summary>
public class Bookshelf
{
public string[] Books { get; set; }
}
// Command object to send in a POST call.
public class CreateBookshelfCommand
{
public string[] Books { get; set; }
}
// Validator to validate that command.
public class CreateBookshelfCommandValidator : AbstractValidator<CreateBookshelfCommand>
{
public CreateBookshelfCommandValidator()
{
RuleFor(c => c.Books)
.NotEmpty();
RuleForEach(c => c.Books)
.NotEmpty()
.MinimumLength(5)
.MaximumLength(250);
}
}
} |
||||
TheStack | b5f1d91b1fedc97a13994d079e343d33b7cea00d | C#code:C# | {"size": 6004, "ext": "cs", "max_stars_repo_path": "Source/RuntimeBusinessLogic/VirtualViews/VirtualView.cs", "max_stars_repo_name": "sakrut/ZetaResourceEditor", "max_stars_repo_stars_event_min_datetime": "2015-01-02T05:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:51:45.000Z", "max_issues_repo_path": "Source/RuntimeBusinessLogic/VirtualViews/VirtualView.cs", "max_issues_repo_name": "sakrut/ZetaResourceEditor", "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:06:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-21T16:16:44.000Z", "max_forks_repo_path": "Source/RuntimeBusinessLogic/VirtualViews/VirtualView.cs", "max_forks_repo_name": "sakrut/ZetaResourceEditor", "max_forks_repo_forks_event_min_datetime": "2015-02-25T19:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T10:53:38.000Z"} | {"max_stars_count": 217.0, "max_issues_count": 31.0, "max_forks_count": 61.0, "avg_line_length": 30.1708542714, "max_line_length": 115, "alphanum_fraction": 0.5209860093} | namespace ZetaResourceEditor.RuntimeBusinessLogic.VirtualViews
{
using DL;
using FileGroups;
using ProjectFolders;
using Projects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Zeta.VoyagerLibrary.Common;
using Zeta.VoyagerLibrary.Common.Collections;
using ZetaAsync;
public class VirtualView :
ITranslationStateInformation,
IComparable,
IComparable<VirtualView>,
IUniqueID,
IOrderPosition
{
public VirtualView(Project project)
{
Project = project;
}
private string _name;
private Guid _projectFolderUniqueID;
private int _orderPosition;
private Guid _uniqueID;
public Guid UniqueID => _uniqueID;
public Project Project { get; }
public ProjectFolder ProjectFolder
{
get => Project.GetProjectFolderByUniqueID(_projectFolderUniqueID);
set => _projectFolderUniqueID = value?.UniqueID ?? Guid.Empty;
}
internal void StoreToXml(
Project project,
XmlElement parentNode)
{
if (parentNode.OwnerDocument != null)
{
var a = parentNode.OwnerDocument.CreateAttribute(@"name");
a.Value = Name;
parentNode.Attributes.Append(a);
a = parentNode.OwnerDocument.CreateAttribute(@"projectFolderUniqueID");
a.Value = _projectFolderUniqueID.ToString();
parentNode.Attributes.Append(a);
a = parentNode.OwnerDocument.CreateAttribute(@"orderPosition");
a.Value = OrderPosition.ToString();
parentNode.Attributes.Append(a);
a = parentNode.OwnerDocument.CreateAttribute(@"viewMode");
a.Value = Mode.ToString();
parentNode.Attributes.Append(a);
var remarksNode =
parentNode.OwnerDocument.CreateElement(@"remarks");
parentNode.AppendChild(remarksNode);
remarksNode.InnerText = Remarks;
if (parentNode.OwnerDocument != null)
{
a = parentNode.OwnerDocument.CreateAttribute(@"uniqueID");
a.Value = _uniqueID.ToString();
parentNode.Attributes.Append(a);
}
}
}
internal void LoadFromXml(
Project project,
XmlNode parentNode)
{
if (parentNode.Attributes != null)
{
XmlHelper.ReadAttribute(
out _uniqueID,
parentNode.Attributes[@"uniqueID"]);
}
if (_uniqueID == Guid.Empty)
{
_uniqueID = Guid.NewGuid();
}
// --
if (parentNode.Attributes != null)
{
XmlHelper.ReadAttribute(
out _projectFolderUniqueID,
parentNode.Attributes[@"projectFolderUniqueID"]);
}
string viewMode = null;
if (parentNode.Attributes != null)
{
XmlHelper.ReadAttribute(
out viewMode,
parentNode.Attributes[@"viewMode"]);
}
if (string.IsNullOrEmpty(viewMode))
{
Mode = ViewMode.Unknown;
}
else
{
Mode = (ViewMode)Enum.Parse(typeof(ViewMode), viewMode, true);
}
if (parentNode.Attributes != null)
{
XmlHelper.ReadAttribute(
out _name,
parentNode.Attributes[@"name"]);
XmlHelper.ReadAttribute(
out _orderPosition,
parentNode.Attributes[@"orderPosition"]);
}
var remarksNode = parentNode.SelectSingleNode(@"remarks");
Remarks = remarksNode?.InnerText;
}
public Guid ProjectFolderUniqueID => _projectFolderUniqueID;
public void StoreOrderPosition(
object threadPoolManager,
object postExecuteCallback,
AsynchronousMode asynchronousMode,
object userState)
{
Project.MarkAsModified();
}
public int OrderPosition
{
get => _orderPosition;
set => _orderPosition = value;
}
public string Remarks { get; set; }
public ViewMode Mode { get; set; }
public string Name
{
get => _name;
set => _name = value;
}
public MyTuple<string, string>[] GetLanguageCodesExtended(Project project)
{
var result = new HashSet<MyTuple<string, string>>();
var fileGroups =
ProjectFolder == null
? Project.GetRootFileGroups()
: ProjectFolder.ChildFileGroups;
foreach (var fg in fileGroups)
{
foreach (var f in fg.GetLanguageCodesExtended(project))
{
var g = f;
if (result.All(x => string.Compare(x.Item1, g.Item1, StringComparison.OrdinalIgnoreCase) != 0))
{
result.Add(f);
}
}
}
return result.ToArray();
}
public int CompareTo(VirtualView other)
{
var a = _orderPosition.CompareTo(other._orderPosition);
return a == 0 ? string.Compare(Name, other.Name, StringComparison.Ordinal) : a;
}
public int CompareTo(object obj)
{
return CompareTo((VirtualView)obj);
}
public FileGroupStateColor TranslationStateColor => throw new NotImplementedException();
}
} |
||||
TheStack | b5f452826183fadb2ce74a7359b20afffbe81918 | C#code:C# | {"size": 1485, "ext": "cs", "max_stars_repo_path": "backend/src/Application/Auth/Commands/GenerateAccessTokenCommand.cs", "max_stars_repo_name": "BinaryStudioAcademy/bsa-2021-scout", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backend/src/Application/Auth/Commands/GenerateAccessTokenCommand.cs", "max_issues_repo_name": "BinaryStudioAcademy/bsa-2021-scout", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backend/src/Application/Auth/Commands/GenerateAccessTokenCommand.cs", "max_forks_repo_name": "BinaryStudioAcademy/bsa-2021-scout", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.306122449, "max_line_length": 120, "alphanum_fraction": 0.6882154882} | using Application.Auth.Dtos;
using Application.Interfaces;
using Application.Users.Dtos;
using Domain.Entities;
using Domain.Interfaces.Abstractions;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace Application.Auth.Commands
{
public class GenerateAccessTokenCommand : IRequest<AccessTokenDto>
{
public UserDto User { get; }
public GenerateAccessTokenCommand(UserDto user)
{
User = user;
}
}
public class GenerateAccessTokenCommandHandler : IRequestHandler<GenerateAccessTokenCommand, AccessTokenDto>
{
protected readonly IWriteRepository<RefreshToken> _tokenRepository;
protected readonly IJwtService _jwtService;
public GenerateAccessTokenCommandHandler(IWriteRepository<RefreshToken> tokenRepository, IJwtService jwtService)
{
_tokenRepository = tokenRepository;
_jwtService = jwtService;
}
public async Task<AccessTokenDto> Handle(GenerateAccessTokenCommand command, CancellationToken _)
{
var refreshToken = _jwtService.GenerateRefreshToken();
await _tokenRepository.CreateAsync(new RefreshToken
{
Token = refreshToken,
UserId = command.User.Id
});
var accessToken = await _jwtService.GenerateJsonWebToken(command.User);
return new AccessTokenDto(accessToken, refreshToken);
}
}
}
|
||||
TheStack | b5f499f59e1f24c88764307f86387120d37af1c0 | C#code:C# | {"size": 1746, "ext": "cs", "max_stars_repo_path": "src/Hyperledger.Aries.TestHarness/Utils/ProofServiceUtils.cs", "max_stars_repo_name": "lissi-id/aries-framework-dotnet", "max_stars_repo_stars_event_min_datetime": "2019-08-22T15:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:48:12.000Z", "max_issues_repo_path": "src/Hyperledger.Aries.TestHarness/Utils/ProofServiceUtils.cs", "max_issues_repo_name": "lissi-id/aries-framework-dotnet", "max_issues_repo_issues_event_min_datetime": "2019-08-22T13:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T14:33:05.000Z", "max_forks_repo_path": "src/Hyperledger.Aries.TestHarness/Utils/ProofServiceUtils.cs", "max_forks_repo_name": "lissi-id/aries-framework-dotnet", "max_forks_repo_forks_event_min_datetime": "2019-08-19T18:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T13:12:46.000Z"} | {"max_stars_count": 67.0, "max_issues_count": 93.0, "max_forks_count": 88.0, "avg_line_length": 37.9565217391, "max_line_length": 130, "alphanum_fraction": 0.6013745704} | using System.Linq;
using System.Threading.Tasks;
using Hyperledger.Aries.Agents;
using Hyperledger.Aries.Features.PresentProof;
namespace Hyperledger.TestHarness.Utils
{
public static class ProofServiceUtils
{
public static async Task<RequestedCredentials> GetAutoRequestedCredentialsForProofCredentials(IAgentContext holderContext,
IProofService proofService, ProofRequest proofRequest)
{
var requestedCredentials = new RequestedCredentials();
foreach (var requestedAttribute in proofRequest.RequestedAttributes)
{
var credentials =
await proofService.ListCredentialsForProofRequestAsync(holderContext, proofRequest,
requestedAttribute.Key);
requestedCredentials.RequestedAttributes.Add(requestedAttribute.Key,
new RequestedAttribute
{
CredentialId = credentials.First().CredentialInfo.Referent,
Revealed = true
});
}
foreach (var requestedAttribute in proofRequest.RequestedPredicates)
{
var credentials =
await proofService.ListCredentialsForProofRequestAsync(holderContext, proofRequest,
requestedAttribute.Key);
requestedCredentials.RequestedPredicates.Add(requestedAttribute.Key,
new RequestedAttribute
{
CredentialId = credentials.First().CredentialInfo.Referent,
Revealed = true
});
}
return requestedCredentials;
}
}
}
|
||||
TheStack | b5f5518ce0680b71a41c543135d4cf328ac54772 | C#code:C# | {"size": 1364, "ext": "cs", "max_stars_repo_path": "UiPath.Web.Client/generated201910/Models/IEdmTypeReference.cs", "max_stars_repo_name": "AFWberlin/orchestrator-powershell", "max_stars_repo_stars_event_min_datetime": "2018-06-05T16:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:09:18.000Z", "max_issues_repo_path": "UiPath.Web.Client/generated201910/Models/IEdmTypeReference.cs", "max_issues_repo_name": "AFWberlin/orchestrator-powershell", "max_issues_repo_issues_event_min_datetime": "2018-05-23T03:11:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:14:27.000Z", "max_forks_repo_path": "UiPath.Web.Client/generated201910/Models/IEdmTypeReference.cs", "max_forks_repo_name": "AFWberlin/orchestrator-powershell", "max_forks_repo_forks_event_min_datetime": "2018-05-23T18:10:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T08:38:12.000Z"} | {"max_stars_count": 81.0, "max_issues_count": 94.0, "max_forks_count": 55.0, "avg_line_length": 27.8367346939, "max_line_length": 108, "alphanum_fraction": 0.5909090909} | // <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client201910.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class IEdmTypeReference
{
/// <summary>
/// Initializes a new instance of the IEdmTypeReference class.
/// </summary>
public IEdmTypeReference()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the IEdmTypeReference class.
/// </summary>
public IEdmTypeReference(bool? isNullable = default(bool?), IEdmType definition = default(IEdmType))
{
IsNullable = isNullable;
Definition = definition;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "IsNullable")]
public bool? IsNullable { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Definition")]
public IEdmType Definition { get; private set; }
}
}
|
||||
TheStack | b5f58d2d9c1c93ca7dbdf1fbf823941404d3a0b0 | C#code:C# | {"size": 5073, "ext": "cs", "max_stars_repo_path": "Daramkun.Misty.Core/Mathematics/Quaternion.Calculate.cs", "max_stars_repo_name": "Daramkun/Misty", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Daramkun.Misty.Core/Mathematics/Quaternion.Calculate.cs", "max_issues_repo_name": "Daramkun/Misty", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Daramkun.Misty.Core/Mathematics/Quaternion.Calculate.cs", "max_forks_repo_name": "Daramkun/Misty", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 64.2151898734, "max_line_length": 145, "alphanum_fraction": 0.6134437217} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Daramkun.Misty.Mathematics
{
public partial struct Quaternion
{
public static Quaternion operator + ( Quaternion a, Quaternion b ) { Quaternion result; Add ( ref a, ref b, out result ); return result; }
public static Quaternion operator - ( Quaternion a ) { Quaternion result; Negate ( ref a, out result ); return result; }
public static Quaternion operator - ( Quaternion a, Quaternion b ) { Quaternion result; Subtract ( ref a, ref b, out result ); return result; }
public static Quaternion operator * ( Quaternion a, Quaternion b ) { Quaternion result; Multiply ( ref a, ref b, out result ); return result; }
public static Quaternion operator * ( Quaternion a, float b ) { Quaternion result; Multiply ( ref a, b, out result ); return result; }
public static Quaternion operator * ( float a, Quaternion b ) { Quaternion result; Multiply ( ref b, a, out result ); return result; }
public static Quaternion operator / ( Quaternion a, Quaternion b ) { Quaternion result; Divide ( ref a, ref b, out result ); return result; }
public static Quaternion operator / ( Quaternion a, float b ) { Quaternion result; Divide ( ref a, b, out result ); return result; }
public static Quaternion operator ~ ( Quaternion a ) { Quaternion result; Invert ( ref a, out result ); return result; }
public static bool operator == ( Quaternion a, Quaternion b ) { return a.Equals ( b ); }
public static bool operator != ( Quaternion a, Quaternion b ) { return !( a == b ); }
public override bool Equals ( object obj )
{
if ( !( obj is Quaternion ) ) return false;
Quaternion q = ( Quaternion ) obj;
return X == q.X && Y == q.Y && Z == q.Z && W == q.W;
}
public static Quaternion Add ( Quaternion a, Quaternion b ) { return a + b; }
public static Quaternion Subtract ( Quaternion a, Quaternion b ) { return a - b; }
public static Quaternion Multiply ( Quaternion a, Quaternion b ) { return a * b; }
public static Quaternion Multiply ( Quaternion a, float b ) { return a * b; }
public static Quaternion Multiply ( float a, Quaternion b ) { return b * a; }
public static Quaternion Dividie ( Quaternion a, Quaternion b ) { return a / b; }
public static Quaternion Divide ( Quaternion a, float b ) { return a / b; }
public static Quaternion Invert ( Quaternion a ) { return ~a; }
public static void Add ( ref Quaternion a, ref Quaternion b, out Quaternion result )
{ result = new Quaternion ( a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W ); }
public static void Negate ( ref Quaternion a, out Quaternion result )
{ result = new Quaternion ( -a.X, -a.Y, -a.Z, -a.W ); }
public static void Subtract ( ref Quaternion a, ref Quaternion b, out Quaternion result )
{ result = new Quaternion ( a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W ); }
public static void Multiply ( ref Quaternion a, ref Quaternion b, out Quaternion result )
{
float x = a.X, y = a.Y, z = a.Z, w = a.W;
float num4 = b.X, num3 = b.Y, num2 = b.Z, num1 = b.W;
float num12 = ( y * num2 ) - ( z * num3 ), num11 = ( z * num4 ) - ( x * num2 ),
num10 = ( x * num3 ) - ( y * num4 ), num9 = ( ( x * num4 ) + ( y * num3 ) ) + ( z * num2 );
result = new Quaternion ( ( ( x * num1 ) + ( num4 * w ) ) + num12, ( ( y * num1 ) + ( num3 * w ) ) + num11,
( ( z * num1 ) + ( num2 * w ) ) + num10, ( w * num1 ) - num9 );
}
public static void Multiply ( ref Quaternion a, float b, out Quaternion result )
{ result = new Quaternion ( a.X * b, a.Y * b, a.Z * b, a.W * b ); }
public static void Multiply ( float a, ref Quaternion b, out Quaternion result ) { Multiply ( ref b, a, out result ); }
public static void Divide ( ref Quaternion a, ref Quaternion b, out Quaternion result )
{
float x = a.X, y = a.Y, z = a.Z, w = a.W;
float num14 = ( ( ( b.X * b.X ) + ( b.Y * b.Y ) ) + ( b.Z * b.Z ) ) + ( b.W * b.W );
float num5 = 1f / num14, num4 = -b.X * num5, num3 = -b.Y * num5, num2 = -b.Z * num5, num1 = b.W * num5;
float num13 = ( y * num2 ) - ( z * num3 ), num12 = ( z * num4 ) - ( x * num2 );
float num11 = ( x * num3 ) - ( y * num4 ), num10 = ( ( x * num4 ) + ( y * num3 ) ) + ( z * num2 );
result = new Quaternion ( ( ( x * num1 ) + ( num4 * w ) ) + num13, ( ( y * num1 ) + ( num3 * w ) ) + num12,
( ( z * num1 ) + ( num2 * w ) ) + num11, ( w * num1 ) - num10 );
}
public static void Divide ( ref Quaternion a, float b, out Quaternion result )
{ result = new Quaternion ( a.X / b, a.Y / b, a.Z / b, a.W / b ); }
public static void Invert ( ref Quaternion a, out Quaternion result )
{ result = new Quaternion ( -a.X / a.LengthSquared, -a.Y / a.LengthSquared, -a.Z / a.LengthSquared, a.W / a.LengthSquared ); }
public static float Dot ( Quaternion a, Quaternion b ) { float result; Dot ( ref a, ref b, out result ); return result; }
public static void Dot ( ref Quaternion a, ref Quaternion b, out float result )
{
result = ( ( ( ( a.X * b.X ) + ( a.Y * b.Y ) ) + ( a.Z * b.Z ) ) + ( a.W * b.W ) );
}
}
}
|
||||
TheStack | b5f63d0051b0d625ead9aded932a5a72acc618a7 | C#code:C# | {"size": 5696, "ext": "cs", "max_stars_repo_path": "Assets/AdVdGlyphRecognition/Scripts/Stroke.cs", "max_stars_repo_name": "EppuSyyrakki/Owls", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/AdVdGlyphRecognition/Scripts/Stroke.cs", "max_issues_repo_name": "EppuSyyrakki/Owls", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/AdVdGlyphRecognition/Scripts/Stroke.cs", "max_forks_repo_name": "EppuSyyrakki/Owls", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.4598930481, "max_line_length": 117, "alphanum_fraction": 0.5521418539} | using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace AdVd.GlyphRecognition
{
[Serializable]
public class Stroke : IEnumerable
{
[SerializeField]
Vector2[] points = new Vector2[0];
public int Length
{
get { return points.Length; }
}
public Vector2 this[int index] {
get {
return points[index];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return points.GetEnumerator();
}
public Stroke(Vector2[] points)
{
this.points = (points != null ? this.points = (Vector2[]) points.Clone() : this.points = new Vector2[0]);
}
public Stroke(int pointCount = 0) {
this.points = new Vector2[pointCount];
}
/// <summary>
/// Draws the stroke using gizmos.
/// </summary>
/// <param name="position">Position.</param>
/// <param name="scale">Scale.</param>
public void DrawStroke(Vector2 position, Vector2 scale)
{
if (points.Length>1){
Vector2 prevPoint, currPoint=Vector2.Scale(points[0],scale)+position;
for (int i = 1; i < points.Length; i++){
prevPoint=currPoint; currPoint=Vector2.Scale(points[i],scale)+position;
Gizmos.DrawLine(prevPoint, currPoint);
}
}
}
/// <summary>
/// Inverse of this stroke.
/// </summary>
internal Stroke Inverse()
{
Vector2[] iPoints = new Vector2[this.Length];
for (int i = 0; i < this.Length; i++) iPoints[i] = points[this.Length - 1 - i];
return new Stroke(iPoints);
}
/// <summary>
/// Gets the bounds of the stroke.
/// </summary>
/// <value>The bounds.</value>
public Rect Bounds{
get{
if (points.Length==0) return new Rect(0,0,0,0);
float minX=points[0].x, minY=points[0].y, maxX=points[0].x, maxY=points[0].y;
for (int i = 1; i < points.Length; i++)
{
if (points[i].x < minX) minX = points[i].x;
else if (points[i].x > maxX) maxX = points[i].x;
if (points[i].y < minY) minY = points[i].y;
else if (points[i].y > maxY) maxY = points[i].y;
}
return new Rect(minX, minY, maxX-minX, maxY-minY);
}
}
/// <summary>
/// Translate this stroke to the specified position.
/// </summary>
/// <param name="position">Position.</param>
public void Translate(Vector2 position)
{
for (int i = 0; i < Length; i++)
{
points[i] += position;
}
}
/// <summary>
/// Scale this stroke by specified value.
/// </summary>
/// <param name="scale">Scale.</param>
public void Scale(Vector2 scale)
{
for (int i = 0; i < Length; i++)
{
points[i].Scale(scale);
}
}
/// <summary>
/// Sets this stroke to a lerp state of a stroke match.
/// </summary>
/// <param name="strokeMatch">Stroke Match.</param>
/// <param name="t">T.</param>
public void SetToMatchLerp(GlyphMatch.StrokeMatch strokeMatch, float t) {
if (points.Length != strokeMatch.Length) {
points = new Vector2[strokeMatch.Length];//Resize points array
}
for (int index = 0; index < Length; index++) points[index] = strokeMatch[index, t];
}
public const float minSampleDistance = 1e-3f;
/// <summary>
/// Resample this stroke by the specified sampleDistance. A sample distance sorter than 1e-3 does nothing.
/// </summary>
/// <param name="sampleDistance">Sample distance.</param>
public void Resample(float sampleDistance)
{
if (sampleDistance<minSampleDistance) return;
float totalLength=0;
float[] lengths=new float[points.Length-1];
for (int i = 0; i < lengths.Length; i++)
{
totalLength += (lengths[i] = Vector2.Distance(points[i], points[i + 1]));
}
int numberOfSamples = (int)Math.Floor(totalLength / sampleDistance);
sampleDistance = totalLength / numberOfSamples;
Vector2[] aux = new Vector2[numberOfSamples+1];
int auxIndex = 0;
float progress = 0f;
for (int i = 0; i < lengths.Length; i++)
{
float segLength = lengths[i];
while (progress < segLength && auxIndex < numberOfSamples)
{
aux[auxIndex] = Vector2.Lerp(points[i], points[i + 1], progress / segLength);
auxIndex++;
progress += sampleDistance;
}
progress -= segLength;
}
aux[numberOfSamples] = points[Length - 1];
points = aux;
}
public static bool operator ==(Stroke a, Stroke b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b)) return true;
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null)) return false;
// Return true if the fields match:
if (a.Length != b.Length) return false;
for (int index = 0; index < a.Length; index++) if (a[index] != b[index]) return false;
return true;
}
public static bool operator !=(Stroke a, Stroke b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
Stroke s = obj as Stroke;
return this == s;
}
public override int GetHashCode()
{
return points.Length;
}
}
}
|
||||
TheStack | b5f6b8bc5fa02c63aff9155b3c78e8a8818c1bd6 | C#code:C# | {"size": 145, "ext": "cs", "max_stars_repo_path": "tests/Seneca.Interception.Core.Tests/Interceptors/Stubs/IStubWithGenericTask.cs", "max_stars_repo_name": "eminencegrs/seneca-interception", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Seneca.Interception.Core.Tests/Interceptors/Stubs/IStubWithGenericTask.cs", "max_issues_repo_name": "eminencegrs/seneca-interception", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Seneca.Interception.Core.Tests/Interceptors/Stubs/IStubWithGenericTask.cs", "max_forks_repo_name": "eminencegrs/seneca-interception", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.1666666667, "max_line_length": 61, "alphanum_fraction": 0.8068965517} | namespace Seneca.Interception.Core.Tests.Interceptors.Stubs;
public interface IStubWithGenericTask
{
Task<ModelStub> GetModel(string id);
} |
||||
TheStack | b5f7280f53315ff2c28ecc5fd9df61034b8555b8 | C#code:C# | {"size": 5824, "ext": "cs", "max_stars_repo_path": "src/Monik.Service/Bootstrapper.cs", "max_stars_repo_name": "Totopolis/monik", "max_stars_repo_stars_event_min_datetime": "2019-03-10T08:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-10T08:43:07.000Z", "max_issues_repo_path": "src/Monik.Service/Bootstrapper.cs", "max_issues_repo_name": "Totopolis/monik", "max_issues_repo_issues_event_min_datetime": "2020-04-25T16:02:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-25T16:02:59.000Z", "max_forks_repo_path": "src/Monik.Service/Bootstrapper.cs", "max_forks_repo_name": "Totopolis/monik", "max_forks_repo_forks_event_min_datetime": "2019-01-30T09:31:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-20T16:31:23.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": 4.0, "avg_line_length": 38.8266666667, "max_line_length": 120, "alphanum_fraction": 0.6208791209} | using System;
using System.Reflection;
using Autofac;
using Microsoft.Extensions.Logging;
using Monik.Common;
using Nancy;
using Nancy.Authentication.Stateless;
using Nancy.Bootstrapper;
using Nancy.Bootstrappers.Autofac;
using Nancy.Gzip;
namespace Monik.Service
{
public partial class Bootstrapper : AutofacNancyBootstrapper
{
public static Bootstrapper Singleton;
private readonly IMonikServiceSettings _settings;
private readonly ILoggerFactory _loggerFactory;
public Bootstrapper(IMonikServiceSettings settings, ILoggerFactory loggerFactory)
{
_settings = settings;
_loggerFactory = loggerFactory;
}
public T Resolve<T>() => ApplicationContainer.Resolve<T>();
protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
{
if (Singleton != null)
throw new BootstrapperException("Duplicate");
Singleton = this;
// No registrations should be performed in here, however you may
// resolve things that are needed during application startup.
// Enable Compression with Default Settings
pipelines.EnableGzipCompression();
var userIdentityProvider = container.Resolve<IUserIdentityProvider>();
var configuration = new StatelessAuthenticationConfiguration(userIdentityProvider.GetUserIdentity);
StatelessAuthentication.Enable(pipelines, configuration);
OnApplicationStart();
}
public void OnApplicationStart()
{
var logger = Resolve<IMonik>();
logger.ApplicationWarning($"Starting {Assembly.GetExecutingAssembly().GetName().Version}");
logger.ApplicationInfo("Load sources");
Resolve<ICacheSourceInstance>().OnStart();
logger.ApplicationInfo("Load logs");
Resolve<ICacheLog>().OnStart();
logger.ApplicationInfo("Load ka");
Resolve<ICacheKeepAlive>().OnStart();
logger.ApplicationInfo("Load metrics");
Resolve<ICacheMetric>().OnStart();
logger.ApplicationInfo("Starting messages");
Resolve<IMessageProcessor>().OnStart();
Resolve<IMessagePump>().OnStart();
logger.ApplicationWarning("Started");
}
// Raise at NancyHostHolder.Stop() when service shutdown
public void OnApplicationStop()
{
Resolve<IMonik>().ApplicationWarning(
$"Stopping {Assembly.GetExecutingAssembly().GetName().Version}");
Resolve<IMonik>().OnStop();
Resolve<IMessagePump>().OnStop();
Resolve<IMessageProcessor>().OnStop();
Resolve<ICacheMetric>().OnStop();
Resolve<ICacheKeepAlive>().OnStop();
Resolve<ICacheLog>().OnStop();
Resolve<ICacheSourceInstance>().OnStop();
}
protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
{
existingContainer.Update(b =>
{
b.RegisterInstance(_loggerFactory);
b.RegisterGeneric(typeof(Logger<>))
.As(typeof(ILogger<>))
.SingleInstance();
});
existingContainer.RegisterImplementation<IUserIdentityProvider, UserIdentityProvider>();
existingContainer.Update(b => b.RegisterInstance(_settings));
existingContainer.Update(
b => b.Register<IRepository>(c =>
{
var settings = c.Resolve<IMonikServiceSettings>();
switch (settings.DbProvider)
{
case DbProvider.SqlServer:
return new RepositorySqlServer(settings);
case DbProvider.PostgreSql:
return new RepositoryPostgreSql(settings);
default:
throw new ArgumentException($"Unsupported {nameof(DbProvider)}: {settings.DbProvider}");
}
})
.SingleInstance()
);
existingContainer.RegisterSingleton<IMonik, MonikEmbedded>();
existingContainer.RegisterSingleton<ICacheSourceInstance, CacheSourceInstance>();
existingContainer.RegisterSingleton<ICacheLog, CacheLog>();
existingContainer.RegisterSingleton<ICacheKeepAlive, CacheKeepAlive>();
existingContainer.RegisterSingleton<ICacheMetric, CacheMetric>();
existingContainer.RegisterSingleton<IMessageProcessor, MessageProcessor>();
existingContainer.RegisterSingleton<IMessagePump, MessagePump>();
existingContainer.RegisterImplementation<IMetricObject, MetricObject>();
existingContainer.Update(builder => builder.Register(c => existingContainer));
}
protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
{
// Perform registrations that should have a request lifetime
}
protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context)
{
// No registrations should be performed in here, however you may
// resolve things that are needed during request startup.
}
// Use JSON.NET serializer
protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration =>
NancyInternalConfiguration.WithOverrides(c => c.Serializers = new [] {typeof(JsonNetSerializer)});
}
//end of class
}
|
||||
TheStack | b5f87d2bdc631f087e658b1e23ccea810b811bab | C#code:C# | {"size": 3578, "ext": "cs", "max_stars_repo_path": "src/DynamoCoreWpf/Views/Core/ConnectorPinView.xaml.cs", "max_stars_repo_name": "minhphi93/Dynamo", "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:18:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:18:03.000Z", "max_issues_repo_path": "src/DynamoCoreWpf/Views/Core/ConnectorPinView.xaml.cs", "max_issues_repo_name": "minhphi93/Dynamo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DynamoCoreWpf/Views/Core/ConnectorPinView.xaml.cs", "max_forks_repo_name": "minhphi93/Dynamo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.5272727273, "max_line_length": 99, "alphanum_fraction": 0.6140301845} | using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Dynamo.Configuration;
using Dynamo.Controls;
using Dynamo.Graph.Connectors;
using Dynamo.Selection;
using Dynamo.UI;
using Dynamo.UI.Controls;
using Dynamo.UI.Prompts;
using Dynamo.Utilities;
using Dynamo.ViewModels;
using DynCmd = Dynamo.Models.DynamoModel;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
namespace Dynamo.Nodes
{
/// <summary>
/// Interaction logic for ConnectorPinView.xaml
/// </summary>
public partial class ConnectorPinView : IViewModelView<ConnectorPinViewModel>
{
public ConnectorPinViewModel ViewModel { get; private set; }
/// <summary>
/// Old ZIndex of node. It's set, when mouse leaves node.
/// </summary>
private int oldZIndex;
public ConnectorPinView()
{
// Add DynamoConverters - currently using the InverseBoolToVisibilityCollapsedConverter
// to be able to collapse pins
Resources.MergedDictionaries.Add(SharedDictionaryManager.DynamoConvertersDictionary);
InitializeComponent();
ViewModel = null;
Loaded += OnPinViewLoaded;
}
private void OnPinViewLoaded(object sender, RoutedEventArgs e)
{
ViewModel = this.DataContext as ConnectorPinViewModel;
}
private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
BringToFront();
}
private void OnPinViewMouseLeave(object sender, MouseEventArgs e)
{
ViewModel.ZIndex = oldZIndex;
}
/// <summary>
/// Sets ZIndex of the particular note to be the highest in the workspace
/// This brings the note to the forefront of the workspace when clicked
/// </summary>
private void BringToFront()
{
if (ConnectorPinViewModel.StaticZIndex == int.MaxValue)
{
PrepareZIndex();
}
ViewModel.ZIndex = ++ConnectorPinViewModel.StaticZIndex;
}
/// <summary>
/// If ZIndex is more then max value of int, it should be set back to 0 for all elements.
/// The ZIndex for ConnectorPins is set to match that of nodes.
/// </summary>
private void PrepareZIndex()
{
var parent = TemplatedParent as ContentPresenter;
if (parent == null) return;
// reset the ZIndex for all ConnectorPins
foreach (var child in parent.ChildrenOfType<ConnectorPinView>())
{
child.ViewModel.ZIndex = Configurations.NodeStartZIndex;
}
}
private void OnPinMouseDown(object sender, MouseButtonEventArgs e)
{
if (!ViewModel.Model.IsSelected)
{
if (!Keyboard.IsKeyDown(Key.LeftShift) && !Keyboard.IsKeyDown(Key.RightShift))
{
DynamoSelection.Instance.ClearSelection();
}
DynamoSelection.Instance.Selection.AddUnique(ViewModel.Model);
}
else
{
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
DynamoSelection.Instance.Selection.Remove(ViewModel.Model);
}
}
}
}
}
|
||||
TheStack | b5f8ba1cf69a997dbf552ea1d8d64483f900db60 | C#code:C# | {"size": 10268, "ext": "cs", "max_stars_repo_path": "LankaStocks/UserControls/UIMenu.cs", "max_stars_repo_name": "HasinduLanka/LankaStocks", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LankaStocks/UserControls/UIMenu.cs", "max_issues_repo_name": "HasinduLanka/LankaStocks", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LankaStocks/UserControls/UIMenu.cs", "max_forks_repo_name": "HasinduLanka/LankaStocks", "max_forks_repo_forks_event_min_datetime": "2019-07-30T14:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T14:29:00.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 37.0685920578, "max_line_length": 232, "alphanum_fraction": 0.5605765485} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static LankaStocks.Core;
using LankaStocks.KeyInput;
using System.Diagnostics;
using LankaStocks.Shared;
using System.Management;
namespace LankaStocks.UserControls
{
public partial class UIMenu : UserControl
{
public UIMenu()
{
InitializeComponent();
int itemC = 0;
foreach (var s in client.ps.Live.Items)
{
if (itemC < 100)
{
UItem item = new UItem { _Code = s.Key /*Name = s.Key.ToString()*/ };
DrawCodes.Add(s.Key);
item.CartItemSelected += CartItem_Selected;
//item.DoubleClick += BtnAddToCart_Click;
//item.PB.DoubleClick += BtnAddToCart_Click;
//item.btnaddtoc.Click += BtnAddToCart_Click;
flPanel.Controls.Add(item);
}
itemC++;
ItemBarcodes.Add(s.Value.Barcode);
}
CBItemCount.SelectedIndex = 0;
uiBasicSale1.TxtCode.KeyDown += TxtCode_KeyDown;
uiBasicSale1.TxtQty.KeyDown += TxtQty_KeyDown;
uiBasicSale1.btnIssue.Click += BtnIssue_Click;
//Forms.frmWaiting = new UIForms.FrmWaiting(UIForms.ServerStatus.Waiting);
// Forms.frmWaiting.Show();
#region KeyInput Handle
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
_KeyInput = new RawInput(this.Handle, true);
_KeyInput.KeyPressed += OnKeyPressed;
#endregion
//foreach (var s in _KeyInput._keyboardDriver.GetNames()) Debug.WriteLine($">>{s}");
}
private void CartItem_Selected(UItem.CartItemSelectedEventArgs args)
{
RepeatedFunctions.AddToCart(ref args.Item, 1, Cart);
uiBasicSale1.labelTotal.Text = $"Total : Rs.{RepeatedFunctions.RefCart(Cart, DGV).ToString("0.00")}";
}
private void OnKeyPressed(object sender, RawInputEventArg e)
{
Device = e.KeyPressEvent.DeviceName;
if (!uiBasicSale1.TxtCode.Focused && Device.ToLower().Contains(Pos_Barcode.ToLower()))
uiBasicSale1.TxtCode.Focus();
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
throw new Exception(e.ExceptionObject.ToString());
}
private readonly RawInput _KeyInput;
string Device = "";
string Pos_Barcode => localSettings.Data.POSBarcodeID;
readonly List<uint> DrawCodes = new List<uint>(); // Uint Item Codes To Draw In FlowLayoutPanel
public List<string> ItemBarcodes = new List<string>();
public static Dictionary<uint, decimal> Cart = new Dictionary<uint, decimal>();
uint ItemCode = 0;
readonly string BeginChar = "i";
private void UIMenu_Load(object sender, EventArgs e)
{
DrawItems(int.Parse(CBItemCount.Text), (int)TxtPageON.Value);
RepeatedFunctions.CheckBarcodeReader();
}
private void TxtCode_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
RepeatedFunctions.TxtCode_Handle(uiBasicSale1.TxtCode, uiBasicSale1.TxtQty, Cart, ItemBarcodes, ref ItemCode, ref Device, Pos_Barcode, BeginChar, DGV, uiBasicSale1.labelTotal);
}
}
private void TxtQty_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
RepeatedFunctions.TxtQty_Handle(uiBasicSale1.TxtCode, uiBasicSale1.TxtQty, Cart, ref ItemCode, ref Device, DGV, uiBasicSale1.labelTotal);
}
}
private void BtnIssue_Click(object sender, EventArgs e)
{
RepeatedFunctions.IssueItem(Cart);
uiBasicSale1.labelTotal.Text = $"Total : Rs.{RepeatedFunctions.RefCart(Cart, DGV).ToString("0.00")}";
}
#region Draw Item's Usercontrols In FlowLayoutPanel
void DrawItems(int ItemMax, int PageNO)
{
//int count = 0;
//if (DrawCodes.Count > ItemMax) count = ItemMax;
//else count = DrawCodes.Count;
for (int i = 0; i <= DrawCodes.Count; i++)
{
try
{
if (flPanel.Controls[i] is UItem S)
{
if (i >= ItemMax * (PageNO - 1) && i < ItemMax * PageNO)
{
S.Visible = true;
S._Code = DrawCodes[i];
S.Setdata(DrawCodes[i]);
}
else S.Visible = false;
}
}
catch { }
}
if (DrawCodes.Count < flPanel.Controls.Count)
{
for (int i = DrawCodes.Count; i < flPanel.Controls.Count; i++)
{
if (flPanel.Controls[i] is UItem S)
{
S.Visible = false;
}
}
}
TxtPageON.Maximum = (flPanel.Controls.Count / ItemMax) + 1;
}
private void CBItemCount_SelectedIndexChanged(object sender, EventArgs e)
{
DrawItems(int.Parse(CBItemCount.Text), (int)TxtPageON.Value);
}
private void TxtPageON_ValueChanged(object sender, EventArgs e)
{
DrawItems(int.Parse(CBItemCount.Text), (int)TxtPageON.Value);
}
#endregion
#region Search Item's In FlowLayoutPanel
private void TxtCode_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(TxtCode.Text))
{
Search_Item_Name("");
}
else if (uint.TryParse(TxtCode.Text, out uint o)) Search_Item(o);
}
private void TxtBarcode_TextChanged(object sender, EventArgs e)
{
Search_Item(TxtBarcode.Text);
}
private void TxtName_TextChanged(object sender, EventArgs e)
{
Search_Item_Name(TxtName.Text);
}
void Search_Item(uint Code)
{
DrawCodes.Clear();
foreach (var s in client.ps.Live.Items)
{
if (s.Key.ToString().Contains(Code.ToString())) DrawCodes.Add(s.Key);
}
DrawItems(int.Parse(CBItemCount.Text), (int)TxtPageON.Value);
}
void Search_Item(string BarCode)
{
DrawCodes.Clear();
foreach (var s in client.ps.Live.Items)
{
if (s.Value.Barcode.ToLower().Contains(BarCode.ToLower())) DrawCodes.Add(s.Key);
}
DrawItems(int.Parse(CBItemCount.Text, System.Globalization.NumberStyles.Any), (int)TxtPageON.Value);
}
void Search_Item_Name(string Name)
{
DrawCodes.Clear();
foreach (var s in client.ps.Live.Items)
{
if (s.Value.name.ToLower().Contains(Name.ToLower())) DrawCodes.Add(s.Key);
}
DrawItems(int.Parse(CBItemCount.Text), (int)TxtPageON.Value);
}
#endregion
#region Edit Handle
private void DGV_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (DGV.CurrentCell != null && DGV.Rows?[DGV.CurrentCell.RowIndex]?.Cells?[0].Value?.ToString() != null)
{
btnEdit.Enabled = true;
btnRemove.Enabled = true;
}
}
private void EditQtyOK_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
RepeatedFunctions.EditCart(Forms.frmEditQty.Code, Forms.frmEditQty.TxtQty.Value, Cart);
uiBasicSale1.labelTotal.Text = $"Total : Rs.{RepeatedFunctions.RefCart(Cart, DGV).ToString("0.00")}";
Forms.frmEditQty.Close();
}
}
private void EditQtyOK_Click(object sender, EventArgs e)
{
RepeatedFunctions.EditCart(Forms.frmEditQty.Code, Forms.frmEditQty.TxtQty.Value, Cart);
uiBasicSale1.labelTotal.Text = $"Total : Rs.{RepeatedFunctions.RefCart(Cart, DGV).ToString("0.00")}";
Forms.frmEditQty.Close();
}
private void BtnEdit_Click_1(object sender, EventArgs e)
{
if (DGV.CurrentCell != null && uint.TryParse(DGV.Rows?[DGV.CurrentCell.RowIndex]?.Cells?[0].Value?.ToString(), out uint uc) && uint.TryParse(DGV.Rows?[DGV.CurrentCell.RowIndex]?.Cells?[3].Value?.ToString(), out uint co))
{
Forms.frmEditQty = new UIForms.FrmEditQty(co) { Code = uc };
Forms.frmEditQty.labelName.Text = $"Name : {client.ps.Live.Items[uc].name}\t Code : {uc.ToString()}";
Forms.frmEditQty.btnOK.Click += EditQtyOK_Click;
Forms.frmEditQty.TxtQty.KeyDown += EditQtyOK_KeyDown;
Forms.frmEditQty.ShowDialog();
}
btnEdit.Enabled = false;
btnRemove.Enabled = false;
}
private void BtnRemove_Click_1(object sender, EventArgs e)
{
if (DGV.CurrentCell != null && uint.TryParse(DGV.Rows?[DGV.CurrentCell.RowIndex]?.Cells?[0].Value?.ToString(), out uint a))
{
RepeatedFunctions.RemoveCart(a, Cart);
uiBasicSale1.labelTotal.Text = $"Total : Rs.{RepeatedFunctions.RefCart(Cart, DGV).ToString("0.00")}";
}
btnEdit.Enabled = false;
btnRemove.Enabled = false;
}
#endregion
}
public struct DGVcart_Data
{
public uint Code { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public decimal Qty { get; set; }
public decimal Total { get; set; }
}
}
|
||||
TheStack | b5f8ba6ceb7d7e9e97e658b5a70bb0189708163d | C#code:C# | {"size": 2337, "ext": "cs", "max_stars_repo_path": "sdk/src/Services/Glue/Generated/Model/WorkflowGraph.cs", "max_stars_repo_name": "a-leontiev/aws-sdk-net", "max_stars_repo_stars_event_min_datetime": "2020-02-09T03:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-09T03:13:21.000Z", "max_issues_repo_path": "sdk/src/Services/Glue/Generated/Model/WorkflowGraph.cs", "max_issues_repo_name": "lukeenterprise/aws-sdk-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/src/Services/Glue/Generated/Model/WorkflowGraph.cs", "max_forks_repo_name": "lukeenterprise/aws-sdk-net", "max_forks_repo_forks_event_min_datetime": "2021-12-22T18:53:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T18:53:25.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 30.75, "max_line_length": 102, "alphanum_fraction": 0.6148908858} | /*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Glue.Model
{
/// <summary>
/// A workflow graph represents the complete workflow containing all the AWS Glue components
/// present in the workflow and all the directed connections between them.
/// </summary>
public partial class WorkflowGraph
{
private List<Edge> _edges = new List<Edge>();
private List<Node> _nodes = new List<Node>();
/// <summary>
/// Gets and sets the property Edges.
/// <para>
/// A list of all the directed connections between the nodes belonging to the workflow.
/// </para>
/// </summary>
public List<Edge> Edges
{
get { return this._edges; }
set { this._edges = value; }
}
// Check to see if Edges property is set
internal bool IsSetEdges()
{
return this._edges != null && this._edges.Count > 0;
}
/// <summary>
/// Gets and sets the property Nodes.
/// <para>
/// A list of the the AWS Glue components belong to the workflow represented as nodes.
/// </para>
/// </summary>
public List<Node> Nodes
{
get { return this._nodes; }
set { this._nodes = value; }
}
// Check to see if Nodes property is set
internal bool IsSetNodes()
{
return this._nodes != null && this._nodes.Count > 0;
}
}
} |
||||
TheStack | b5f97b5be9c6bad9eba5e48ffdc7cad9900a2b65 | C#code:C# | {"size": 797, "ext": "cs", "max_stars_repo_path": "src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinWxverify/CgibinWxverifyCheckWxverifyNicknameResponse.cs", "max_stars_repo_name": "dotNetTreasury/DotNetCore.SKIT.FlurlHttpClient.Wechat", "max_stars_repo_stars_event_min_datetime": "2021-11-04T12:37:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T12:37:18.000Z", "max_issues_repo_path": "src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinWxverify/CgibinWxverifyCheckWxverifyNicknameResponse.cs", "max_issues_repo_name": "KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinWxverify/CgibinWxverifyCheckWxverifyNicknameResponse.cs", "max_forks_repo_name": "KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.6538461538, "max_line_length": 80, "alphanum_fraction": 0.634880803} | using System;
using System.Collections.Generic;
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [POST] /cgi-bin/wxverify/checkwxverifynickname 接口的响应。</para>
/// </summary>
public class CgibinWxverifyCheckWxverifyNicknameResponse : WechatApiResponse
{
/// <summary>
/// 获取或设置是否命中关键字策略。
/// </summary>
[Newtonsoft.Json.JsonProperty("hit_condition")]
[System.Text.Json.Serialization.JsonPropertyName("hit_condition")]
public bool IsHinted { get; set; }
/// <summary>
/// 获取或设置命中关键字的说明描述。
/// </summary>
[Newtonsoft.Json.JsonProperty("wording")]
[System.Text.Json.Serialization.JsonPropertyName("wording")]
public string? Wording { get; set; }
}
}
|
||||
TheStack | b5fdee06a9f0d9c112e64116d65481aa04feef18 | C#code:C# | {"size": 7228, "ext": "cs", "max_stars_repo_path": "source/Iam/Demo.Nebula.Web/Controllers/HomeController.cs", "max_stars_repo_name": "HTT323/IAM", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Iam/Demo.Nebula.Web/Controllers/HomeController.cs", "max_issues_repo_name": "HTT323/IAM", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Iam/Demo.Nebula.Web/Controllers/HomeController.cs", "max_forks_repo_name": "HTT323/IAM", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.2585365854, "max_line_length": 139, "alphanum_fraction": 0.5821804095} | #region
using System;
using System.Collections.Generic;
using System.IdentityModel.Protocols.WSTrust;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Threading.Tasks;
using System.Web.Mvc;
using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using Thinktecture.IdentityModel.Constants;
using Thinktecture.IdentityModel.WSTrust;
#endregion
namespace Demo.Nebula.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize]
public async Task<ActionResult> Claims()
{
var user = User as ClaimsPrincipal;
var name = User.Identity.Name;
if (user == null)
throw new InvalidOperationException();
var accessToken = user.Claims.First(f => f.Type == "access_token").Value;
var uic = new UserInfoClient(new Uri("https://auth.iam.dev:44300/connect/userinfo"), accessToken);
var ui = await uic.GetAsync();
ViewBag.Json = ui.JsonObject;
return View();
}
[Authorize]
public async Task<ActionResult> SecuredApiViewer()
{
var user = User as ClaimsPrincipal;
if (user == null)
throw new InvalidOperationException();
var accessToken = user.Claims.First(f => f.Type == "access_token").Value;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}");
var json = await httpClient.GetStringAsync("https://localhost:44330/identity");
ViewBag.Json = JArray.Parse(json).ToString();
return View();
}
public ActionResult GetCookie()
{
var httpClientHandler = new HttpClientHandler()
{
AllowAutoRedirect = false,
CookieContainer = new CookieContainer(),
Credentials = new NetworkCredential("Administrator", "Abcde12345#", "gatherforms")
};
using (var client = new HttpClient(httpClientHandler))
{
client.BaseAddress = new Uri("https://sp2013.gatherforms.org");
var response = client.PostAsync("/", null).Result;
var cookies = response.Headers.First(f => f.Key == "Set-Cookie");
}
return new HttpStatusCodeResult(HttpStatusCode.Accepted);
}
[Authorize]
public ActionResult SpTrust()
{
var cp = User as ClaimsPrincipal;
if (cp == null)
throw new InvalidOperationException();
var email = cp.Claims.First(f => f.Type == "email").Value;
var accessToken = cp.Claims.First(f => f.Type == "access_token").Value;
const string realm = "urn:nebula:8af89396db32459c8cf2a819f1142c36";
const string ep = "https://localhost:44303/issue/wstrust/mixed/username";
var factory =
new WSTrustChannelFactory(
new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
new EndpointAddress(ep))
{
TrustVersion = TrustVersion.WSTrust13
};
if (factory.Credentials == null)
throw new InvalidOperationException();
factory.Credentials.UserName.UserName = email;
factory.Credentials.UserName.Password = accessToken;
var channel = factory.CreateChannel();
var securityToken = new RequestSecurityToken
{
TokenType = TokenTypes.OasisWssSaml11TokenProfile11,
AppliesTo = new EndpointReference(realm),
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer
};
var message =
channel.Issue(Message.CreateMessage(MessageVersion.Default, WSTrust13Constants.Actions.Issue,
new WSTrustRequestBodyWriter(securityToken, new WSTrust13RequestSerializer(),
new WSTrustSerializationContext())));
var reader = message.GetReaderAtBodyContents();
var token = reader.ReadOuterXml();
const string assert = @"<trust:RequestSecurityTokenResponse xmlns:trust=""http://docs.oasis-open.org/ws-sx/ws-trust/200512"">";
const string assertStart = "<trust:RequestSecurityTokenResponse>";
const string assertEnd = "</trust:RequestSecurityTokenResponse>";
var startAssertIndex = token.IndexOf(assertStart, StringComparison.InvariantCulture);
token = token.Substring(startAssertIndex);
var endAssertIndex = token.IndexOf(assertEnd, StringComparison.InvariantCulture) + assertEnd.Length;
token = token.Substring(0, endAssertIndex);
token = token.Replace(assertStart, assert);
var cookies = GetAuthenticationCookie(token);
return Content(token, "text/xml");
}
private static IEnumerable<string> GetAuthenticationCookie(string token)
{
const string wa = "wsignin1.0";
const string wctx = "/_layouts/Authenticate.aspx?Source=%2F";
var httpClientHandler = new HttpClientHandler()
{
AllowAutoRedirect = false,
CookieContainer = new CookieContainer()
};
using (var client = new HttpClient(httpClientHandler))
{
client.BaseAddress = new Uri("https://sp2013.gatherforms.org");
var data =
new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("wa", wa),
new KeyValuePair<string, string>("wresult", token),
new KeyValuePair<string, string>("wctx", wctx)
});
var response = client.PostAsync("/_trust/", data).Result;
var cookies = response.Headers.First(f => f.Key == "Set-Cookie");
return cookies.Value;
}
}
[Authorize]
public async Task<ActionResult> SecuredApiCcViewer()
{
var client =
new TokenClient(
"https://auth.iam.dev:44300/connect/token",
"nebula-service",
"nebula-api-access");
var ccToken = await client.RequestClientCredentialsAsync("nebula-api-scope");
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {ccToken.AccessToken}");
var json = await httpClient.GetStringAsync("https://localhost:44330/identity");
ViewBag.Json = JArray.Parse(json).ToString();
return View();
}
}
} |
||||
TheStack | bd002f70c28dc6f64d2c28c2d9f711c8026c15b6 | C#code:C# | {"size": 386, "ext": "cs", "max_stars_repo_path": "Assets/Script/BTree/PlayerAI/PreCondition/BTreePreConditionPlayerIsInCompany.cs", "max_stars_repo_name": "qingshu/BTreeDemo", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Script/BTree/PlayerAI/PreCondition/BTreePreConditionPlayerIsInCompany.cs", "max_issues_repo_name": "qingshu/BTreeDemo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Script/BTree/PlayerAI/PreCondition/BTreePreConditionPlayerIsInCompany.cs", "max_forks_repo_name": "qingshu/BTreeDemo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.6923076923, "max_line_length": 80, "alphanum_fraction": 0.7875647668} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BTreePreConditionPlayerIsInCompany : BTreePreCondition
{
public override bool IsPreCondition(BTreeParamData bTreeInputData)
{
BTreePlayerInputData inputData = bTreeInputData as BTreePlayerInputData;
return inputData.playerData.pos == Player.PlayerPos.company;
}
}
|
||||
TheStack | bd0049b12788af8b1f9b338f5fb5e1a3059da03b | C#code:C# | {"size": 1024, "ext": "cs", "max_stars_repo_path": "src/SpoolWatcher/Helpers/FiltersHelper.cs", "max_stars_repo_name": "magalhaesleo/SpoolWatcher", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SpoolWatcher/Helpers/FiltersHelper.cs", "max_issues_repo_name": "magalhaesleo/SpoolWatcher", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SpoolWatcher/Helpers/FiltersHelper.cs", "max_forks_repo_name": "magalhaesleo/SpoolWatcher", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.0322580645, "max_line_length": 124, "alphanum_fraction": 0.599609375} | using System;
using System.Collections.Generic;
namespace SpoolerWatcher.Helpers
{
internal static class FiltersHelper
{
internal static IEnumerable<PrinterNotifyField> ToPrinterNotifyFields(this PrinterNotifyFilters printerNotifyFilter)
{
foreach (Enum value in Enum.GetValues(printerNotifyFilter.GetType()))
{
if (printerNotifyFilter.HasFlag(value))
{
yield return (PrinterNotifyField)Enum.Parse(typeof(PrinterNotifyField), value.ToString());
}
}
}
internal static IEnumerable<JobNotifyField> ToJobNotifyFields(this JobNotifyFilters jobNotifyFilter)
{
foreach (Enum value in Enum.GetValues(jobNotifyFilter.GetType()))
{
if (jobNotifyFilter.HasFlag(value))
{
yield return (JobNotifyField)Enum.Parse(typeof(JobNotifyField), value.ToString());
}
}
}
}
}
|
||||
TheStack | bd0073fd60f9b7a52c1636460d63f879fe12dcea | C#code:C# | {"size": 1178, "ext": "cs", "max_stars_repo_path": "pst/pst/impl/blockallocation/datatree/ExternalDataBlockFactory.cs", "max_stars_repo_name": "Clancey/PST", "max_stars_repo_stars_event_min_datetime": "2017-12-20T20:55:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T15:40:40.000Z", "max_issues_repo_path": "pst/pst/impl/blockallocation/datatree/ExternalDataBlockFactory.cs", "max_issues_repo_name": "Clancey/PST", "max_issues_repo_issues_event_min_datetime": "2019-08-28T09:43:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-23T08:52:38.000Z", "max_forks_repo_path": "pst/pst/impl/blockallocation/datatree/ExternalDataBlockFactory.cs", "max_forks_repo_name": "Clancey/PST", "max_forks_repo_forks_event_min_datetime": "2018-03-01T09:50:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T21:53:06.000Z"} | {"max_stars_count": 22.0, "max_issues_count": 1.0, "max_forks_count": 12.0, "avg_line_length": 33.6571428571, "max_line_length": 104, "alphanum_fraction": 0.6443123939} | using pst.encodables.ndb;
using pst.encodables.ndb.blocks;
using pst.encodables.ndb.blocks.data;
using pst.interfaces;
using pst.interfaces.blockallocation.datatree;
using pst.utilities;
namespace pst.impl.blockallocation.datatree
{
class ExternalDataBlockFactory : IDataBlockFactory<BinaryData, ExternalDataBlock>
{
private readonly IBlockDataObfuscator dataObfuscator;
public ExternalDataBlockFactory(IBlockDataObfuscator dataObfuscator)
{
this.dataObfuscator = dataObfuscator;
}
public ExternalDataBlock Create(IB blockOffset, BID blockId, BinaryData data)
{
var obfuscatedData = dataObfuscator.Obfuscate(data, blockId);
return
new ExternalDataBlock(
obfuscatedData,
BinaryData.OfSize(Utilities.GetExternalDataBlockPaddingSize(obfuscatedData.Length)),
new BlockTrailer(
obfuscatedData.Length,
BlockSignature.Calculate(blockOffset, blockId),
Crc32.ComputeCrc32(obfuscatedData),
blockId));
}
}
}
|
||||
TheStack | bd0290dccb28ed3d9faa45d39c3bba29a92e9372 | C#code:C# | {"size": 2416, "ext": "cs", "max_stars_repo_path": "DynamicFramework/Basic/DynamicFramework_Integration/EntityTemplate/Real/JG_AdjustEntity.cs", "max_stars_repo_name": "xzssws/Code-Generate", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DynamicFramework/Basic/DynamicFramework_Integration/EntityTemplate/Real/JG_AdjustEntity.cs", "max_issues_repo_name": "xzssws/Code-Generate", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DynamicFramework/Basic/DynamicFramework_Integration/EntityTemplate/Real/JG_AdjustEntity.cs", "max_forks_repo_name": "xzssws/Code-Generate", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.3805309735, "max_line_length": 43, "alphanum_fraction": 0.4341887417} | using System;
namespace DynamicEntity
{
/// <summary>
/// JG_Adjust
/// </summary>
public class JG_AdjustEntity:BaseEntity
{
private string _ja_id;
/// <summary>
/// 存款ID
/// </summary>
public string JA_ID
{
get { return _ja_id; }
set { _ja_id = value; }
}
private string _ja_fmid;
/// <summary>
/// 原存款ID
/// </summary>
public string JA_FmID
{
get { return _ja_fmid; }
set { _ja_fmid = value; }
}
private string _ja_xybh;
/// <summary>
/// 协议编号
/// </summary>
public string JA_Xybh
{
get { return _ja_xybh; }
set { _ja_xybh = value; }
}
private string _ja_fmxybh;
/// <summary>
/// 原协议编号
/// </summary>
public string JA_FmXybh
{
get { return _ja_fmxybh; }
set { _ja_fmxybh = value; }
}
private DateTime? _ja_sqtime;
/// <summary>
/// 申请时间
/// </summary>
public DateTime? JA_SqTime
{
get { return _ja_sqtime; }
set { _ja_sqtime = value; }
}
private DateTime? _ja_qrtime;
/// <summary>
/// 确认时间
/// </summary>
public DateTime? JA_QrTime
{
get { return _ja_qrtime; }
set { _ja_qrtime = value; }
}
private string _ja_qrr;
/// <summary>
/// 确认人
/// </summary>
public string JA_Qrr
{
get { return _ja_qrr; }
set { _ja_qrr = value; }
}
private string _ja_lc;
/// <summary>
/// 0:申请1审核2确认
/// </summary>
public string JA_LC
{
get { return _ja_lc; }
set { _ja_lc = value; }
}
private string _ja_tzzflsh;
/// <summary>
/// 调账支付流水号
/// </summary>
public string JA_Tzzflsh
{
get { return _ja_tzzflsh; }
set { _ja_tzzflsh = value; }
}
private string _ja_fmcklsh;
/// <summary>
/// 原存款流水号
/// </summary>
public string JA_FmCklsh
{
get { return _ja_fmcklsh; }
set { _ja_fmcklsh = value; }
}
}
}
|
||||
TheStack | bd04ced917b64a882084f700c3c77a9c4f8aa0cb | C#code:C# | {"size": 13411, "ext": "cs", "max_stars_repo_path": "SoundComposition/VisualProperties.cs", "max_stars_repo_name": "forki/Labs", "max_stars_repo_stars_event_min_datetime": "2015-09-08T17:11:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-08T17:11:41.000Z", "max_issues_repo_path": "SoundComposition/VisualProperties.cs", "max_issues_repo_name": "forki/Labs", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoundComposition/VisualProperties.cs", "max_forks_repo_name": "forki/Labs", "max_forks_repo_forks_event_min_datetime": "2018-02-28T09:12:45.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-28T09:12:45.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 36.2459459459, "max_line_length": 113, "alphanum_fraction": 0.4318842741} | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// 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 SoundComposition.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Composition;
using Windows.UI.Core;
namespace SoundComposition
{
class VisualProperties : IFrameworkView
{
//------------------------------------------------------------------------------
//
// VisualProperties.Initialize
//
// This method is called during startup to associate the IFrameworkView with the
// CoreApplicationView.
//
//------------------------------------------------------------------------------
void IFrameworkView.Initialize(CoreApplicationView view)
{
_view = view;
_random = new Random();
}
//------------------------------------------------------------------------------
//
// VisualProperties.SetWindow
//
// This method is called when the CoreApplication has created a new CoreWindow,
// allowing the application to configure the window and start producing content
// to display.
//
//------------------------------------------------------------------------------
void IFrameworkView.SetWindow(CoreWindow window)
{
_window = window;
InitNewComposition();
_window.PointerPressed += OnPointerPressed;
_window.PointerMoved += OnPointerMoved;
_window.PointerReleased += OnPointerReleased;
}
//------------------------------------------------------------------------------
//
// VisualProperties.OnPointerPressed
//
// This method is called when the user touches the screen, taps it with a stylus
// or clicks the mouse.
//
//------------------------------------------------------------------------------
void OnPointerPressed(CoreWindow window, PointerEventArgs args)
{
Point position = args.CurrentPoint.Position;
//
// Walk our list of visuals to determine who, if anybody, was selected
//
foreach (var child in _root.Children)
{
//
// Did we hit this child?
//
Vector3 offset = child.Offset;
Vector2 size = child.Size;
if ((position.X >= offset.X) &&
(position.X < offset.X + size.X) &&
(position.Y >= offset.Y) &&
(position.Y < offset.Y + size.Y))
{
//
// This child was hit. Since the children are stored back to front,
// the last one hit is the front-most one so it wins
//
_currentVisual = child as ContainerVisual;
_offsetBias = new Vector2((float)(offset.X - position.X),
(float)(offset.Y - position.Y));
}
}
//
// If a visual was hit, bring it to the front of the Z order
//
if (_currentVisual != null)
{
ContainerVisual parent = _currentVisual.Parent as ContainerVisual;
parent.Children.Remove(_currentVisual);
parent.Children.InsertAtTop(_currentVisual);
var instrument = _library.Instruments
.FirstOrDefault(x => x.Name == Instrument.FromElement(_currentVisual));
if (null != instrument)
{
if (instrument.Songs.Any())
{
var song = instrument.Songs.FirstOrDefault(
x => x.Note == _library.SelectedNote
&& x.Octave == _library.SelectedOctave);
if (null != song)
{
song.Play();
}
}
}
}
}
//------------------------------------------------------------------------------
//
// VisualProperties.OnPointerMoved
//
// This method is called when the user moves their finger, stylus or mouse with
// a button pressed over the screen.
//
//------------------------------------------------------------------------------
void OnPointerMoved(CoreWindow window, PointerEventArgs args)
{
//
// If a visual is selected, drag it with the pointer position and
// make it opaque while we drag it
//
if (_currentVisual != null)
{
//
// Set up the properties of the visual the first time it is
// dragged. This will last for the duration of the drag
//
if (!_dragging)
{
_currentVisual.Opacity = 1.0f;
//
// Transform the first child of the current visual so that
// the image is rotated
//
foreach (var child in _currentVisual.Children)
{
child.RotationAngleInDegrees = 45.0f;
child.CenterPoint = new Vector3(_currentVisual.Size.X / 2, _currentVisual.Size.Y / 2, 0);
break;
}
//
// Clip the visual to its original layout rect by using an inset
// clip with a one-pixel margin all around
//
var clip = _compositor.CreateInsetClip();
clip.LeftInset = 1.0f;
clip.RightInset = 1.0f;
clip.TopInset = 1.0f;
clip.BottomInset = 1.0f;
_currentVisual.Clip = clip;
_dragging = true;
}
Point position = args.CurrentPoint.Position;
_currentVisual.Offset = new Vector3((float)(position.X + _offsetBias.X),
(float)(position.Y + _offsetBias.Y),
0.0f);
}
}
//------------------------------------------------------------------------------
//
// VisualProperties.OnPointerReleased
//
// This method is called when the user lifts their finger or stylus from the
// screen, or lifts the mouse button.
//
//------------------------------------------------------------------------------
void OnPointerReleased(CoreWindow window, PointerEventArgs args)
{
//
// If a visual was selected, make it transparent again when it is
// released and restore the transform and clip
//
if (_currentVisual != null)
{
if (_dragging)
{
//
// Remove the transform from the first child
//
foreach (var child in _currentVisual.Children)
{
child.RotationAngle = 0.0f;
child.CenterPoint = new Vector3(0.0f, 0.0f, 0.0f);
break;
}
_currentVisual.Opacity = 0.8f;
_currentVisual.Clip = null;
_dragging = false;
}
_currentVisual = null;
}
}
//------------------------------------------------------------------------------
//
// VisualProperties.Load
//
// This method is called when a specific page is being loaded in the
// application. It is not used for this application.
//
//------------------------------------------------------------------------------
void IFrameworkView.Load(string unused)
{
}
//------------------------------------------------------------------------------
//
// VisualProperties.Run
//
// This method is called by CoreApplication.Run() to actually run the
// dispatcher's message pump.
//
//------------------------------------------------------------------------------
void IFrameworkView.Run()
{
_window.Activate();
_window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit);
}
//------------------------------------------------------------------------------
//
// VisualProperties.Uninitialize
//
// This method is called during shutdown to disconnect the CoreApplicationView,
// and CoreWindow from the IFrameworkView.
//
//------------------------------------------------------------------------------
void IFrameworkView.Uninitialize()
{
_window = null;
_view = null;
}
//------------------------------------------------------------------------------
//
// VisualProperties.InitNewComposition
//
// This method is called by SetWindow(), where we initialize Composition after
// the CoreWindow has been created.
//
//------------------------------------------------------------------------------
async void InitNewComposition()
{
//
// Set up Windows.UI.Composition Compositor, root ContainerVisual, and associate with
// the CoreWindow.
//
_compositor = new Compositor();
_root = _compositor.CreateContainerVisual();
_compositionTarget = _compositor.CreateTargetForCurrentView();
_compositionTarget.Root = _root;
_library = new Library();
await _library.LoadInstruments();
_library.SelectedNote = _library.Notes.FirstOrDefault();
_library.SelectedOctave = _library.Octaves.FirstOrDefault();
//
// Create a few visuals for our window
//
foreach(var instrument in _library.Instruments)
{
_root.Children.InsertAtTop(CreateChildElement(instrument));
}
}
//------------------------------------------------------------------------------
//
// VisualProperties.CreateChildElement
//
// Creates a small sub-tree to represent a visible element in our application.
//
//------------------------------------------------------------------------------
Visual CreateChildElement(Instrument instrument)
{
return instrument.ComposeElement(_compositor);
}
// CoreWindow / CoreApplicationView
private CoreWindow _window;
private CoreApplicationView _view;
// Windows.UI.Composition
private Compositor _compositor;
private CompositionTarget _compositionTarget;
private ContainerVisual _root;
private ContainerVisual _currentVisual;
private Vector2 _offsetBias;
private bool _dragging;
// Helpers
private Random _random;
//library
private Library _library;
}
public sealed class VisualPropertiesFactory : IFrameworkViewSource
{
//------------------------------------------------------------------------------
//
// VisualPropertiesFactory.CreateView
//
// This method is called by CoreApplication to provide a new IFrameworkView for
// a CoreWindow that is being created.
//
//------------------------------------------------------------------------------
IFrameworkView IFrameworkViewSource.CreateView()
{
return new VisualProperties();
}
//------------------------------------------------------------------------------
//
// main
//
//------------------------------------------------------------------------------
static int Main(string[] args)
{
CoreApplication.Run(new VisualPropertiesFactory());
return 0;
}
}
}
|
||||
TheStack | bd05294f345cddfd18ef5639720abf27e42c30f3 | C#code:C# | {"size": 1442, "ext": "cs", "max_stars_repo_path": "IfTasks/IfTask14/IfTask14/Program.cs", "max_stars_repo_name": "lauriellonen/digitrade-test-4-9-2019", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IfTasks/IfTask14/IfTask14/Program.cs", "max_issues_repo_name": "lauriellonen/digitrade-test-4-9-2019", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IfTasks/IfTask14/IfTask14/Program.cs", "max_forks_repo_name": "lauriellonen/digitrade-test-4-9-2019", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.0444444444, "max_line_length": 95, "alphanum_fraction": 0.4736477115} | using System;
namespace IfTask14
{
/// <summary>
/// Versio 0.1
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This program will sort the numbers from smaalest to biggest. ");
//Program will ask user the first number.
Console.WriteLine("Input first number: ");
int x = int.Parse(Console.ReadLine());
//Program will ask user the second number.
Console.Write("Input second number: ");
int y = int.Parse(Console.ReadLine());
//Program will ask user the third number.
Console.Write("Input third number: ");
int z = int.Parse(Console.ReadLine());
//Here is where the number sorting will happen.
if (x > y) { }
if (y > z)
Console.WriteLine($"{z},{y},{x}");
else if (x > z)
Console.WriteLine($"{y},{z},{x}");
else Console.WriteLine($"{y},{x},{z}");
if (y > x)
if (x > z)
Console.WriteLine($"{z},{x},{y}");
else if (y > z)
Console.WriteLine($"{x},{z},{y}");
else Console.WriteLine($"{x},{y},{z}");
//Message to use how to close program.
Console.WriteLine("Press any button to close program");
}
}
}
|
||||
TheStack | bd056ed8010c4bb1f06563ab2700124f9acc18cf | C#code:C# | {"size": 187, "ext": "cs", "max_stars_repo_path": "HistoricalDataPreparer/src/Dfe.Spi.HistoricalDataPreparer.Domain/Gias/CodeNamePair.cs", "max_stars_repo_name": "DFE-Digital/spi-tools", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HistoricalDataPreparer/src/Dfe.Spi.HistoricalDataPreparer.Domain/Gias/CodeNamePair.cs", "max_issues_repo_name": "DFE-Digital/spi-tools", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HistoricalDataPreparer/src/Dfe.Spi.HistoricalDataPreparer.Domain/Gias/CodeNamePair.cs", "max_forks_repo_name": "DFE-Digital/spi-tools", "max_forks_repo_forks_event_min_datetime": "2021-04-10T21:51:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T17:43:22.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 23.375, "max_line_length": 52, "alphanum_fraction": 0.6470588235} | namespace Dfe.Spi.HistoricalDataPreparer.Domain.Gias
{
public class CodeNamePair
{
public string Code { get; set; }
public string DisplayName { get; set; }
}
} |
||||
TheStack | bd0586e7a3d99e3849f6112d466987bd3f295abf | C#code:C# | {"size": 4891, "ext": "cs", "max_stars_repo_path": "Assets/Sisus/Power Inspector/Code/Editor/Drawers/UnityObject/Asset/FormattedText/Yaml/SceneDrawer.cs", "max_stars_repo_name": "rafaeldolfe/MasterServerChess", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Sisus/Power Inspector/Code/Editor/Drawers/UnityObject/Asset/FormattedText/Yaml/SceneDrawer.cs", "max_issues_repo_name": "rafaeldolfe/MasterServerChess", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Sisus/Power Inspector/Code/Editor/Drawers/UnityObject/Asset/FormattedText/Yaml/SceneDrawer.cs", "max_forks_repo_name": "rafaeldolfe/MasterServerChess", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.1312217195, "max_line_length": 108, "alphanum_fraction": 0.6898384788} | #if UNITY_EDITOR
using System;
using JetBrains.Annotations;
using Sisus.Attributes;
using UnityEditor;
using UnityEngine;
namespace Sisus
{
[Serializable, DrawerForAsset(typeof(SceneAsset), false, true)]
public class SceneDrawer : CustomEditorAssetDrawer
{
[CanBeNull]
private Code yaml;
private float yamlContentHeight;
private Vector2 yamlViewScrollPos;
private float yamlViewportHeight;
private bool yamlViewHasScrollBar;
/// <summary>
///
/// </summary>
public override float Height
{
get
{
return ViewingYaml() ? yamlViewportHeight : base.Height;
}
}
private float YamlContentHeight
{
get
{
return yamlContentHeight;
}
}
/// <inheritdoc />
protected override void OnInspectorWidthChanged()
{
base.OnChildLayoutChanged();
if(yaml != null)
{
yamlContentHeight = yaml.LineCount * DrawGUI.SingleLineHeight;
yamlViewportHeight = CalculateViewportHeight();
yamlViewHasScrollBar = yamlContentHeight > yamlViewportHeight;
}
}
/// <inheritdoc />
protected override void OnDebugModeChanged(bool nowEnabled)
{
if(nowEnabled)
{
RebuildYamlContent();
UnityEditor.SceneManagement.EditorSceneManager.sceneSaved += OnSceneSaved;
}
else
{
UnityEditor.SceneManagement.EditorSceneManager.sceneSaved -= OnSceneSaved;
if(yaml != null)
{
yaml.Dispose();
yaml = null;
}
yamlContentHeight = 0f;
yamlViewScrollPos.x = 0f;
yamlViewScrollPos.y = 0f;
yamlViewportHeight = 0f;
yamlViewHasScrollBar = false;
}
base.OnDebugModeChanged(nowEnabled);
}
/// <inheritdoc />
public override bool DrawBody(Rect position)
{
if(ViewingYaml())
{
var contentRect = position;
contentRect.x = 0f;
contentRect.y = 0f;
contentRect.height = yamlContentHeight;
if(yamlViewHasScrollBar)
{
contentRect.width -= DrawGUI.ScrollBarWidth;
}
var viewportRect = position;
viewportRect.height = yamlViewportHeight;
DrawGUI.BeginScrollView(viewportRect, contentRect, ref yamlViewScrollPos);
{
var style = InspectorPreferences.Styles.formattedText;
var linePosition = contentRect;
linePosition.height = DrawGUI.SingleLineHeight;
int firstIndex = Mathf.FloorToInt(yamlViewScrollPos.y / DrawGUI.SingleLineHeight);
int lastIndex = firstIndex + Mathf.FloorToInt(yamlViewportHeight / DrawGUI.SingleLineHeight);
int lineCount = yaml.LineCount;
if(lastIndex >= lineCount)
{
lastIndex = lineCount - 1;
}
linePosition.y = yamlViewScrollPos.y - yamlViewScrollPos.y % DrawGUI.SingleLineHeight;
for(int n = firstIndex; n <= lastIndex; n++)
{
EditorGUI.SelectableLabel(linePosition, yaml[n], style);
linePosition.y += DrawGUI.SingleLineHeight;
}
}
DrawGUI.EndScrollView();
return false;
}
return base.DrawBody(position);
}
/// <inheritdoc />
public override void Dispose()
{
if(yaml != null)
{
yaml.Dispose();
yaml = null;
yamlContentHeight = 0f;
yamlViewScrollPos.x = 0f;
yamlViewScrollPos.y = 0f;
yamlViewportHeight = 0f;
yamlViewHasScrollBar = false;
UnityEditor.SceneManagement.EditorSceneManager.sceneSaved -= OnSceneSaved;
}
base.Dispose();
}
private void OnSceneSaved(UnityEngine.SceneManagement.Scene savedScene)
{
var scene = UnityEngine.SceneManagement.SceneManager.GetSceneByPath(LocalPath);
if(savedScene == scene)
{
RebuildYamlContent();
}
}
private void RebuildYamlContent()
{
var yamlText = System.IO.File.ReadAllText(FullPath);
if(yaml != null)
{
if(string.Equals(yaml.TextUnformatted, yamlText))
{
return;
}
yaml.Dispose();
yaml = null;
}
var builder = CreateSyntaxFormatter();
yaml = new Code(builder);
builder.SetCode(yamlText);
builder.BuildAllBlocks();
builder.GeneratedBlocks.ToCode(ref yaml, builder, Fonts.NormalSizes);
yamlContentHeight = yaml.LineCount * DrawGUI.SingleLineHeight;
yamlViewportHeight = CalculateViewportHeight();
yamlViewHasScrollBar = yamlContentHeight > yamlViewportHeight;
}
private bool ViewingYaml()
{
return DebugMode && targets.Length == 1;
}
private float CalculateViewportHeight()
{
float height = inspector.State.WindowRect.height - inspector.ToolbarHeight - inspector.PreviewAreaHeight;
if(height < 0f)
{
return 0f;
}
if(HasHorizontalScrollBar())
{
height -= DrawGUI.ScrollBarWidth;
}
if(!UserSettings.MergedMultiEditMode && inspector.State.inspected.Length > 1)
{
height = Mathf.Min(yamlContentHeight, height);
}
return height;
}
private bool HasHorizontalScrollBar()
{
return yaml.width > Width;
}
private YamlSyntaxFormatter CreateSyntaxFormatter()
{
return YamlSyntaxFormatterPool.Pop();
}
}
}
#endif |
||||
TheStack | bd05bd4ca8fb881401caa5bf21b5a9a70025228d | C#code:C# | {"size": 3508, "ext": "cs", "max_stars_repo_path": "tests/Workbench.Core.Tests.Unit/Models/ExpressionConstraintModelTests.cs", "max_stars_repo_name": "constraint-capers/workbench", "max_stars_repo_stars_event_min_datetime": "2019-03-29T11:20:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-18T15:21:51.000Z", "max_issues_repo_path": "tests/Workbench.Core.Tests.Unit/Models/ExpressionConstraintModelTests.cs", "max_issues_repo_name": "digitalbricklayer/workbench", "max_issues_repo_issues_event_min_datetime": "2016-10-28T12:20:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T14:18:23.000Z", "max_forks_repo_path": "tests/Workbench.Core.Tests.Unit/Models/ExpressionConstraintModelTests.cs", "max_forks_repo_name": "dyna-project/workbench", "max_forks_repo_forks_event_min_datetime": "2015-07-30T14:01:56.000Z", "max_forks_repo_forks_event_max_datetime": "2015-07-30T14:01:56.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 87.0, "max_forks_count": 1.0, "avg_line_length": 52.3582089552, "max_line_length": 152, "alphanum_fraction": 0.7038198404} | using System;
using NUnit.Framework;
using Workbench.Core.Models;
using Workbench.Core.Nodes;
namespace Workbench.Core.Tests.Unit.Models
{
[TestFixture]
public class ExpressionConstraintModelTests
{
[Test]
public void Initialize_With_Raw_Expression_Parses_Expected_Variable_Name_On_Left()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel("$x > 1"));
var leftVariableReference = (SingletonVariableReferenceNode) sut.Expression.Node.InnerExpression.LeftExpression.InnerExpression;
Assert.That(leftVariableReference.VariableName, Is.EqualTo("x"));
}
[Test]
public void Initialize_With_Raw_Expression_Parses_Expected_Operator()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel(" $a1 > 999 "));
Assert.That(sut.Expression.OperatorType, Is.EqualTo(OperatorType.Greater));
}
[Test]
public void Initialize_With_Raw_Expression_Parses_Expected_Literal_On_Right()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel("$y <= 44"));
var rightLiteral = (IntegerLiteralNode) sut.Expression.Node.InnerExpression.RightExpression.InnerExpression;
Assert.That(rightLiteral.Value, Is.EqualTo(44));
}
[Test]
public void Initialize_With_Raw_Expression_Parses_Expected_Variable_Name_On_Right()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel("$y = $x"));
var rightVariableReference = (SingletonVariableReferenceNode)sut.Expression.Node.InnerExpression.RightExpression.InnerExpression;
Assert.That(rightVariableReference.VariableName, Is.EqualTo("x"));
}
[Test]
public void InitializeWithRawExpressionParsesExpectedAggregateVariableNameOnLeft()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel("$xx[1] > 1"));
var leftVariableReference = (AggregateVariableReferenceNode)sut.Expression.Node.InnerExpression.LeftExpression.InnerExpression;
Assert.That(leftVariableReference.VariableName, Is.EqualTo("xx"));
}
[Test]
public void InitializeWithRawExpressionParsesExpectedAggregateVariableSubscriptOnLeft()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel("$xx[1] > 1"));
var leftVariableReference = (AggregateVariableReferenceNode)sut.Expression.Node.InnerExpression.LeftExpression.InnerExpression;
Assert.That(leftVariableReference.SubscriptStatement.Subscript, Is.EqualTo(1));
}
[Test]
public void InitializeWithRawExpressionParsesExpectedAggregateVariableNameOnRight()
{
var sut = new ExpressionConstraintModel(WorkspaceModelFactory.Create().Model, new ConstraintExpressionModel("$x[1] > $x[2]"));
var rightVariableReference = (AggregateVariableReferenceNode)sut.Expression.Node.InnerExpression.RightExpression.InnerExpression;
Assert.That(rightVariableReference.VariableName, Is.EqualTo("x"));
}
}
}
|
||||
TheStack | bd075f61c62243c214178a55f9d79371288d6136 | C#code:C# | {"size": 3818, "ext": "cs", "max_stars_repo_path": "Official Windows Platform Sample/Windows Phone 8.1 samples/[C#]-Windows Phone 8.1 samples/Background sensors for Windows Phone 8.1 sample/C#/BackgroundTask/Scenario1_BackgroundTask.cs", "max_stars_repo_name": "zzgchina888/msdn-code-gallery-microsoft", "max_stars_repo_stars_event_min_datetime": "2022-01-21T01:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:41:10.000Z", "max_issues_repo_path": "Official Windows Platform Sample/Windows Phone 8.1 samples/[C#]-Windows Phone 8.1 samples/Background sensors for Windows Phone 8.1 sample/C#/BackgroundTask/Scenario1_BackgroundTask.cs", "max_issues_repo_name": "zzgchina888/msdn-code-gallery-microsoft", "max_issues_repo_issues_event_min_datetime": "2022-03-15T04:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T04:21:41.000Z", "max_forks_repo_path": "Official Windows Platform Sample/Windows Phone 8.1 samples/[C#]-Windows Phone 8.1 samples/Background sensors for Windows Phone 8.1 sample/C#/BackgroundTask/Scenario1_BackgroundTask.cs", "max_forks_repo_name": "zzgchina888/msdn-code-gallery-microsoft", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 38.9591836735, "max_line_length": 140, "alphanum_fraction": 0.639863803} | // Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Devices.Background;
using Windows.Devices.Sensors;
using Windows.Foundation;
using Windows.Storage;
namespace BackgroundTasks
{
public sealed class Scenario1_BackgroundTask : IBackgroundTask, IDisposable
{
private Accelerometer _accelerometer;
private BackgroundTaskDeferral _deferral;
private ulong _sampleCount;
/// <summary>
/// Background task entry point.
/// </summary>
/// <param name="taskInstance"></param>
public void Run(IBackgroundTaskInstance taskInstance)
{
_accelerometer = Accelerometer.GetDefault();
if (null != _accelerometer)
{
_sampleCount = 0;
// Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
uint minReportIntervalMsecs = _accelerometer.MinimumReportInterval;
_accelerometer.ReportInterval = minReportIntervalMsecs > 16 ? minReportIntervalMsecs : 16;
// Subscribe to accelerometer ReadingChanged events.
_accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
// Take a deferral that is released when the task is completed.
_deferral = taskInstance.GetDeferral();
// Get notified when the task is canceled.
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
// Store a setting so that the app knows that the task is running.
ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true;
}
}
/// <summary>
/// Called when the background task is canceled by the app or by the system.
/// </summary>
/// <param name="sender"></param>
/// <param name="reason"></param>
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = reason.ToString();
ApplicationData.Current.LocalSettings.Values["SampleCount"] = _sampleCount;
ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = false;
// Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration).
_deferral.Complete();
}
/// <summary>
/// Frees resources held by this background task.
/// </summary>
public void Dispose()
{
if (null != _accelerometer)
{
_accelerometer.ReadingChanged -= new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
_accelerometer.ReportInterval = 0;
}
}
/// <summary>
/// This is the event handler for acceleroemter ReadingChanged events.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
{
_sampleCount++;
// Save the sample count if the foreground app is visible.
bool appVisible = (bool)ApplicationData.Current.LocalSettings.Values["IsAppVisible"];
if (appVisible)
{
ApplicationData.Current.LocalSettings.Values["SampleCount"] = _sampleCount;
}
}
}
}
|
||||
TheStack | bd09b08f3589d323d2923399ccf3150d9eb80a66 | C#code:C# | {"size": 533, "ext": "cs", "max_stars_repo_path": "BudgetCalculator.Entities/Dtos/BudgetDto.cs", "max_stars_repo_name": "yavuzsav/BudgetCalculator", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BudgetCalculator.Entities/Dtos/BudgetDto.cs", "max_issues_repo_name": "yavuzsav/BudgetCalculator", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BudgetCalculator.Entities/Dtos/BudgetDto.cs", "max_forks_repo_name": "yavuzsav/BudgetCalculator", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.6111111111, "max_line_length": 48, "alphanum_fraction": 0.607879925} | using System;
using BudgetCalculator.Entities.Abstract;
namespace BudgetCalculator.Entities.Dtos
{
public class BudgetDto : IDto
{
public Guid Id { get; set; }
public Guid CategoryId { get; set; }
public string CategoryName { get; set; }
public int Year { get; set; }
public int Period { get; set; }
public decimal Target { get; set; }
public decimal Actual { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
} |
||||
TheStack | bd0a773b99f04d26442fc8d04f2efe5904b2057c | C#code:C# | {"size": 25832, "ext": "cs", "max_stars_repo_path": "src/back-end/CryptEx/CryptExApi/Migrations/20210619215022_Initial.Designer.cs", "max_stars_repo_name": "laurentksh/CryptEx", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/back-end/CryptEx/CryptExApi/Migrations/20210619215022_Initial.Designer.cs", "max_issues_repo_name": "laurentksh/CryptEx", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/back-end/CryptEx/CryptExApi/Migrations/20210619215022_Initial.Designer.cs", "max_forks_repo_name": "laurentksh/CryptEx", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.2300140252, "max_line_length": 125, "alphanum_fraction": 0.4464230412} | // <auto-generated />
using System;
using CryptExApi.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CryptExApi.Migrations
{
[DbContext(typeof(CryptExDbContext))]
[Migration("20210619215022_Initial")]
partial class Initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.6")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("CryptExApi.Models.Database.AppRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("CryptExApi.Models.Database.AppUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<DateTime>("BirthDay")
.HasColumnType("datetime2");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("PreferedCurrency")
.HasColumnType("nvarchar(max)");
b.Property<string>("PreferedLanguage")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("CryptExApi.Models.Database.AssetConversion", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<decimal>("Amount")
.HasPrecision(14, 2)
.HasColumnType("decimal(14,2)");
b.Property<Guid>("PriceLockId")
.HasColumnType("uniqueidentifier");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("PriceLockId")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("AssetConversions");
});
modelBuilder.Entity("CryptExApi.Models.Database.AssetConversionLock", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<decimal>("ExchangeRate")
.HasPrecision(20, 8)
.HasColumnType("decimal(20,8)");
b.Property<DateTime>("ExpirationUtc")
.HasColumnType("datetime2");
b.Property<Guid>("LeftId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("RightId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("LeftId");
b.HasIndex("RightId");
b.HasIndex("UserId");
b.ToTable("AssetConversionLocks");
});
modelBuilder.Entity("CryptExApi.Models.Database.BankAccount", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<DateTime>("DecisionDate")
.HasColumnType("datetime2");
b.Property<string>("Iban")
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("BankAccounts");
});
modelBuilder.Entity("CryptExApi.Models.Database.Country", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Iso31661Alpha2Code")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Countries");
});
modelBuilder.Entity("CryptExApi.Models.Database.CryptoDeposit", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<decimal>("Amount")
.HasPrecision(14, 2)
.HasColumnType("decimal(14,2)");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<string>("TransactionId")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("WalletId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("WalletId");
b.ToTable("CryptoDeposits");
});
modelBuilder.Entity("CryptExApi.Models.Database.FiatDeposit", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<decimal>("Amount")
.HasPrecision(14, 2)
.HasColumnType("decimal(14,2)");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<string>("StripeSessionId")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("WalletId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("WalletId");
b.ToTable("FiatDeposits");
});
modelBuilder.Entity("CryptExApi.Models.Database.FiatWithdrawal", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<decimal>("Amount")
.HasPrecision(14, 2)
.HasColumnType("decimal(14,2)");
b.Property<Guid>("BankAccountId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("WalletId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("BankAccountId");
b.HasIndex("UserId");
b.HasIndex("WalletId");
b.ToTable("FiatWithdrawals");
});
modelBuilder.Entity("CryptExApi.Models.Database.UserAddress", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("City")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("CountryId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<DateTime>("LastEditDate")
.HasColumnType("datetime2");
b.Property<string>("PostalCode")
.HasColumnType("nvarchar(max)");
b.Property<string>("Street")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("CountryId");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("UserAddresses");
});
modelBuilder.Entity("CryptExApi.Models.Database.Wallet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("FullName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Ticker")
.HasColumnType("nvarchar(max)");
b.Property<int>("Type")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Wallets");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("CryptExApi.Models.Database.AssetConversion", b =>
{
b.HasOne("CryptExApi.Models.Database.AssetConversionLock", "PriceLock")
.WithOne("Conversion")
.HasForeignKey("CryptExApi.Models.Database.AssetConversion", "PriceLockId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PriceLock");
b.Navigation("User");
});
modelBuilder.Entity("CryptExApi.Models.Database.AssetConversionLock", b =>
{
b.HasOne("CryptExApi.Models.Database.Wallet", "Left")
.WithMany()
.HasForeignKey("LeftId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.Wallet", "Right")
.WithMany()
.HasForeignKey("RightId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.Navigation("Left");
b.Navigation("Right");
b.Navigation("User");
});
modelBuilder.Entity("CryptExApi.Models.Database.BankAccount", b =>
{
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithOne("BankAccount")
.HasForeignKey("CryptExApi.Models.Database.BankAccount", "UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("CryptExApi.Models.Database.CryptoDeposit", b =>
{
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.Wallet", "Wallet")
.WithMany()
.HasForeignKey("WalletId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("Wallet");
});
modelBuilder.Entity("CryptExApi.Models.Database.FiatDeposit", b =>
{
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.Wallet", "Wallet")
.WithMany()
.HasForeignKey("WalletId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("Wallet");
});
modelBuilder.Entity("CryptExApi.Models.Database.FiatWithdrawal", b =>
{
b.HasOne("CryptExApi.Models.Database.BankAccount", "BankAccount")
.WithMany()
.HasForeignKey("BankAccountId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.Wallet", "Wallet")
.WithMany()
.HasForeignKey("WalletId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("BankAccount");
b.Navigation("User");
b.Navigation("Wallet");
});
modelBuilder.Entity("CryptExApi.Models.Database.UserAddress", b =>
{
b.HasOne("CryptExApi.Models.Database.Country", "Country")
.WithMany()
.HasForeignKey("CountryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.AppUser", "User")
.WithOne("Address")
.HasForeignKey("CryptExApi.Models.Database.UserAddress", "UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Country");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("CryptExApi.Models.Database.AppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("CryptExApi.Models.Database.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("CryptExApi.Models.Database.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("CryptExApi.Models.Database.AppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CryptExApi.Models.Database.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("CryptExApi.Models.Database.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("CryptExApi.Models.Database.AppUser", b =>
{
b.Navigation("Address");
b.Navigation("BankAccount");
});
modelBuilder.Entity("CryptExApi.Models.Database.AssetConversionLock", b =>
{
b.Navigation("Conversion");
});
#pragma warning restore 612, 618
}
}
}
|
||||
TheStack | bd0a79d211af526aa0f79428335d645f133df22a | C#code:C# | {"size": 952, "ext": "cs", "max_stars_repo_path": "src/GitVersion.Core/BuildAgents/BuildServerModule.cs", "max_stars_repo_name": "scphantm/GitVersion", "max_stars_repo_stars_event_min_datetime": "2015-06-22T16:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:24:06.000Z", "max_issues_repo_path": "src/GitVersion.Core/BuildAgents/BuildServerModule.cs", "max_issues_repo_name": "scphantm/GitVersion", "max_issues_repo_issues_event_min_datetime": "2015-06-24T17:58:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:24:51.000Z", "max_forks_repo_path": "src/GitVersion.Core/BuildAgents/BuildServerModule.cs", "max_forks_repo_name": "scphantm/GitVersion", "max_forks_repo_forks_event_min_datetime": "2015-06-26T16:56:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:04:48.000Z"} | {"max_stars_count": 2111.0, "max_issues_count": 2293.0, "max_forks_count": 750.0, "avg_line_length": 43.2727272727, "max_line_length": 169, "alphanum_fraction": 0.75} | using Microsoft.Extensions.DependencyInjection;
namespace GitVersion.BuildAgents;
public class BuildServerModule : GitVersionModule
{
public override void RegisterTypes(IServiceCollection services)
{
var buildAgents = FindAllDerivedTypes<BuildAgentBase>(Assembly.GetAssembly(GetType()));
foreach (var buildAgent in buildAgents)
{
services.AddSingleton(typeof(IBuildAgent), buildAgent);
}
services.AddSingleton<IBuildAgentResolver, BuildAgentResolver>();
#pragma warning disable CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
services.AddSingleton(sp => sp.GetService<IBuildAgentResolver>()?.Resolve());
#pragma warning restore CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
}
}
|
||||
TheStack | bd0b086a878f532e1795eb97797acb2d21988558 | C#code:C# | {"size": 569, "ext": "cs", "max_stars_repo_path": "DomainModels/Address.cs", "max_stars_repo_name": "dotnet-labs/BuilderPattern-Moq-UnitTests", "max_stars_repo_stars_event_min_datetime": "2021-04-15T14:11:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-15T14:11:40.000Z", "max_issues_repo_path": "DomainModels/Address.cs", "max_issues_repo_name": "dotnet-labs/BuilderPatter-Moq-UnitTests", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DomainModels/Address.cs", "max_forks_repo_name": "dotnet-labs/BuilderPatter-Moq-UnitTests", "max_forks_repo_forks_event_min_datetime": "2021-04-16T21:25:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T04:18:16.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 24.7391304348, "max_line_length": 89, "alphanum_fraction": 0.5202108963} | namespace DomainModels
{
public class Address
{
public string Street { get; private set; }
public string City { get; private set; }
public string State { get; private set; }
public string ZipCode { get; private set; }
protected Address()
{
ZipCode = "00000";
}
public Address(string street, string city, string state, string zipCode) : this()
{
Street = street;
City = city;
State = state;
ZipCode = zipCode;
}
}
}
|
||||
TheStack | bd0b79ef3a266e12e50db99e5c5a435b4128573a | C#code:C# | {"size": 365, "ext": "cs", "max_stars_repo_path": "src/Spk.UnhandledExceptionHandlerCore/src/Constants/UnwantedInvalidOperationExceptions.cs", "max_stars_repo_name": "spektrummedia/unhandled-exception-handler", "max_stars_repo_stars_event_min_datetime": "2018-02-13T16:31:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-13T16:31:48.000Z", "max_issues_repo_path": "src/Spk.UnhandledExceptionHandlerCore/src/Constants/UnwantedInvalidOperationExceptions.cs", "max_issues_repo_name": "spektrummedia/unhandled-exception-handler", "max_issues_repo_issues_event_min_datetime": "2018-02-13T16:38:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-02T14:49:04.000Z", "max_forks_repo_path": "src/Spk.UnhandledExceptionHandlerCore/src/Constants/UnwantedInvalidOperationExceptions.cs", "max_forks_repo_name": "spektrumgeeks/unhandled-exception-handler", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": 8.0, "max_forks_count": null, "avg_line_length": 30.4166666667, "max_line_length": 113, "alphanum_fraction": 0.701369863} | using System.Collections.Generic;
namespace Spk.UnhandledExceptionHandlerCore
{
internal partial class Constants
{
public static readonly List<string> UnwantedInvalidOperationExceptions = new List<string>
{
"the requested resource can only be accessed via ssl" // SSL website accessed by bot not handling SSL
};
}
} |
||||
TheStack | bd0eaac17f5a7ac9cd542aab946b6bfc728f9743 | C#code:C# | {"size": 2445, "ext": "cs", "max_stars_repo_path": "Libs/GizmoFort.Connector.ERPNext/ERPTypes/Bank_clearance_detail/ERPBank_clearance_detail.cs", "max_stars_repo_name": "dmequus/gizmofort.connector.erpnext", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Libs/GizmoFort.Connector.ERPNext/ERPTypes/Bank_clearance_detail/ERPBank_clearance_detail.cs", "max_issues_repo_name": "dmequus/gizmofort.connector.erpnext", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Libs/GizmoFort.Connector.ERPNext/ERPTypes/Bank_clearance_detail/ERPBank_clearance_detail.cs", "max_forks_repo_name": "dmequus/gizmofort.connector.erpnext", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.1071428571, "max_line_length": 218, "alphanum_fraction": 0.5844580777} | using GizmoFort.Connector.ERPNext.PublicTypes;
using GizmoFort.Connector.ERPNext.WrapperTypes;
using System.ComponentModel;
namespace GizmoFort.Connector.ERPNext.ERPTypes.Bank_clearance_detail
{
public class ERPBank_clearance_detail : ERPNextObjectBase
{
public ERPBank_clearance_detail() : this(new ERPObject(DocType.Bank_clearance_detail)) { }
public ERPBank_clearance_detail(ERPObject obj) : base(obj) { }
public static ERPBank_clearance_detail Create(string paymentdocument, string paymententry, string againstaccount, string amount, string postingdate, string chequenumber, string chequedate, string clearancedate)
{
ERPBank_clearance_detail obj = new ERPBank_clearance_detail();
obj.payment_document = paymentdocument;
obj.payment_entry = paymententry;
obj.against_account = againstaccount;
obj.amount = amount;
obj.posting_date = postingdate;
obj.cheque_number = chequenumber;
obj.cheque_date = chequedate;
obj.clearance_date = clearancedate;
return obj;
}
public string payment_document
{
get { return data.payment_document; }
set
{
data.payment_document = value;
data.name = value;
}
}
public string payment_entry
{
get { return data.payment_entry; }
set { data.payment_entry = value; }
}
public string against_account
{
get { return data.against_account; }
set { data.against_account = value; }
}
public string amount
{
get { return data.amount; }
set { data.amount = value; }
}
public string posting_date
{
get { return data.posting_date; }
set { data.posting_date = value; }
}
public string cheque_number
{
get { return data.cheque_number; }
set { data.cheque_number = value; }
}
public string cheque_date
{
get { return data.cheque_date; }
set { data.cheque_date = value; }
}
public string clearance_date
{
get { return data.clearance_date; }
set { data.clearance_date = value; }
}
}
//Enums go here
} |
||||
TheStack | bd0ecf88704a76a4eab0b7c11110de8a0178303a | C#code:C# | {"size": 617, "ext": "cs", "max_stars_repo_path": "src/Uno.UWP/Generated/3.0.0.0/Windows.Graphics.Effects/IGraphicsEffect.cs", "max_stars_repo_name": "AlexTrepanier/Uno", "max_stars_repo_stars_event_min_datetime": "2020-03-24T01:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T13:23:33.000Z", "max_issues_repo_path": "src/Uno.UWP/Generated/3.0.0.0/Windows.Graphics.Effects/IGraphicsEffect.cs", "max_issues_repo_name": "billchungiii/Uno", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Uno.UWP/Generated/3.0.0.0/Windows.Graphics.Effects/IGraphicsEffect.cs", "max_forks_repo_name": "billchungiii/Uno", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.380952381, "max_line_length": 99, "alphanum_fraction": 0.7455429498} | #pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Graphics.Effects
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial interface IGraphicsEffect : global::Windows.Graphics.Effects.IGraphicsEffectSource
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
string Name
{
get;
set;
}
#endif
// Forced skipping of method Windows.Graphics.Effects.IGraphicsEffect.Name.get
// Forced skipping of method Windows.Graphics.Effects.IGraphicsEffect.Name.set
}
}
|
||||
TheStack | bd1007db54683a1d745de7ff8b2e22342cd1e451 | C#code:C# | {"size": 164, "ext": "cs", "max_stars_repo_path": "src/FlowStoreBackend/FlowStoreBackend.Logic/Models/Product/CreateProductModel.cs", "max_stars_repo_name": "DenisPolukhin/FlowerStore", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FlowStoreBackend/FlowStoreBackend.Logic/Models/Product/CreateProductModel.cs", "max_issues_repo_name": "DenisPolukhin/FlowerStore", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FlowStoreBackend/FlowStoreBackend.Logic/Models/Product/CreateProductModel.cs", "max_forks_repo_name": "DenisPolukhin/FlowerStore", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.3333333333, "max_line_length": 69, "alphanum_fraction": 0.7682926829} | namespace FlowStoreBackend.Logic.Models.Product
{
public record CreateProductModel(string Name, string Description,
Guid CategoryId, decimal Price);
}
|
||||
TheStack | bd1091d8a39adc1db88c5c0d60ca3ebd127f3eaf | C#code:C# | {"size": 296, "ext": "cs", "max_stars_repo_path": "Master/ASTRA.EMSG.Business/Reports/MengeProBelastungskategorie/MengeProBelastungskategorieParameter.cs", "max_stars_repo_name": "astra-emsg/ASTRA.EMSG", "max_stars_repo_stars_event_min_datetime": "2017-09-07T08:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T02:29:23.000Z", "max_issues_repo_path": "Master/ASTRA.EMSG.Business/Reports/MengeProBelastungskategorie/MengeProBelastungskategorieParameter.cs", "max_issues_repo_name": "astra-emsg/ASTRA.EMSG", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Master/ASTRA.EMSG.Business/Reports/MengeProBelastungskategorie/MengeProBelastungskategorieParameter.cs", "max_forks_repo_name": "astra-emsg/ASTRA.EMSG", "max_forks_repo_forks_event_min_datetime": "2017-09-20T07:07:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T14:27:07.000Z"} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 29.6, "max_line_length": 88, "alphanum_fraction": 0.7837837838} | using ASTRA.EMSG.Business.Reporting;
using ASTRA.EMSG.Common.Enums;
namespace ASTRA.EMSG.Business.Reports.MengeProBelastungskategorie
{
public class MengeProBelastungskategorieParameter : EmsgTabellarischeReportParameter
{
public EigentuemerTyp? Eigentuemer { get; set; }
}
} |
||||
TheStack | bd114dc7f1ea6b2a15f16596d335f2c551062fb0 | C#code:C# | {"size": 3392, "ext": "cs", "max_stars_repo_path": "AzureDreamsDamageCalculator/StatsCalculator.cs", "max_stars_repo_name": "czajowaty/ad_damage_calculator", "max_stars_repo_stars_event_min_datetime": "2021-01-11T17:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T17:24:30.000Z", "max_issues_repo_path": "AzureDreamsDamageCalculator/StatsCalculator.cs", "max_issues_repo_name": "czajowaty/ad_damage_calculator", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AzureDreamsDamageCalculator/StatsCalculator.cs", "max_forks_repo_name": "czajowaty/ad_damage_calculator", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 49.8823529412, "max_line_length": 148, "alphanum_fraction": 0.59375} | using System;
namespace AzureDreamsDamageCalculator
{
public class StatsCalculator
{
public static readonly uint ATK_DEF_DIVISOR = 64u;
public static readonly uint MP_LUCK_DIVISOR = 1024u;
public static readonly uint MAX_STAT = 255u;
public static uint Attack(UnitTraits traits, uint level, bool doubleStat)
{ return CalculateStat(ref traits, level, traits.BaseAttack, traits.AttackGrowth, ATK_DEF_DIVISOR, doubleStat); }
public static uint Defense(UnitTraits traits, uint level, bool doubleStat)
{ return CalculateStat(ref traits, level, traits.BaseDefense, traits.DefenseGrowth, ATK_DEF_DIVISOR, doubleStat); }
public static uint HP(UnitTraits traits, uint level, bool doubleStat)
{
uint calculatedHp;
if (traits.IsEvolved)
{
calculatedHp = traits.BaseHp;
for (uint n = 1; n < level; ++n)
{
calculatedHp = calculatedHp +
(uint)(
Math.Floor(traits.HpGrowth * n / 16.0f) -
Math.Floor(traits.HpGrowth * (n - 1) / 16.0f) +
Math.Floor(2896 * traits.HpGrowth * Math.Sqrt(traits.HpGrowth * n) / 32768.0f) -
Math.Floor(2896 * traits.HpGrowth * Math.Sqrt(traits.HpGrowth * (n - 1)) / 32768.0f)
);
}
}
else
{
calculatedHp = traits.BaseHp +
(uint)Math.Floor(traits.HpGrowth * (level - 1) / 16.0f) +
(uint)Math.Floor(2896 * traits.HpGrowth * Math.Sqrt(traits.HpGrowth * (level - 1)) / 32768);
}
return CappedStat(calculatedHp, doubleStat);
}
public static uint MP(UnitTraits traits, uint level)
{ return CalculateStat(ref traits, level, traits.BaseMp, traits.MpGrowth, MP_LUCK_DIVISOR, false); }
private static uint CalculateStat(ref UnitTraits traits, uint level, uint baseStat, uint statGrowth, uint statDivisor, bool doubleStat)
{
uint stat = traits.IsEvolved ?
CalculateEvolvedStat(level, baseStat, statGrowth, statDivisor) :
CalculateNonEvolvedStat(level, baseStat, statGrowth, statDivisor);
return CappedStat(stat, doubleStat);
}
private static uint CalculateNonEvolvedStat(uint level, uint baseStat, uint statGrowth, uint statDivisor)
{ return baseStat + HelperCalculation(baseStat, statGrowth, level - 1, statDivisor); }
private static uint CalculateEvolvedStat(uint level, uint baseStat, uint statGrowth, uint statDivisor)
{
uint stat = baseStat;
for (uint n = 1; n < level; ++n)
{ stat = stat + HelperCalculation(baseStat, statGrowth, n, statDivisor) - HelperCalculation(baseStat, statGrowth, n - 1, statDivisor); }
return stat;
}
private static uint HelperCalculation(uint baseStat, uint statGrowth, uint n, uint statDivisor)
{ return (uint)Math.Floor((double)((baseStat * statGrowth * n) / statDivisor)); }
private static uint CappedStat(uint stat, bool doubleStat)
{
if (doubleStat)
{ stat *= 2; }
return Math.Min(stat, MAX_STAT);
}
}
}
|
||||
TheStack | bd117ded42ab7b144715508aab4a5f3fcb673b7f | C#code:C# | {"size": 1027, "ext": "cs", "max_stars_repo_path": "src/Silverpop.Core/XML/SendMailingEncoder.cs", "max_stars_repo_name": "cmelgarejo/silverpop-dotnet-api", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Silverpop.Core/XML/SendMailingEncoder.cs", "max_issues_repo_name": "cmelgarejo/silverpop-dotnet-api", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Silverpop.Core/XML/SendMailingEncoder.cs", "max_forks_repo_name": "cmelgarejo/silverpop-dotnet-api", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.1212121212, "max_line_length": 94, "alphanum_fraction": 0.6075949367} | using System;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace Silverpop.Core.XML
{
public class SendMailingEncoder
{
public virtual string Encode(SendMailing sendMailing)
{
if (sendMailing == null) throw new ArgumentNullException("sendMailing");
var xml = new XElement(XName.Get("Envelope"));
var bodyXml = new XElement(XName.Get("Body"));
var loginXml = new XElement(XName.Get("SendMailing"));
loginXml.SetElementValue(XName.Get("MailingId"), sendMailing.MailingId);
loginXml.SetElementValue(XName.Get("RecipientEmail"), sendMailing.RecipientEmail);
bodyXml.Add(loginXml);
xml.Add(bodyXml);
return xml.ToString();
}
private static bool ContainsCDATASection(string str)
{
if (string.IsNullOrWhiteSpace(str))
return false;
return Regex.Match(str, @"<!\[CDATA\[(.|\n|\r)*]]>").Success;
}
}
} |
||||
TheStack | bd14763690c73b10fcd6dc2329a6106313d481e1 | C#code:C# | {"size": 6599, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/GameObjects/AmazingTrack.cs", "max_stars_repo_name": "EugenyN/AmazingTrack", "max_stars_repo_stars_event_min_datetime": "2019-10-19T02:41:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T05:50:01.000Z", "max_issues_repo_path": "Assets/Scripts/GameObjects/AmazingTrack.cs", "max_issues_repo_name": "EugenyN/AmazingTrack", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/GameObjects/AmazingTrack.cs", "max_forks_repo_name": "EugenyN/AmazingTrack", "max_forks_repo_forks_event_min_datetime": "2020-03-11T21:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T06:17:35.000Z"} | {"max_stars_count": 7.0, "max_issues_count": null, "max_forks_count": 4.0, "avg_line_length": 33.3282828283, "max_line_length": 106, "alphanum_fraction": 0.5993332323} | // Copyright 2019 Eugeny Novikov. Code under MIT license.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using Zenject;
namespace AmazingTrack
{
/// <summary>
/// AmazingTrack
///
/// Encapsulates the behavior of the entire track: rules of creation
/// and fall/removing blocks and crystals on the track.
///
/// uses ObjectSpawner to create and delete (place in a pool) game objects
/// </summary>
public class AmazingTrack : MonoBehaviour
{
private const int BlocksOnScreen = 30;
private const float BallSpawnHeight = 0.75f;
private const float FallTimeBeforeDead = 2.0f;
private ObjectSpawner spawner;
private SignalBus signalBus;
private Vector3 lastSpawnPos = new Vector3(0f, 0f, 0f);
private Queue<GameObject> liveBlocksQueue = new Queue<GameObject>();
private CrystalSpawnStrategy crystalSpawnStrategy;
private BlockHolesStrategy blockHolesStrategy;
public bool RandomCrystals = false;
public bool MakeHoles = false;
public int BlocksInGroup = 1;
public Ball Ball { get; private set; }
private CrystalSpawnStrategy GetCrystalSpawnStrategy()
{
if (crystalSpawnStrategy == null)
{
if (RandomCrystals)
crystalSpawnStrategy = new RandomCrystalSpawnStrategy();
else
crystalSpawnStrategy = new ProgressiveCrystalSpawnStrategy();
}
return crystalSpawnStrategy;
}
private BlockHolesStrategy GetBlockHolesStrategy()
{
if (blockHolesStrategy == null)
blockHolesStrategy = new BlockHolesStrategy();
return blockHolesStrategy;
}
[Inject]
public void Construct(SignalBus signalBus, ObjectSpawner spawner)
{
this.signalBus = signalBus;
this.spawner = spawner;
signalBus.Subscribe<BallMovedToNextBlockSignal>(OnBallMovedToNextBlock);
signalBus.Subscribe<BallHitCrystalSignal>(OnBallHitCrystal);
}
public void CreateObjects(bool randomCrystals, bool makeHoles, int blocksInGroup, float ballSpeed)
{
RandomCrystals = randomCrystals;
MakeHoles = makeHoles;
BlocksInGroup = blocksInGroup;
GameObject startPlatform = spawner.SpawnStartPlatform(Color.gray);
liveBlocksQueue.Enqueue(startPlatform);
lastSpawnPos = new Vector3(1f, 0f, 1f);
for (int i = 0; i < BlocksOnScreen; i++)
SpawnNextBlocks();
var ballObj = spawner.SpawnBall(new Vector3(0, BallSpawnHeight, 0));
Ball = ballObj.GetComponent<Ball>();
Ball.Speed = ballSpeed;
}
public void DestroyObjects()
{
StopAllCoroutines();
if (Ball != null)
DestroyImmediate(Ball.gameObject);
liveBlocksQueue.Clear();
spawner.Clear();
crystalSpawnStrategy = null;
}
void SpawnNextBlocks()
{
bool rightDirection = Random.Range(0, 2) == 0;
lastSpawnPos += rightDirection ? Vector3.right : Vector3.forward;
Color color = new Color(Random.value, Random.value, Random.value, 1.0f);
GameObject group = SpawnBlocksGroupWithCrystalAndHole(lastSpawnPos, rightDirection, color);
liveBlocksQueue.Enqueue(group);
}
GameObject SpawnBlocksGroupWithCrystalAndHole(Vector3 spawnPos, bool rightSide, Color color)
{
var group = spawner.SpawnBlocksGroup(BlocksInGroup, spawnPos, rightSide, color);
GameObject groupObj = group.gameObject;
if (MakeHoles)
{
Assert.IsTrue(groupObj.transform.childCount == 3);
if (GetBlockHolesStrategy().IsTimeToHole())
groupObj.GetComponent<BlocksGroup>().MakeHole();
}
if (GetCrystalSpawnStrategy().ShouldSpawn())
{
var child = groupObj.transform.GetChild(Random.Range(0, BlocksInGroup - 1));
if (child.gameObject.activeSelf)
spawner.SpawnOrResetCrystal(child);
}
return groupObj;
}
private void OnBallHitCrystal(BallHitCrystalSignal signal)
{
signal.Crystal.GetComponent<Crystal>().Take();
spawner.DespawnCrystal(signal.Crystal);
}
private void OnBallMovedToNextBlock(BallMovedToNextBlockSignal signal)
{
if (signal.PreviousBlock == null)
return;
bool isSameGroup = signal.Block.IsSiblingObject(signal.PreviousBlock);
if (!isSameGroup)
OnMovedToBlockInNewGroup(signal.Block, signal.PreviousBlock);
}
private void OnMovedToBlockInNewGroup(GameObject block, GameObject previousBlock)
{
var previousBlockGroup = previousBlock.ParentObject();
if (block.GetComponent<Block>().Falling)
return; // ignore falling blocks
if (previousBlock.GetComponent<Block>().Falling)
return; // ignore falling blocks
Assert.IsTrue(liveBlocksQueue.Contains(previousBlockGroup));
GameObject blockGroup = null;
while (blockGroup != previousBlockGroup)
{
blockGroup = liveBlocksQueue.Dequeue();
StartCoroutine(FallDownBlocks(blockGroup));
SpawnNextBlocks();
}
}
private IEnumerator FallDownBlocks(GameObject blockGroup)
{
foreach (Transform child in blockGroup.transform)
{
var block = child.gameObject.GetComponent<Block>();
if (child.gameObject.activeSelf)
{
block.FallDown();
if (block.HasCrystal())
StartCoroutine(FallDownCrystal(block.GetCrystal()));
}
}
yield return new WaitForSeconds(FallTimeBeforeDead);
spawner.DespawnBlocksGroup(blockGroup);
}
private IEnumerator FallDownCrystal(GameObject crystal)
{
crystal.GetComponent<Crystal>().FallDown();
yield return new WaitForSeconds(FallTimeBeforeDead);
spawner.DespawnCrystal(crystal);
}
}
} |
||||
TheStack | bd15346085380f172ac3f9d9891f04670bace1a8 | C#code:C# | {"size": 481, "ext": "cs", "max_stars_repo_path": "MyGame/Assets/Scripts/OntoLvl3.cs", "max_stars_repo_name": "AsharNaveed/Unity-3D", "max_stars_repo_stars_event_min_datetime": "2020-11-13T16:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T16:12:26.000Z", "max_issues_repo_path": "MyGame/Assets/Scripts/OntoLvl3.cs", "max_issues_repo_name": "AsharNaveed/Unity-3D", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyGame/Assets/Scripts/OntoLvl3.cs", "max_forks_repo_name": "AsharNaveed/Unity-3D", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 16.5862068966, "max_line_length": 60, "alphanum_fraction": 0.656964657} | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class OntoLvl3: MonoBehaviour
{
public GameObject cube2;
void Start()
{
cube2.SetActive(true);
}
void Update()
{
}
void OnTriggerEnter()
{
cube2.SetActive(false);
#pragma warning disable CS0618 // Type or member is obsolete
Application.LoadLevel("Level 3");
#pragma warning restore CS0618 // Type or member is obsolete
}
}
|
||||
TheStack | bd16381ec7514616f63349ea16e4a2f9a44dd759 | C#code:C# | {"size": 2434, "ext": "cs", "max_stars_repo_path": "src/Application/Actions/ServiceConnection/Command/Remove/ServiceConnectionRemoveAction.cs", "max_stars_repo_name": "PoolPirate/WeShare", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Application/Actions/ServiceConnection/Command/Remove/ServiceConnectionRemoveAction.cs", "max_issues_repo_name": "PoolPirate/WeShare", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Application/Actions/ServiceConnection/Command/Remove/ServiceConnectionRemoveAction.cs", "max_forks_repo_name": "PoolPirate/WeShare", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.4533333333, "max_line_length": 134, "alphanum_fraction": 0.6598192276} | using MediatR;
using Microsoft.EntityFrameworkCore;
using WeShare.Application.Common;
using WeShare.Application.Common.Exceptions;
using WeShare.Application.Services;
using WeShare.Domain.Entities;
namespace WeShare.Application.Actions.Commands;
public class ServiceConnectionRemoveAction
{
public class Command : IRequest<Result>
{
public UserId UserId { get; }
public ServiceConnectionId ServiceConnectionId { get; }
public Command(UserId userId, ServiceConnectionId serviceConnectionId)
{
UserId = userId;
ServiceConnectionId = serviceConnectionId;
}
}
public enum Status : byte
{
Success,
UserNotFound,
ServiceConnectionNotFound,
}
public record Result(Status Status);
public class Handler : IRequestHandler<Command, Result>
{
private readonly IShareContext DbContext;
private readonly IAuthorizer Authorizer;
public Handler(IShareContext dbContext, IAuthorizer authorizer)
{
DbContext = dbContext;
Authorizer = authorizer;
}
public async Task<Result> Handle(Command request, CancellationToken cancellationToken)
{
if (!await DbContext.Users.AnyAsync(x => x.Id == request.UserId, cancellationToken: cancellationToken))
{
return new Result(Status.UserNotFound);
}
var serviceConnection = await DbContext.ServiceConnections
.Where(x => x.Id == request.ServiceConnectionId)
.SingleOrDefaultAsync(cancellationToken);
if (serviceConnection is null)
{
return new Result(Status.ServiceConnectionNotFound);
}
await Authorizer.EnsureAuthorizationAsync(serviceConnection, ServiceConnectionCommandOperation.Remove, cancellationToken);
DbContext.ServiceConnections.Remove(serviceConnection);
var saveResult = await DbContext.SaveChangesAsync(DbStatus.ConcurrencyEntryDeleted, cancellationToken: cancellationToken);
return saveResult.Status switch
{
DbStatus.Success => new Result(Status.Success),
DbStatus.ConcurrencyEntryDeleted => new Result(Status.ServiceConnectionNotFound),
_ => throw new UnhandledDbStatusException(saveResult),
};
}
}
}
|
||||
TheStack | bd166d10ee31f9c52708225dec43e0bf2033b66d | C#code:C# | {"size": 551, "ext": "cs", "max_stars_repo_path": "Source/StandardUtils/Models/Requests/BaseAuthenticatedPagedRequest.cs", "max_stars_repo_name": "Enisbeygorus/standard-utils", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/StandardUtils/Models/Requests/BaseAuthenticatedPagedRequest.cs", "max_issues_repo_name": "Enisbeygorus/standard-utils", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/StandardUtils/Models/Requests/BaseAuthenticatedPagedRequest.cs", "max_forks_repo_name": "Enisbeygorus/standard-utils", "max_forks_repo_forks_event_min_datetime": "2019-11-16T15:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T05:19:52.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 29.0, "max_line_length": 89, "alphanum_fraction": 0.6370235935} | using StandardUtils.Models.Shared;
namespace StandardUtils.Models.Requests
{
public abstract class BaseAuthenticatedPagedRequest : BaseAuthenticatedRequest
{
/// <summary>
/// if skip is greater than 0
/// service does not checks for LastUid,
/// To use last uid ensure Skip is 0
/// </summary>
public PagingInfo PagingInfo { get; }
protected BaseAuthenticatedPagedRequest(long currentUserId) : base(currentUserId)
{
PagingInfo = new PagingInfo();
}
}
} |
||||
TheStack | bd1789f04f5e892fb9414770028d1b3501da5290 | C#code:C# | {"size": 9128, "ext": "cs", "max_stars_repo_path": "utils/ModifyTool/FakeProviderSyntaxRewriter.cs", "max_stars_repo_name": "LogoFX/Samples.Cli", "max_stars_repo_stars_event_min_datetime": "2020-05-06T04:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T06:29:31.000Z", "max_issues_repo_path": "utils/ModifyTool/FakeProviderSyntaxRewriter.cs", "max_issues_repo_name": "LogoFX/cli-dotnet", "max_issues_repo_issues_event_min_datetime": "2020-05-01T08:43:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T00:28:10.000Z", "max_forks_repo_path": "utils/ModifyTool/FakeProviderSyntaxRewriter.cs", "max_forks_repo_name": "LogoFX/Samples.Cli", "max_forks_repo_forks_event_min_datetime": "2020-05-05T17:14:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T17:14:28.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 75.0, "max_forks_count": 1.0, "avg_line_length": 46.3350253807, "max_line_length": 207, "alphanum_fraction": 0.657427695} | using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ModifyTool
{
internal sealed partial class FakeProviderSyntaxRewriter : CSharpSyntaxRewriter
{
private const string ModuleClassName = "Module";
private const string RegisterModuleMethodName = "RegisterModule";
private const string CreateBuilderMethodName = "CreateBuilder";
private const string RegisterInstanceName = "RegisterInstance";
private const string AddSingletonName = "AddSingleton";
private const string AddInstanceName = "AddInstance";
private readonly string _containerContract;
private readonly string _containerType;
private readonly string _containerName;
private readonly string _dtoName;
private readonly string _initializeContainerMethodName;
private readonly string _providerBuilderName;
private readonly string _providerContractName;
private readonly string _fakeProviderName;
private string _checkingMethod;
public FakeProviderSyntaxRewriter(string entityName)
{
_containerContract = $"I{entityName}DataContainer";
_containerType = $"{entityName}DataContainer";
_containerName = "container";
_dtoName = $"{entityName}Dto";
_initializeContainerMethodName = $"Initialize{entityName}Container";
_providerBuilderName = $"{entityName}ProviderBuilder";
_providerContractName = $"I{entityName}DataProvider";
_fakeProviderName = $"Fake{entityName}DataProvider";
}
public bool NormalizeWhitespaceOnly { get; set; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (!NormalizeWhitespaceOnly && node.Identifier.Text == ModuleClassName)
{
var newClass = AddContainerInitializationMethod(node);
if (newClass == null)
return node;
node = newClass;
}
return base.VisitClassDeclaration(node);
}
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
_checkingMethod = node.Identifier.Text;
if (_checkingMethod == RegisterModuleMethodName)
{
node = NormalizeWhitespaceOnly ? SyntaxHelper.NormalizeWhitespace(node) :
RewriteRegisterModuleMethod(node);
}
var result = base.VisitMethodDeclaration(node);
_checkingMethod = null;
return result;
}
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
private MethodDeclarationSyntax RewriteRegisterModuleMethod(MethodDeclarationSyntax method)
{
var dependencyRegistratorParam = method.ParameterList.ChildNodes().OfType<ParameterSyntax>().First();
var body = method.Body;
var stList = CreateRegistrationStatement(body.Statements, dependencyRegistratorParam.Identifier.Text);
body = body.WithStatements(stList);
method = method.WithBody(body);
return method;
}
private SyntaxList<StatementSyntax> CreateRegistrationStatement(SyntaxList<StatementSyntax> statements,
string registratorIdentifier)
{
statements = statements.Add(
SyntaxFactory.ExpressionStatement(SyntaxHelper.ToInvocationExpression(
SyntaxHelper.ToMemberAccessExpression(SyntaxHelper.ToInvocationExpression(
SyntaxHelper.ToMemberAccessExpression(registratorIdentifier, AddInstanceName), SyntaxHelper.ArgumentList(SyntaxHelper.ToInvocationExpression(_initializeContainerMethodName))),
SyntaxHelper.ToGenericName(AddSingletonName, _providerContractName, _fakeProviderName)))));
statements = statements.Add(
SyntaxFactory.ExpressionStatement(SyntaxHelper.ToInvocationExpression(
SyntaxHelper.ToMemberAccessExpression(registratorIdentifier, RegisterInstanceName), SyntaxHelper.ArgumentList(SyntaxHelper.ToInvocationExpression(
SyntaxHelper.ToMemberAccessExpression(_providerBuilderName, CreateBuilderMethodName))))));
return statements;
}
public override SyntaxNode VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node)
{
if (NormalizeWhitespaceOnly && _checkingMethod != RegisterInstanceName)
{
var closeBracket = node.CloseBracketToken.WithTrailingTrivia(SyntaxHelper.EndOfLineTrivia);
node = node.WithCloseBracketToken(closeBracket);
node = node.WithInitializer(RewriteInitializer(node.Initializer));
}
return base.VisitImplicitArrayCreationExpression(node);
}
public override SyntaxNode VisitInitializerExpression(InitializerExpressionSyntax node)
{
if (NormalizeWhitespaceOnly &&
node.IsKind(SyntaxKind.ArrayInitializerExpression) &&
_checkingMethod != RegisterInstanceName)
{
var openBrace = node.OpenBraceToken.WithLeadingTrivia(SyntaxHelper.Whitespace(12));
node = node.WithOpenBraceToken(openBrace);
var closeBrace = node.CloseBraceToken.WithLeadingTrivia(SyntaxHelper.EndOfLineTrivia, SyntaxHelper.Whitespace(12));
node = node.WithCloseBraceToken(closeBrace);
}
return base.VisitInitializerExpression(node!);
}
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
if (NormalizeWhitespaceOnly &&
node.Parent is InitializerExpressionSyntax initializerExpression &&
initializerExpression.IsKind(SyntaxKind.ArrayInitializerExpression) &&
_checkingMethod != RegisterInstanceName)
{
var newKeyword = node.NewKeyword
.WithLeadingTrivia(SyntaxHelper.EndOfLineTrivia, SyntaxHelper.Whitespace(16))
.WithTrailingTrivia(SyntaxHelper.Whitespace(1));
node = node.WithNewKeyword(newKeyword);
var type = (IdentifierNameSyntax) node.Type;
var identifier = type.Identifier.WithTrailingTrivia(SyntaxHelper.EndOfLineTrivia);
type = type.WithIdentifier(identifier);
node = node.WithType(type);
var initializer = RewriteInitializer(node.Initializer);
var openBrace = initializer.OpenBraceToken
.WithLeadingTrivia(SyntaxHelper.Whitespace(16))
.WithTrailingTrivia(SyntaxHelper.EndOfLineTrivia);
var closeBrace = initializer.CloseBraceToken
.WithLeadingTrivia(SyntaxHelper.EndOfLineTrivia, SyntaxHelper.Whitespace(16));
initializer = initializer.WithOpenBraceToken(openBrace).WithCloseBraceToken(closeBrace);
node = node.WithInitializer(initializer);
}
return base.VisitObjectCreationExpression(node);
}
private InitializerExpressionSyntax RewriteInitializer(InitializerExpressionSyntax initializer)
{
var expressions = new List<ExpressionSyntax>();
foreach (var expression in initializer.Expressions)
{
var expr = expression.WithLeadingTrivia(SyntaxHelper.Whitespace(20));
expressions.Add(expr);
}
initializer = initializer.WithExpressions(
SyntaxFactory.SeparatedList(
expressions,
Enumerable.Repeat(
SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(SyntaxHelper.EndOfLineTrivia),
expressions.Count - 1)));
return initializer;
}
private ClassDeclarationSyntax AddContainerInitializationMethod(ClassDeclarationSyntax moduleClass)
{
var foundMember = moduleClass.Members
.OfType<MethodDeclarationSyntax>()
.Any(x => x.Identifier.Text == _initializeContainerMethodName);
if (foundMember)
return null;
var method = SyntaxFactory.MethodDeclaration(
SyntaxFactory.ParseTypeName(_containerContract),
_initializeContainerMethodName);
method = method.NormalizeWhitespace().AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
method = method.WithBody(CreateContainerInitializationBody());
var members = moduleClass.Members.Add(method);
moduleClass = moduleClass.WithMembers(members);
return moduleClass;
}
}
} |
||||
TheStack | bd17f87f63c313c57c0149b5b65dbdb99517e0be | C#code:C# | {"size": 7453, "ext": "cs", "max_stars_repo_path": "Polygon.ColorPicker/Polygon.ColorPicker/ViewModels/PickerViewModel.cs", "max_stars_repo_name": "Elendan/Notale-Text-Picker", "max_stars_repo_stars_event_min_datetime": "2019-07-08T18:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-14T15:09:44.000Z", "max_issues_repo_path": "Polygon.ColorPicker/Polygon.ColorPicker/ViewModels/PickerViewModel.cs", "max_issues_repo_name": "Elendan/Notale-Text-Picker", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Polygon.ColorPicker/Polygon.ColorPicker/ViewModels/PickerViewModel.cs", "max_forks_repo_name": "Elendan/Notale-Text-Picker", "max_forks_repo_forks_event_min_datetime": "2019-12-14T15:09:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-14T15:09:48.000Z"} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 31.5805084746, "max_line_length": 142, "alphanum_fraction": 0.5505165705} | using System;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using Polygon.ColorPicker.Events;
using Polygon.ColorPicker.Interfaces;
using Polygon.Models.Enums;
using Polygon.ColorPicker.Extensions;
using Polygon.Utils;
using Polygon.Utils.Extensions;
namespace Polygon.ColorPicker.ViewModels
{
public class PickerViewModel : BaseViewModel, IPageViewModel
{
#region Constructor
public PickerViewModel()
{
if (!IsAdministrator)
{
MessageBox.Show($"Please run this program as administrator");
Application.Exit();
}
this.InitializeUi();
var data = ConfigurationManager.AppSettings["LauncherPath"];
if (string.IsNullOrEmpty(data) || !File.Exists(data))
{
MessageBox.Show("Please choose your Launcher");
var dlg = new OpenFileDialog
{
Filter = EXE_FILTER
};
if (dlg.ShowDialog() != DialogResult.OK)
{
return;
}
_nostalePath = dlg.FileName;
SettingsManager.AddOrUpdateAppSettings("LauncherPath", dlg.FileName);
}
else
{
_nostalePath = data;
}
}
#endregion
#region Members
private string _oldRightClickColor => ConfigurationManager.AppSettings["CurrentRightClickColor"];
private string _oldGmColor => ConfigurationManager.AppSettings["CurrentGmColor"];
private readonly string _nostalePath = string.Empty;
private static bool IsAdministrator => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
private const string EXE_FILTER = "Executable (*.exe)|*.exe";
#endregion
#region UpdateableProperties
private string _changeRightClickColorContent;
public string ChangeRightClickColorContent
{
get => _changeRightClickColorContent;
set
{
_changeRightClickColorContent = value;
OnPropertyChanged(nameof(ChangeRightClickColorContent));
}
}
private string _changeGmTagButtonContent;
public string ChangeGmTagButtonContent
{
get => _changeGmTagButtonContent;
set
{
_changeGmTagButtonContent = value;
OnPropertyChanged(nameof(ChangeGmTagButtonContent));
}
}
private string _pickerButtonContent;
public string PickerButtonContent
{
get => _pickerButtonContent;
set
{
_pickerButtonContent = value;
OnPropertyChanged(nameof(PickerButtonContent));
}
}
private string _colorDisplayContent;
public string ColorDisplayContent
{
get => _colorDisplayContent;
set
{
_colorDisplayContent = value;
OnPropertyChanged(nameof(ColorDisplayContent));
}
}
private Brush _colorBrush;
public Brush ColorBrush
{
get => _colorBrush;
set
{
_colorBrush = value;
OnPropertyChanged(nameof(ColorBrush));
}
}
#endregion
#region ICommands
private ICommand _chooseColorCommand;
public ICommand ChooseColorCommand
{
get
{
return _chooseColorCommand ?? (_chooseColorCommand = new RelayCommand(x =>
{
var dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
ColorBrush = new SolidColorBrush(dialog.CreateColorFromDialog());
}
ColorDisplayContent = dialog.CreateColorFromDialog().ToNostaleFormat();
}));
}
}
private ICommand _changeGmTagCommand;
public ICommand ChangeGmTagCommand
{
get
{
return _changeGmTagCommand ?? (_changeGmTagCommand = new RelayCommand(x =>
{
var previous = "00FFFFFF";
UpdateInformationFromPattern("CurrentGmColor", $"{previous}{_oldGmColor}", previous.Length);
}));
}
}
private ICommand _changeRightClickColorCommand;
public ICommand ChangeRightClickColorCommand
{
get
{
return _changeRightClickColorCommand ?? (_changeRightClickColorCommand = new RelayCommand(x =>
{
var previous = "C7466F";
UpdateInformationFromPattern("CurrentRightClickColor", $"{previous}{_oldRightClickColor}", previous.Length);
}));
}
}
private ICommand _resetOptionsCommand;
public ICommand ResetOptionsCommand
{
get
{
return _resetOptionsCommand ?? (_resetOptionsCommand = new RelayCommand(x =>
{
SettingsManager.AddOrUpdateAppSettings("LauncherPath", string.Empty);
SettingsManager.AddOrUpdateAppSettings("CurrentGmColor", "FF6CBFFF");
SettingsManager.AddOrUpdateAppSettings("CurrentRightClickColor", "78C4F5FF");
MessageBox.Show("Settings have been reset. This program will close");
System.Windows.Application.Current.Shutdown();
}));
}
}
#endregion
#region Methods
private void UpdateInformationFromPattern(string appSettingKey, string pattern, int substringIndex)
{
const string backupName = "LauncherBackup";
var directory = _nostalePath.FindDirectory();
if (!Directory.Exists(directory + backupName))
{
Directory.CreateDirectory(directory + backupName);
}
var currentDirectoryTime = directory + backupName + $"\\{DateTime.Now:yyyyMdd_HHmmss}";
Directory.CreateDirectory(currentDirectoryTime);
File.Copy(_nostalePath, currentDirectoryTime + $"\\{_nostalePath.Split('\\').Last()}", true);
var hexFinder = new HexFinder(_nostalePath, ColorDisplayContent);
if (!hexFinder.ReplaceColorPattern(pattern, substringIndex))
{
MessageBox.Show("An error occurred !\nplease reset settings and/or restore a backup of your launcher !");
return;
}
SettingsManager.AddOrUpdateAppSettings(appSettingKey, ColorDisplayContent);
MessageBox.Show("Backup created, value changed successfully !");
}
#endregion
}
}
|
||||
TheStack | bd184c5a49e97fa271ee2e8ddf3546c976e1652d | C#code:C# | {"size": 1552, "ext": "cs", "max_stars_repo_path": "Monster RPG Game Kit/MonsterRPGGameKit/Assets/Monster RPG/Scripts/Engine/Ecosystem/Nodes/Creatures/TeachAbility.cs", "max_stars_repo_name": "larsolm/Archives", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Monster RPG Game Kit/MonsterRPGGameKit/Assets/Monster RPG/Scripts/Engine/Ecosystem/Nodes/Creatures/TeachAbility.cs", "max_issues_repo_name": "larsolm/Archives", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Monster RPG Game Kit/MonsterRPGGameKit/Assets/Monster RPG/Scripts/Engine/Ecosystem/Nodes/Creatures/TeachAbility.cs", "max_forks_repo_name": "larsolm/Archives", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.04, "max_line_length": 132, "alphanum_fraction": 0.7577319588} | using PiRhoSoft.CompositionEngine;
using PiRhoSoft.UtilityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PiRhoSoft.MonsterRpgEngine
{
[CreateInstructionGraphNodeMenu("Ecosystem/Teach Ability", 21)]
[HelpURL(MonsterRpg.DocumentationUrl + "teach-ability")]
public class TeachAbility : InstructionGraphNode
{
private const string _invalidVariablesWarning = "(ETAIV) Unable to teach ability for {0}: the given variables must be a Creature";
private const string _noAbilityWarning = "(ETANA) Unable to teach ability for {0}: the ability could not be found";
[Tooltip("The node to move to when this node is finished")]
public InstructionGraphNode Next = null;
[Tooltip("The Ability to Teach")]
[InlineDisplay(PropagateLabel = true)]
public AbilityVariableSource Ability = new AbilityVariableSource();
public override Color NodeColor => Colors.ExecutionDark;
public override void GetInputs(List<VariableDefinition> inputs)
{
Ability.GetInputs(inputs);
}
protected override sealed IEnumerator Run_(InstructionGraph graph, InstructionStore variables, int iteration)
{
if (variables.This is Creature creature)
{
if (Ability.TryGetValue(variables, this, out var ability))
creature.Moves.Add(ability.CreateMove(creature));
else
Debug.LogWarningFormat(this, _noAbilityWarning, Name);
}
else
{
Debug.LogWarningFormat(this, _invalidVariablesWarning, Name);
}
graph.GoTo(Next, variables.This, nameof(Next));
yield break;
}
}
}
|
||||
TheStack | bd186092ce2936f01b6b855a6e4d0e20474bf8fc | C#code:C# | {"size": 2835, "ext": "cs", "max_stars_repo_path": "src/TelegramGames/TelegramGames.Icq.Core/Commands/RollDiceCommand.cs", "max_stars_repo_name": "Semptra/TelegramGames", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TelegramGames/TelegramGames.Icq.Core/Commands/RollDiceCommand.cs", "max_issues_repo_name": "Semptra/TelegramGames", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TelegramGames/TelegramGames.Icq.Core/Commands/RollDiceCommand.cs", "max_forks_repo_name": "Semptra/TelegramGames", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.8, "max_line_length": 166, "alphanum_fraction": 0.5686067019} | namespace TelegramGames.Icq.Core.Commands
{
using System;
using System.Linq;
using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramGames.Core.Extensions;
using TelegramGames.Core.Models;
using TelegramGames.Icq.Core.Database;
using TelegramGames.Icq.Core.Database.Models;
public class RollDiceCommand : ICommand
{
private readonly Random random;
private readonly IcqBotContext context;
public RollDiceCommand(IcqBotContext context)
{
random = new Random();
this.context = context;
}
public string Name => "roll_dice";
public void Execute(Message message, ITelegramBotClient telegramBotClient)
{
var firstDiceResult = random.Next(1, 7);
var secondDiceResult = random.Next(1, 7);
var currentPlayer = message.From.GetFullName();
var isAnyPlayedAlready = context.DiceResults.Any();
if (isAnyPlayedAlready)
{
string winnerMessage;
var lastDiceResult = context.DiceResults.Last();
var result = (firstDiceResult + secondDiceResult) - (lastDiceResult.LastFirstDiceResult + lastDiceResult.LastSecondDiceResult);
if (result < 0)
{
winnerMessage = $"Победитель: {lastDiceResult.LastUserPlayed}!";
}
else if (result > 0)
{
winnerMessage = $"Победитель: {currentPlayer}!";
}
else
{
winnerMessage = "Ничья!";
}
telegramBotClient.SendTextMessage(message.Chat.Id, $"{currentPlayer}, Вы сыграли в игру \"Кости\" против {lastDiceResult.LastUserPlayed}.\n" +
$"Ваш результат: {firstDiceResult} и {secondDiceResult} против {lastDiceResult.LastFirstDiceResult} и {lastDiceResult.LastSecondDiceResult}.\n" +
$"{winnerMessage}");
context.DiceResults.RemoveRange(context.DiceResults.ToList());
}
else
{
var diceResult = new DiceResult
{
LastUserPlayed = currentPlayer,
LastFirstDiceResult = firstDiceResult,
LastSecondDiceResult = secondDiceResult
};
context.DiceResults.Add(diceResult);
telegramBotClient.SendTextMessage(message.Chat.Id, $"{diceResult.LastUserPlayed}, Вы сыграли в игру \"Кости\".\n" +
$"Ваш результат: {diceResult.LastFirstDiceResult} и {diceResult.LastSecondDiceResult}!\n" +
$"Ожидаем результата противника.");
}
context.SaveChanges();
}
}
}
|
||||
TheStack | bd18956f6a175c661b258579b7907c3ca775713f | C#code:C# | {"size": 930, "ext": "cs", "max_stars_repo_path": "C01_C#ProgrammingFundamentals-May-2021/P14_ObjectsAndClasses-Exercise/P05_TeamworkProjects/Models/Team.cs", "max_stars_repo_name": "Statev7/SoftUni-Java", "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T15:58:38.000Z", "max_issues_repo_path": "C01_C#ProgrammingFundamentals-May-2021/P14_ObjectsAndClasses-Exercise/P05_TeamworkProjects/Models/Team.cs", "max_issues_repo_name": "Statev7/SoftUni", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C01_C#ProgrammingFundamentals-May-2021/P14_ObjectsAndClasses-Exercise/P05_TeamworkProjects/Models/Team.cs", "max_forks_repo_name": "Statev7/SoftUni", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.1351351351, "max_line_length": 59, "alphanum_fraction": 0.5505376344} | namespace P05_TeamworkProjects.Models
{
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Team
{
public Team(string teamName, string teamLeaderName)
{
this.TeamName = teamName;
this.TeamLeaderName = teamLeaderName;
Members = new List<string>();
}
public string TeamName { get; private set; }
public string TeamLeaderName { get; private set; }
public List<string> Members { get; set; }
public override string ToString()
{
StringBuilder str = new StringBuilder();
str.AppendLine($"{this.TeamName}");
str.AppendLine($"- {this.TeamLeaderName}");
foreach (var member in Members.OrderBy(x => x))
{
str.AppendLine($"-- {member}");
}
return str.ToString();
}
}
}
|
||||
TheStack | bd193fb67aae7c19879257e6904ae5aa9ab942b7 | C#code:C# | {"size": 681, "ext": "cs", "max_stars_repo_path": "tests/DbUpgader.Tests/IDestinationManagerTestHelper.cs", "max_stars_repo_name": "davidwengier/dbupgrader", "max_stars_repo_stars_event_min_datetime": "2018-04-16T03:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-08T22:30:56.000Z", "max_issues_repo_path": "tests/DbUpgader.Tests/IDestinationManagerTestHelper.cs", "max_issues_repo_name": "davidwengier/dbupgrader", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/DbUpgader.Tests/IDestinationManagerTestHelper.cs", "max_forks_repo_name": "davidwengier/dbupgrader", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.375, "max_line_length": 113, "alphanum_fraction": 0.7488986784} | using System;
using DbUpgrader.Definition;
using Xunit.Abstractions;
namespace DbUpgrader.Tests
{
public interface IDestinationManagerTestHelper : IXunitSerializable
{
bool ShouldRun();
UpgraderBuilder Init(UpgraderBuilder upgrade);
void AssertTableExists(string databaseName, string tableName);
void AssertFieldExists(string databaseName, string tableName, string fieldName);
void AssertFieldSizeEquals(string databaseName, string tableName, string fieldName, int size);
void AssertFieldTypeEquals(string databaseName, string tableName, string fieldName, FieldType fieldType);
IDisposable TestRun();
}
}
|
||||
TheStack | bd19a63e719bbfbfb4802f4e9b71bebc85e162c9 | C#code:C# | {"size": 2003, "ext": "cs", "max_stars_repo_path": "testing/nunit/SampleTests.cs", "max_stars_repo_name": "ewilde/dotnet-playground", "max_stars_repo_stars_event_min_datetime": "2015-01-30T16:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-30T16:33:17.000Z", "max_issues_repo_path": "testing/nunit/SampleTests.cs", "max_issues_repo_name": "ewilde/dotnet-playground", "max_issues_repo_issues_event_min_datetime": "2015-01-30T10:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-30T10:34:07.000Z", "max_forks_repo_path": "testing/nunit/SampleTests.cs", "max_forks_repo_name": "ewilde/dotnet-playground", "max_forks_repo_forks_event_min_datetime": "2015-01-30T10:24:13.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T12:38:58.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": 2.0, "avg_line_length": 26.3552631579, "max_line_length": 77, "alphanum_fraction": 0.5032451323} | // -----------------------------------------------------------------------
// <copyright file="ProductTests.cs">
// Copyright (c) 2014.
// </copyright>
// -----------------------------------------------------------------------
using System;
namespace nunit.example
{
using System.Diagnostics;
using Edward.Wilde.CSharp.Features.Model;
using NUnit.Framework;
[TestFixture]
public class SampleTests
{
[TestFixtureSetUp] // Once per class
public void TestFixtureSetUp()
{
Debug.WriteLine("SampleTests: TestFixtureSetUp");
}
[TestFixtureTearDown] // Once per class
public void TestFixtureTearDown()
{
Debug.WriteLine("SampleTests: TestFixtureTearDown");
}
[SetUp] // Once per test
public void SetUp()
{
Debug.WriteLine("SampleTests: Setup");
}
[TearDown] // Once per test
public void TearDown()
{
Debug.WriteLine("SampleTests: TearDown");
}
[Test]
public void creating_an_instance_of_employee_should_initialize_foo()
{
var product = new Product("Bean", 15.5m);
Assert.That(product.Name, Is.EqualTo("Bean"));
}
[Test]
public void creating_an_instance_of_employee_should_initialize_foo2()
{
var product = new Product("Bean", 15.5m);
Assert.That(product.Name, Is.EqualTo("Bean"));
}
[Test]
public void asserting_for_an_exception()
{
Assert.Throws<NullReferenceException>(() =>
{
object foo = null;
foo.ToString();
});
}
[Test, ExpectedException(typeof(NullReferenceException))]
public void asserting_for_an_exception_using_an_attribute()
{
object foo = null;
foo.ToString();
}
}
} |
||||
TheStack | bd1a835e0c9e9bb5ab62f5a431546ec8dde1e90d | C#code:C# | {"size": 2715, "ext": "cs", "max_stars_repo_path": "tests/MSTest.Extensions.Tests/Contracts/ContractTestTests.cs", "max_stars_repo_name": "dotnet-campus/cUnit", "max_stars_repo_stars_event_min_datetime": "2019-12-13T03:46:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:39:17.000Z", "max_issues_repo_path": "tests/MSTest.Extensions.Tests/Contracts/ContractTestTests.cs", "max_issues_repo_name": "dotnet-campus/cUnit", "max_issues_repo_issues_event_min_datetime": "2020-05-18T23:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-24T06:54:29.000Z", "max_forks_repo_path": "tests/MSTest.Extensions.Tests/Contracts/ContractTestTests.cs", "max_forks_repo_name": "dotnet-campus/cUnit", "max_forks_repo_forks_event_min_datetime": "2020-02-18T10:34:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T09:27:57.000Z"} | {"max_stars_count": 27.0, "max_issues_count": 5.0, "max_forks_count": 6.0, "avg_line_length": 33.5185185185, "max_line_length": 118, "alphanum_fraction": 0.5749539595} | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MSTest.Extensions.Contracts;
#pragma warning disable CS1998
namespace MSTest.Extensions.Tests.Contracts
{
[TestClass]
public class ContractTestTests
{
[TestMethod]
[DataRow(null, false, false, DisplayName = "If contract is null but action is not null, exception thrown.")]
[DataRow("", true, false, DisplayName = "If contract is not null but action is null, exception thrown.")]
[DataRow(null, false, true, DisplayName =
"If contract is null but async action is not null, exception thrown.")]
[DataRow("", true, true, DisplayName = "If contract is not null but async action is null, exception thrown.")]
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
public void Test_NullArgument_ArgumentNullExceptionThrown(string contract, bool isActionNull, bool isAsync)
{
if (isAsync)
{
// Arrange
var action = isActionNull ? (Func<Task>) null : async () => { };
// Action & Assert
Assert.ThrowsException<ArgumentNullException>(() => { contract.Test(action); });
}
else
{
// Arrange
var action = isActionNull ? (Action) null : () => { };
// Action & Assert
Assert.ThrowsException<ArgumentNullException>(() => { contract.Test(action); });
}
}
[TestMethod]
public void Test_Action_TestCaseCreatedAndExecuted()
{
// Arrange
const string contract = "Test contract description.";
var executed = false;
// Action
contract.Test(() => executed = true);
var result = ContractTest.Method.Current.Single().Result;
// Assert
Assert.AreEqual(result.DisplayName, contract);
Assert.IsTrue(executed);
}
[TestMethod]
public void Test_AsyncAction_TestCaseCreatedAndExecuted()
{
// Arrange
const string contract = "Test contract description.";
var executed = false;
// Action
contract.Test(async () =>
{
await Task.Yield();
executed = true;
});
var result = ContractTest.Method.Current.Single().Result;
// Assert
Assert.AreEqual(result.DisplayName, contract);
Assert.IsTrue(executed);
}
}
}
#pragma warning restore CS1998
|
||||
TheStack | bd1c7f8c16ed6bb2717c826858c7c73d2bde01b3 | C#code:C# | {"size": 16284, "ext": "cs", "max_stars_repo_path": "SpritesetEditorPlugin/Components/DirectionLayout.Designer.cs", "max_stars_repo_name": "spheredev/sphere-studio", "max_stars_repo_stars_event_min_datetime": "2021-11-29T05:43:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T05:43:17.000Z", "max_issues_repo_path": "SpritesetEditorPlugin/Components/DirectionLayout.Designer.cs", "max_issues_repo_name": "fatcerberus/sphere-studio", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SpritesetEditorPlugin/Components/DirectionLayout.Designer.cs", "max_forks_repo_name": "fatcerberus/sphere-studio", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 51.8598726115, "max_line_length": 173, "alphanum_fraction": 0.620547777} | namespace SphereStudio.Components
{
partial class DirectionLayout
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.InfoPanel = new System.Windows.Forms.Panel();
this.NamePanel = new System.Windows.Forms.Panel();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.NameLabel = new SphereStudio.UI.DialogHeader();
this.ImagesPanel = new System.Windows.Forms.Panel();
this.AddPanel = new System.Windows.Forms.Panel();
this.AddFrameButton = new System.Windows.Forms.Button();
this.RemoveFrameButton = new System.Windows.Forms.Button();
this.DirectionStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.AddItem = new System.Windows.Forms.ToolStripMenuItem();
this.RemoveItem = new System.Windows.Forms.ToolStripMenuItem();
this.Seperator1 = new System.Windows.Forms.ToolStripSeparator();
this.AddDirectionItem = new System.Windows.Forms.ToolStripMenuItem();
this.RemoveDirectionItem = new System.Windows.Forms.ToolStripMenuItem();
this.Separator2 = new System.Windows.Forms.ToolStripSeparator();
this.SetDelayItem = new System.Windows.Forms.ToolStripMenuItem();
this.Separator3 = new System.Windows.Forms.ToolStripSeparator();
this.ZoomInItem = new System.Windows.Forms.ToolStripMenuItem();
this.ZoomOutItem = new System.Windows.Forms.ToolStripMenuItem();
this.Seperator4 = new System.Windows.Forms.ToolStripSeparator();
this.ToggleItem = new System.Windows.Forms.ToolStripMenuItem();
this.InfoPanel.SuspendLayout();
this.NamePanel.SuspendLayout();
this.AddPanel.SuspendLayout();
this.DirectionStrip.SuspendLayout();
this.SuspendLayout();
//
// InfoPanel
//
this.InfoPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(225)))), ((int)(((byte)(243)))));
this.InfoPanel.Controls.Add(this.NamePanel);
this.InfoPanel.Controls.Add(this.NameLabel);
this.InfoPanel.Dock = System.Windows.Forms.DockStyle.Left;
this.InfoPanel.Location = new System.Drawing.Point(0, 0);
this.InfoPanel.Name = "InfoPanel";
this.InfoPanel.Size = new System.Drawing.Size(140, 81);
this.InfoPanel.TabIndex = 0;
//
// NamePanel
//
this.NamePanel.Controls.Add(this.NameTextBox);
this.NamePanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.NamePanel.Location = new System.Drawing.Point(0, 23);
this.NamePanel.Name = "NamePanel";
this.NamePanel.Size = new System.Drawing.Size(140, 58);
this.NamePanel.TabIndex = 2;
//
// NameTextBox
//
this.NameTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.NameTextBox.Location = new System.Drawing.Point(5, 19);
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.Size = new System.Drawing.Size(131, 20);
this.NameTextBox.TabIndex = 1;
this.NameTextBox.Text = "Direction";
this.NameTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.NameTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
//
// NameLabel
//
this.NameLabel.Dock = System.Windows.Forms.DockStyle.Top;
this.NameLabel.Font = new System.Drawing.Font("Verdana", 10.5F);
this.NameLabel.ForeColor = System.Drawing.Color.MidnightBlue;
this.NameLabel.Location = new System.Drawing.Point(0, 0);
this.NameLabel.Name = "NameLabel";
this.NameLabel.Size = new System.Drawing.Size(140, 23);
this.NameLabel.TabIndex = 3;
this.NameLabel.Text = "Name";
this.NameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.NameLabel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.NameLabel_MouseDown);
this.NameLabel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.NameLabel_MouseMove);
//
// ImagesPanel
//
this.ImagesPanel.AutoSize = true;
this.ImagesPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.ImagesPanel.Location = new System.Drawing.Point(140, 0);
this.ImagesPanel.Name = "ImagesPanel";
this.ImagesPanel.Size = new System.Drawing.Size(0, 81);
this.ImagesPanel.TabIndex = 1;
//
// AddPanel
//
this.AddPanel.AllowDrop = true;
this.AddPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(225)))), ((int)(((byte)(243)))));
this.AddPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.AddPanel.Controls.Add(this.AddFrameButton);
this.AddPanel.Controls.Add(this.RemoveFrameButton);
this.AddPanel.Dock = System.Windows.Forms.DockStyle.Right;
this.AddPanel.Location = new System.Drawing.Point(140, 0);
this.AddPanel.MinimumSize = new System.Drawing.Size(90, 2);
this.AddPanel.Name = "AddPanel";
this.AddPanel.Size = new System.Drawing.Size(90, 81);
this.AddPanel.TabIndex = 0;
//
// AddFrameButton
//
this.AddFrameButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.AddFrameButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.AddFrameButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.AddFrameButton.Image = global::SphereStudio.Properties.Resources.NextToolIcon;
this.AddFrameButton.Location = new System.Drawing.Point(47, 23);
this.AddFrameButton.Name = "AddFrameButton";
this.AddFrameButton.Size = new System.Drawing.Size(32, 32);
this.AddFrameButton.TabIndex = 0;
this.AddFrameButton.UseVisualStyleBackColor = true;
this.AddFrameButton.Click += new System.EventHandler(this.AddFrameButton_Click);
//
// RemoveFrameButton
//
this.RemoveFrameButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.RemoveFrameButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.RemoveFrameButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.RemoveFrameButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.RemoveFrameButton.Image = global::SphereStudio.Properties.Resources.BackToolIcon;
this.RemoveFrameButton.Location = new System.Drawing.Point(9, 23);
this.RemoveFrameButton.Name = "RemoveFrameButton";
this.RemoveFrameButton.Size = new System.Drawing.Size(32, 32);
this.RemoveFrameButton.TabIndex = 1;
this.RemoveFrameButton.UseVisualStyleBackColor = true;
this.RemoveFrameButton.Click += new System.EventHandler(this.RemoveFrameButton_Click);
//
// DirectionStrip
//
this.DirectionStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddItem,
this.RemoveItem,
this.Seperator1,
this.AddDirectionItem,
this.RemoveDirectionItem,
this.Separator2,
this.SetDelayItem,
this.Separator3,
this.ZoomInItem,
this.ZoomOutItem,
this.Seperator4,
this.ToggleItem});
this.DirectionStrip.Name = "DirectionStrip";
this.DirectionStrip.Size = new System.Drawing.Size(172, 226);
this.DirectionStrip.Opening += new System.ComponentModel.CancelEventHandler(this.DirectionStrip_Opening);
//
// AddItem
//
this.AddItem.Image = global::SphereStudio.Properties.Resources.AddToolIcon;
this.AddItem.Name = "AddItem";
this.AddItem.Size = new System.Drawing.Size(171, 22);
this.AddItem.Text = "&Add Frame";
this.AddItem.Click += new System.EventHandler(this.AddItem_Click);
//
// RemoveItem
//
this.RemoveItem.Image = global::SphereStudio.Properties.Resources.DeleteToolIcon;
this.RemoveItem.Name = "RemoveItem";
this.RemoveItem.Size = new System.Drawing.Size(171, 22);
this.RemoveItem.Text = "&Remove Frame";
this.RemoveItem.Click += new System.EventHandler(this.RemoveItem_Click);
//
// Seperator1
//
this.Seperator1.Name = "Seperator1";
this.Seperator1.Size = new System.Drawing.Size(168, 6);
//
// AddDirectionItem
//
this.AddDirectionItem.Image = global::SphereStudio.Properties.Resources.AddToolIcon;
this.AddDirectionItem.Name = "AddDirectionItem";
this.AddDirectionItem.Size = new System.Drawing.Size(171, 22);
this.AddDirectionItem.Text = "Add &Direction";
this.AddDirectionItem.Click += new System.EventHandler(this.AddDirectionItem_Click);
//
// RemoveDirectionItem
//
this.RemoveDirectionItem.Image = global::SphereStudio.Properties.Resources.DeleteToolIcon;
this.RemoveDirectionItem.Name = "RemoveDirectionItem";
this.RemoveDirectionItem.Size = new System.Drawing.Size(171, 22);
this.RemoveDirectionItem.Text = "R&emove Direction";
this.RemoveDirectionItem.Click += new System.EventHandler(this.RemoveDirectionItem_Click);
//
// Separator2
//
this.Separator2.Name = "Separator2";
this.Separator2.Size = new System.Drawing.Size(168, 6);
//
// SetDelayItem
//
this.SetDelayItem.Image = global::SphereStudio.Properties.Resources.page_white_edit;
this.SetDelayItem.Name = "SetDelayItem";
this.SetDelayItem.Size = new System.Drawing.Size(171, 22);
this.SetDelayItem.Text = "&Set Delay...";
this.SetDelayItem.Click += new System.EventHandler(this.SetDelayItem_Click);
//
// Separator3
//
this.Separator3.Name = "Separator3";
this.Separator3.Size = new System.Drawing.Size(168, 6);
//
// ZoomInItem
//
this.ZoomInItem.Image = global::SphereStudio.Properties.Resources.ZoomInToolIcon;
this.ZoomInItem.Name = "ZoomInItem";
this.ZoomInItem.Size = new System.Drawing.Size(171, 22);
this.ZoomInItem.Text = "Zoom &In";
this.ZoomInItem.Click += new System.EventHandler(this.ZoomInItem_Click);
//
// ZoomOutItem
//
this.ZoomOutItem.Image = global::SphereStudio.Properties.Resources.ZoomOutToolIcon;
this.ZoomOutItem.Name = "ZoomOutItem";
this.ZoomOutItem.Size = new System.Drawing.Size(171, 22);
this.ZoomOutItem.Text = "Zoom &Out";
this.ZoomOutItem.Click += new System.EventHandler(this.ZoomOutItem_Click);
//
// Seperator4
//
this.Seperator4.Name = "Seperator4";
this.Seperator4.Size = new System.Drawing.Size(168, 6);
//
// ToggleItem
//
this.ToggleItem.Name = "ToggleItem";
this.ToggleItem.Size = new System.Drawing.Size(171, 22);
this.ToggleItem.Text = "&Show Delay Values";
this.ToggleItem.Click += new System.EventHandler(this.ToggleItem_Click);
//
// DirectionLayout
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
this.BackColor = System.Drawing.SystemColors.AppWorkspace;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ContextMenuStrip = this.DirectionStrip;
this.Controls.Add(this.ImagesPanel);
this.Controls.Add(this.InfoPanel);
this.Controls.Add(this.AddPanel);
this.DoubleBuffered = true;
this.MinimumSize = new System.Drawing.Size(230, 83);
this.Name = "DirectionLayout";
this.Size = new System.Drawing.Size(230, 81);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.DirectionLayout_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.DirectionLayout_DragEnter);
this.DragOver += new System.Windows.Forms.DragEventHandler(this.DirectionLayout_DragOver);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.DirectionLayout_Paint);
this.InfoPanel.ResumeLayout(false);
this.NamePanel.ResumeLayout(false);
this.NamePanel.PerformLayout();
this.AddPanel.ResumeLayout(false);
this.DirectionStrip.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel InfoPanel;
private System.Windows.Forms.TextBox NameTextBox;
private System.Windows.Forms.Panel NamePanel;
private System.Windows.Forms.Panel ImagesPanel;
private System.Windows.Forms.Panel AddPanel;
private System.Windows.Forms.Button RemoveFrameButton;
private System.Windows.Forms.Button AddFrameButton;
private System.Windows.Forms.ContextMenuStrip DirectionStrip;
private System.Windows.Forms.ToolStripMenuItem AddItem;
private System.Windows.Forms.ToolStripMenuItem RemoveItem;
private System.Windows.Forms.ToolStripSeparator Seperator1;
private System.Windows.Forms.ToolStripMenuItem ToggleItem;
private SphereStudio.UI.DialogHeader NameLabel;
private System.Windows.Forms.ToolStripMenuItem ZoomInItem;
private System.Windows.Forms.ToolStripMenuItem ZoomOutItem;
private System.Windows.Forms.ToolStripSeparator Separator3;
private System.Windows.Forms.ToolStripMenuItem AddDirectionItem;
private System.Windows.Forms.ToolStripSeparator Separator2;
private System.Windows.Forms.ToolStripMenuItem RemoveDirectionItem;
private System.Windows.Forms.ToolStripMenuItem SetDelayItem;
private System.Windows.Forms.ToolStripSeparator Seperator4;
}
}
|
||||
TheStack | bd1cc8704c3b9f81a92bbb38455f7a00531c12e2 | C#code:C# | {"size": 788, "ext": "cs", "max_stars_repo_path": "Xamarin.Forms.Platform.GTK/Extensions/PageExtensions.cs", "max_stars_repo_name": "brainoffline/Xamarin.Forms", "max_stars_repo_stars_event_min_datetime": "2018-11-14T14:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T10:18:01.000Z", "max_issues_repo_path": "Xamarin.Forms.Platform.GTK/Extensions/PageExtensions.cs", "max_issues_repo_name": "brainoffline/Xamarin.Forms", "max_issues_repo_issues_event_min_datetime": "2020-04-23T07:50:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T12:06:48.000Z", "max_forks_repo_path": "Xamarin.Forms.Platform.GTK/Extensions/PageExtensions.cs", "max_forks_repo_name": "brainoffline/Xamarin.Forms", "max_forks_repo_forks_event_min_datetime": "2019-04-20T11:28:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T22:01:31.000Z"} | {"max_stars_count": 4.0, "max_issues_count": 2.0, "max_forks_count": 2.0, "avg_line_length": 19.2195121951, "max_line_length": 73, "alphanum_fraction": 0.7030456853} | using System;
namespace Xamarin.Forms.Platform.GTK.Extensions
{
public static class PageExtensions
{
internal static bool ShouldDisplayNativeWindow(this Page page)
{
var parentPage = page.Parent as Page;
if (parentPage != null)
{
return string.IsNullOrEmpty(parentPage.BackgroundImage);
}
return true;
}
public static GtkFormsContainer CreateContainer(this Page view)
{
if (!Forms.IsInitialized)
throw new InvalidOperationException("call Forms.Init() before this");
if (!(view.RealParent is Application))
{
Application app = new DefaultApplication();
app.MainPage = view;
}
var result = new Platform();
result.SetPage(view);
return result.PlatformRenderer;
}
class DefaultApplication : Application
{
}
}
}
|
||||
TheStack | bd1eab20538a4feb6c3bb1c30ab8035c87ae0421 | C#code:C# | {"size": 840, "ext": "cs", "max_stars_repo_path": "consumer-tests/WeatherForecastPact.cs", "max_stars_repo_name": "uglyog/pact-csharp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "consumer-tests/WeatherForecastPact.cs", "max_issues_repo_name": "uglyog/pact-csharp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "consumer-tests/WeatherForecastPact.cs", "max_forks_repo_name": "uglyog/pact-csharp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.0967741935, "max_line_length": 118, "alphanum_fraction": 0.7047619048} | using System;
using PactNet;
using PactNet.Mocks.MockHttpService;
namespace consumer_tests
{
public class WeatherForecastPact : IDisposable
{
public IPactBuilder PactBuilder { get; private set; }
public IMockProviderService MockProviderService { get; private set; }
public int MockServerPort { get { return 9222; } }
public string MockProviderServiceBaseUri { get { return String.Format("http://localhost:{0}", MockServerPort); } }
public WeatherForecastPact()
{
PactBuilder = new PactBuilder(new PactConfig { SpecificationVersion = "2.0.0" });
PactBuilder
.ServiceConsumer("WeatherForcastConsumer")
.HasPactWith("WeatherForcastAPI");
MockProviderService = PactBuilder.MockService(MockServerPort);
}
public void Dispose()
{
PactBuilder.Build();
}
}
}
|
||||
TheStack | bd1f107ba1fdb46de04b56d5267054c451e879ae | C#code:C# | {"size": 291, "ext": "cs", "max_stars_repo_path": "Lishl.Users.Api/Cqrs/Queries/GetUsersByPaginationFilterQuery.cs", "max_stars_repo_name": "danylo-boiko/Lishl", "max_stars_repo_stars_event_min_datetime": "2021-11-07T22:19:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T21:41:55.000Z", "max_issues_repo_path": "Lishl.Users.Api/Cqrs/Queries/GetUsersByPaginationFilterQuery.cs", "max_issues_repo_name": "danylo-boiko/Lishl", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lishl.Users.Api/Cqrs/Queries/GetUsersByPaginationFilterQuery.cs", "max_forks_repo_name": "danylo-boiko/Lishl", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.25, "max_line_length": 79, "alphanum_fraction": 0.7491408935} | using System.Collections.Generic;
using Lishl.Core;
using Lishl.Core.Models;
using MediatR;
namespace Lishl.Users.Api.Cqrs.Queries
{
public record GetUsersByPaginationFilterQuery : IRequest<IEnumerable<User>>
{
public PaginationFilter PaginationFilter { get; set; }
}
} |
||||
TheStack | bd209f0cf476eb4189fc27058f4ed88efb7dad78 | C#code:C# | {"size": 691, "ext": "cs", "max_stars_repo_path": "test/Routine.Test/Client/Stubs/Sync.cs", "max_stars_repo_name": "multinetinventiv/routine", "max_stars_repo_stars_event_min_datetime": "2019-09-09T16:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T08:01:23.000Z", "max_issues_repo_path": "test/Routine.Test/Client/Stubs/Sync.cs", "max_issues_repo_name": "multinetinventiv/routine", "max_issues_repo_issues_event_min_datetime": "2020-01-02T05:28:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T12:12:16.000Z", "max_forks_repo_path": "test/Routine.Test/Client/Stubs/Sync.cs", "max_forks_repo_name": "multinetinventiv/routine", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 23.0, "max_forks_count": null, "avg_line_length": 31.4090909091, "max_line_length": 104, "alphanum_fraction": 0.6787264834} | using Moq;
using Routine.Client;
using Routine.Core;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Routine.Test.Client.Stubs
{
public class Sync : IPerformer
{
public Rvariable Perform(Robject target, string operationName, params Rvariable[] parameters) =>
target.Perform(operationName, parameters);
public void SetUp(Mock<IObjectService> mock,
ReferenceData id,
string operation,
Expression<Func<Dictionary<string, ParameterValueData>, bool>> match,
VariableData result
) => mock.Setup(os => os.Do(id, operation, It.Is(match))).Returns(result);
}
} |
||||
TheStack | bd20a327b5b84ed99665c5439afad904db69fcaf | C#code:C# | {"size": 6584, "ext": "cs", "max_stars_repo_path": "Simple.Wpf.FSharp.Repl.Tests/ReplEngineControllerFixtures.cs", "max_stars_repo_name": "oriches/Simple.Wpf.FSharp.Repl", "max_stars_repo_stars_event_min_datetime": "2015-02-15T19:31:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T21:20:51.000Z", "max_issues_repo_path": "Simple.Wpf.FSharp.Repl.Tests/ReplEngineControllerFixtures.cs", "max_issues_repo_name": "oriches/Simple.Wpf.FSharp.Repl", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simple.Wpf.FSharp.Repl.Tests/ReplEngineControllerFixtures.cs", "max_forks_repo_name": "oriches/Simple.Wpf.FSharp.Repl", "max_forks_repo_forks_event_min_datetime": "2015-06-10T10:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T13:15:52.000Z"} | {"max_stars_count": 12.0, "max_issues_count": null, "max_forks_count": 6.0, "avg_line_length": 36.9887640449, "max_line_length": 114, "alphanum_fraction": 0.60009113} | using System;
using System.Linq;
using System.Reactive.Subjects;
using Microsoft.Reactive.Testing;
using Moq;
using NUnit.Framework;
using Simple.Wpf.FSharp.Repl.Core;
using Simple.Wpf.FSharp.Repl.Services;
using Simple.Wpf.FSharp.Repl.Tests.Extensions;
using Simple.Wpf.FSharp.Repl.UI.Controllers;
using Simple.Wpf.FSharp.Repl.UI.ViewModels;
namespace Simple.Wpf.FSharp.Repl.Tests
{
[TestFixture]
public class ReplEngineControllerFixtures
{
[SetUp]
public void Setup()
{
_testScheduler = new TestScheduler();
_processService = new Mock<IProcessService>(MockBehavior.Strict);
_errorSubject = new Subject<string>();
_outputSubject = new Subject<string>();
_stateSubject = new Subject<State>();
_replEngine = new Mock<IReplEngine>(MockBehavior.Strict);
_replEngine.Setup(x => x.Error).Returns(_errorSubject);
_replEngine.Setup(x => x.Output).Returns(_outputSubject);
_replEngine.Setup(x => x.State).Returns(_stateSubject);
_replEngine.Setup(x => x.WorkingDirectory).Returns((string) null);
_replEngine.Setup(x => x.Start(null)).Returns(_replEngine.Object);
}
private Mock<IProcessService> _processService;
private Mock<IReplEngine> _replEngine;
private TestScheduler _testScheduler;
private Subject<string> _errorSubject;
private Subject<string> _outputSubject;
private Subject<State> _stateSubject;
[Test]
public void repl_engine_executes_script_when_controller_execute_is_called()
{
// ARRANGE
const string script = "let x = 345;;";
_replEngine.Setup(x => x.Execute(script)).Returns(_replEngine.Object).Verifiable();
var controller =
new ReplEngineController(null, null, _replEngine.Object, _processService.Object, _testScheduler);
var viewModel = (ReplEngineViewModel) controller.ViewModel;
// ACT
controller.Execute(script);
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ASSERT
_replEngine.Verify(x => x.Execute(script), Times.Once);
}
[Test]
public void repl_engine_executes_when_view_model_execute_is_called()
{
// ARRANGE
var script = @"let x = 123;;";
_replEngine.Setup(x => x.Execute(script)).Returns(_replEngine.Object).Verifiable();
var controller = new ReplEngineController(null, null, _replEngine.Object, _processService.Object,
_testScheduler, _testScheduler);
var viewModel = (ReplEngineViewModel) controller.ViewModel;
_stateSubject.OnNext(State.Running);
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ACT
viewModel.ExecuteCommand.Execute(script);
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ASSERT
_replEngine.Verify(x => x.Execute(script), Times.Once);
}
[Test]
public void repl_engine_generates_error_output_then_view_model_is_updated()
{
// ARRANGE
var controller =
new ReplEngineController(null, null, _replEngine.Object, _processService.Object, _testScheduler);
var viewModel = (ReplEngineViewModel) controller.ViewModel;
// ACT
_errorSubject.OnNext("error 1");
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ASSERT
Assert.That(viewModel.Output.Count(), Is.EqualTo(1));
Assert.That(viewModel.Output.First().Value, Is.EqualTo("error 1"));
Assert.That(viewModel.Output.First().IsError, Is.True);
}
[Test]
public void repl_engine_generates_output_then_view_model_is_updated()
{
// ARRANGE
var controller =
new ReplEngineController(null, null, _replEngine.Object, _processService.Object, _testScheduler);
var viewModel = (ReplEngineViewModel) controller.ViewModel;
// ACT
_outputSubject.OnNext("line 1");
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ASSERT
Assert.That(viewModel.Output.Count(), Is.EqualTo(1));
Assert.That(viewModel.Output.First().Value, Is.EqualTo("line 1"));
Assert.That(viewModel.Output.First().IsError, Is.False);
}
[Test]
public void repl_engine_is_only_started_once()
{
// ARRANGE
var controller =
new ReplEngineController(null, null, _replEngine.Object, _processService.Object, _testScheduler);
// ACT
var viewModel1 = controller.ViewModel;
var viewModel2 = controller.ViewModel;
// ASSERT
Assert.That(viewModel1, Is.Not.Null);
Assert.That(viewModel2, Is.Not.Null);
_replEngine.Verify(x => x.Start(It.IsAny<string>()), Times.Once());
}
[Test]
public void repl_engine_is_started_when_view_model_is_accessed()
{
// ARRANGE
var controller =
new ReplEngineController(null, null, _replEngine.Object, _processService.Object, _testScheduler);
// ACT
var viewModel = controller.ViewModel;
// ASSERT
Assert.That(viewModel, Is.Not.Null);
_replEngine.Verify(x => x.Start(It.IsAny<string>()), Times.Once());
}
[Test]
public void repl_engine_resets_when_view_model_reset_is_called()
{
// ARRANGE
_replEngine.Setup(x => x.Reset()).Returns(_replEngine.Object).Verifiable();
var controller = new ReplEngineController(null, null, _replEngine.Object, _processService.Object,
_testScheduler, _testScheduler);
var viewModel = (ReplEngineViewModel) controller.ViewModel;
_stateSubject.OnNext(State.Running);
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ACT
viewModel.ResetCommand.Execute(null);
_testScheduler.AdvanceBy(TimeSpan.FromSeconds(1));
// ASSERT
_replEngine.Verify(x => x.Reset(), Times.Once);
}
}
} |
||||
TheStack | bd2180efc4127ecab781dcd74dd6a0368b510d3b | C#code:C# | {"size": 946, "ext": "cs", "max_stars_repo_path": "src/Distribox.GUI/InviteDialog.cs", "max_stars_repo_name": "BYVoid/distribox", "max_stars_repo_stars_event_min_datetime": "2015-07-09T19:27:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T03:01:48.000Z", "max_issues_repo_path": "src/Distribox.GUI/InviteDialog.cs", "max_issues_repo_name": "BYVoid/distribox", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Distribox.GUI/InviteDialog.cs", "max_forks_repo_name": "BYVoid/distribox", "max_forks_repo_forks_event_min_datetime": "2015-01-27T03:22:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T02:30:11.000Z"} | {"max_stars_count": 14.0, "max_issues_count": null, "max_forks_count": 10.0, "avg_line_length": 21.5, "max_line_length": 63, "alphanum_fraction": 0.5285412262} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Distribox.GUI
{
public partial class InviteDialog : Form
{
public string IP { get; set; }
public int Port { get; set; }
public InviteDialog()
{
InitializeComponent();
this.Port = -1;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Port = int.Parse(this.textBox1.Text);
this.IP = this.textBox2.Text;
this.Close();
}
catch
{
MessageBox.Show("Please input a valid number");
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
||||
TheStack | bd2268ac3fbd80ddc98be121ce6cb95954b4ac11 | C#code:C# | {"size": 3504, "ext": "cs", "max_stars_repo_path": "Client/Framework/SLStudio.Logging/Loggers/DefaultLogger.cs", "max_stars_repo_name": "adnan-54/SLStudio", "max_stars_repo_stars_event_min_datetime": "2019-08-24T18:06:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T18:43:55.000Z", "max_issues_repo_path": "Client/Framework/SLStudio.Logging/Loggers/DefaultLogger.cs", "max_issues_repo_name": "adnan-54/SLStudio", "max_issues_repo_issues_event_min_datetime": "2021-10-02T21:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T14:02:37.000Z", "max_forks_repo_path": "Client/Framework/SLStudio.Logging/Loggers/DefaultLogger.cs", "max_forks_repo_name": "adnan-54/SLStudio", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 3.0, "max_forks_count": null, "avg_line_length": 40.7441860465, "max_line_length": 128, "alphanum_fraction": 0.6618150685} | using System;
namespace SLStudio.Logging
{
internal class DefaultLogger : ILogger
{
private readonly ILoggingService loggingService;
public DefaultLogger(ILoggingService loggingService)
{
this.loggingService = loggingService;
}
public string Name { get; set; }
public void Log(object message, string title, string callerFile, string callerMember, int callerLine)
{
Enqueue(title, message, null, callerFile, callerMember, callerLine);
}
public void Log(Exception exception, string callerFile, string callerMember, int callerLine)
{
LogException(exception, null, callerFile, callerMember, callerLine);
}
public void Debug(object message, string title, string callerFile, string callerMember, int callerLine)
{
Enqueue(title, message, $"{LogLevel.Debug}", callerFile, callerMember, callerLine);
}
public void Debug(Exception exception, string callerFile, string callerMember, int callerLine)
{
LogException(exception, $"{LogLevel.Debug}", callerFile, callerMember, callerLine);
}
public void Info(object message, string title, string callerFile, string callerMember, int callerLine)
{
Enqueue(title, message, $"{LogLevel.Info}", callerFile, callerMember, callerLine);
}
public void Info(Exception exception, string callerFile, string callerMember, int callerLine)
{
LogException(exception, $"{LogLevel.Info}", callerFile, callerMember, callerLine);
}
public void Warn(object message, string title, string callerFile, string callerMember, int callerLine)
{
Enqueue(title, message, $"{LogLevel.Warning}", callerFile, callerMember, callerLine);
}
public void Warn(Exception exception, string callerFile, string callerMember, int callerLine)
{
LogException(exception, $"{LogLevel.Warning}", callerFile, callerMember, callerLine);
}
public void Error(object message, string title, string callerFile, string callerMember, int callerLine)
{
Enqueue(title, message, $"{LogLevel.Error}", callerFile, callerMember, callerLine);
}
public void Error(Exception exception, string callerFile, string callerMember, int callerLine)
{
LogException(exception, $"{LogLevel.Error}", callerFile, callerMember, callerLine);
}
public void Fatal(object message, string title, string callerFile, string callerMember, int callerLine)
{
Enqueue(title, message, $"{LogLevel.Fatal}", callerFile, callerMember, callerLine);
}
public void Fatal(Exception exception, string callerFile, string callerMember, int callerLine)
{
LogException(exception, $"{LogLevel.Fatal}", callerFile, callerMember, callerLine);
}
private void LogException(Exception exception, string level, string callerFile, string callerMember, int callerLine)
{
Enqueue(exception.Message, exception.ToString(), level, callerFile, callerMember, callerLine);
}
private void Enqueue(string title, object message, string level, string callerFile, string callerMember, int callerLine)
{
loggingService.EnqueueLog(Name, title, $"{message}", level, callerFile, callerMember, callerLine);
}
}
} |
||||
TheStack | bd22b343d5d96fd744c95777cac858c5132413a2 | C#code:C# | {"size": 2216, "ext": "cs", "max_stars_repo_path": "sdk/dotnet/Outputs/LoadBalancerForwardingRule.cs", "max_stars_repo_name": "andrewsomething/pulumi-digitalocean", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/dotnet/Outputs/LoadBalancerForwardingRule.cs", "max_issues_repo_name": "andrewsomething/pulumi-digitalocean", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/dotnet/Outputs/LoadBalancerForwardingRule.cs", "max_forks_repo_name": "andrewsomething/pulumi-digitalocean", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.625, "max_line_length": 149, "alphanum_fraction": 0.6254512635} | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.DigitalOcean.Outputs
{
[OutputType]
public sealed class LoadBalancerForwardingRule
{
/// <summary>
/// The ID of the TLS certificate to be used for SSL termination.
/// </summary>
public readonly string? CertificateId;
/// <summary>
/// An integer representing the port on which the Load Balancer instance will listen.
/// </summary>
public readonly int EntryPort;
/// <summary>
/// The protocol used for traffic to the Load Balancer. The possible values are: `http`, `https`, `http2` or `tcp`.
/// </summary>
public readonly string EntryProtocol;
/// <summary>
/// An integer representing the port on the backend Droplets to which the Load Balancer will send traffic.
/// </summary>
public readonly int TargetPort;
/// <summary>
/// The protocol used for traffic from the Load Balancer to the backend Droplets. The possible values are: `http`, `https`, `http2` or `tcp`.
/// </summary>
public readonly string TargetProtocol;
/// <summary>
/// A boolean value indicating whether SSL encrypted traffic will be passed through to the backend Droplets. The default value is `false`.
/// </summary>
public readonly bool? TlsPassthrough;
[OutputConstructor]
private LoadBalancerForwardingRule(
string? certificateId,
int entryPort,
string entryProtocol,
int targetPort,
string targetProtocol,
bool? tlsPassthrough)
{
CertificateId = certificateId;
EntryPort = entryPort;
EntryProtocol = entryProtocol;
TargetPort = targetPort;
TargetProtocol = targetProtocol;
TlsPassthrough = tlsPassthrough;
}
}
}
|
||||
TheStack | bd23d3f6da9d0d23078f1a664415c329844940e8 | C#code:C# | {"size": 7433, "ext": "cs", "max_stars_repo_path": "Gyomu/Models/FileTransportInfo.cs", "max_stars_repo_name": "Yoshihisa-Matsumoto/Gyomu", "max_stars_repo_stars_event_min_datetime": "2019-11-21T02:17:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-21T02:17:06.000Z", "max_issues_repo_path": "Gyomu/Models/FileTransportInfo.cs", "max_issues_repo_name": "Yoshihisa-Matsumoto/Gyomu", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gyomu/Models/FileTransportInfo.cs", "max_forks_repo_name": "Yoshihisa-Matsumoto/Gyomu", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 40.1783783784, "max_line_length": 187, "alphanum_fraction": 0.4280909458} | using System;
using System.Collections.Generic;
using System.Text;
namespace Gyomu.Models
{
public class FileTransportInfo
{
internal string SourceFileName { get; set; }
internal string SourceFolderName { get; set; }
internal string BasePath { get; private set; }
internal bool SourceIsDirectory
{
get
{
if (string.IsNullOrEmpty(SourceFileName))
return true;
return false;
}
}
internal string DestinationFileName { get; set; }
internal string DestinationFolderName { get; set; }
internal bool DestinationIsDirectory
{
get
{
if (string.IsNullOrEmpty(DestinationFileName))
return true;
return false;
}
}
internal bool DestinationIsRoot
{
get
{
if (string.IsNullOrEmpty(BasePath))
{
if (string.IsNullOrEmpty(SourceFolderName) && string.IsNullOrEmpty(DestinationFolderName))
return true;
}
else
{
if (string.IsNullOrEmpty(DestinationFolderName) && string.IsNullOrEmpty(SourceFolderName))
return true;
}
return false;
}
}
internal string SourceFullName
{
get
{
string part2 = string.IsNullOrEmpty(SourceFolderName)
? "" : SourceFolderName + System.IO.Path.DirectorySeparatorChar;
return part2 + SourceFileName;
}
}
internal string SourceFullNameWithBasePath
{
get
{
string part1 = string.IsNullOrEmpty(BasePath)
? ""
: BasePath + System.IO.Path.DirectorySeparatorChar;
return part1 + SourceFullName;
}
}
internal string DestinationFullName
{
get
{
if (string.IsNullOrEmpty(DestinationFileName) == false && string.IsNullOrEmpty(DestinationFolderName) == false)
{
return DestinationFolderName + System.IO.Path.DirectorySeparatorChar + DestinationFileName;
}
else if (string.IsNullOrEmpty(DestinationFolderName) == false)
{
if (SourceIsDirectory)
return DestinationFolderName;
else
{
return DestinationFolderName + System.IO.Path.DirectorySeparatorChar + SourceFileName;
}
}
else if (string.IsNullOrEmpty(DestinationFileName) == false)
{
if (DestinationIsRoot)
return DestinationFileName;
else
return SourceFolderName + System.IO.Path.DirectorySeparatorChar + DestinationFileName;
}
else
{
if (DestinationIsRoot)
{
if (SourceIsDirectory)
return null;
else
//return SourceFileName;
return null;
}
else
{
if (SourceIsDirectory)
return SourceFolderName;
else
return SourceFolderName;
}
} }
}
internal string DestinationFullNameWithBasePath
{
get {
string part1 = string.IsNullOrEmpty(BasePath)
? ""
: BasePath + System.IO.Path.DirectorySeparatorChar;
return part1 + DestinationFullName;
}
}
///<summary>
/// Constructor
///</summary>
///<param name="strBasePath"></param>
///<param name="srcPath"></param>
///<param name="srcFile"></param>
///<param name="destPath"></param>
///<param name="destFile"></param>
/// <remarks>
/// Base SrcPath SrcFile DestPath DestFile Where to Where
/// @ @ @ @ @ Base\SrcPath\SrcFile->DestPath\DestFile
/// @ @ @ @ Base\SrcPath\SrcFile->DestPath
/// @ @ @ @ Base\SrcPath\SrcFile->SrcPath\DestFile
/// @ @ @ Base\SrcPath\SrcFile->SrcPath
/// @ @ @ Base\SrcPath->DestFolder
/// @ @ Base\SrcPath->SrcPath
/// @ Base->Root?
/// @ @ Base->DestFolder
/// @ @ @ @ Base\SrcFile->DestPath\DestFile
/// @ @ @ Base\SrcFile->DestPath
/// @ @ @ Base\SrcFile->Root.DestFile
/// @ @ Base\SrcFile->Root
///
/// @ @ @ @ SrcPath\SrcFile->DestPath\DestFile
/// @ @ @ SrcPath\SrcFile->DestPath
/// @ @ @ SrcPath\SrcFile->Root.DestFile
/// @ @ SrcPath->DestPath
/// @ SrcPath->Root
/// @ @ @ SrcFile->DestPath\DestFile
/// @ @ SrcFile->DestPath
/// @ @ SrcFile->DestFile
/// @ SrcFile->Root
/// @ @ @ SrcFile->DestPath\DestFile
/// @ @ SrcFile->Root\DestFile
/// @ @ SrcFile->DestPath
/// </remarks>
public FileTransportInfo(string strBasePath, string srcPath, string srcFile, string destPath, string destFile,bool deleteSourceAfterProcess=false,bool overwriteDestination=false)
{
BasePath = strBasePath;
SourceFileName = srcFile;
SourceFolderName = srcPath;
DestinationFileName = destFile;
DestinationFolderName = destPath;
DeleteSourceAfterProcess = deleteSourceAfterProcess;
OverwriteDestination = overwriteDestination;
if (string.IsNullOrEmpty(DestinationFolderName))
DestinationFolderName = SourceFolderName;
if (string.IsNullOrEmpty(DestinationFileName))
DestinationFileName = SourceFileName;
}
public bool DeleteSourceAfterProcess { get; private set; }
public bool OverwriteDestination { get; private set; }
}
}
|
||||
TheStack | bd245a3f21a09c28812c797d7db316fd444cb510 | C#code:C# | {"size": 1827, "ext": "cs", "max_stars_repo_path": "Assets/VitDeck/Exporter/Addons/VRCSDK3/LinkedUdonManager.cs", "max_stars_repo_name": "VRHIKKY/VitDeck-for-vket", "max_stars_repo_stars_event_min_datetime": "2019-09-20T04:16:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:31:45.000Z", "max_issues_repo_path": "Assets/VitDeck/Exporter/Addons/VRCSDK3/LinkedUdonManager.cs", "max_issues_repo_name": "VRHIKKY/VitDeck-for-vket", "max_issues_repo_issues_event_min_datetime": "2019-04-08T07:32:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-07T04:36:39.000Z", "max_forks_repo_path": "Assets/VitDeck/Exporter/Addons/VRCSDK3/LinkedUdonManager.cs", "max_forks_repo_name": "VRHIKKY/VitDeck-for-vket", "max_forks_repo_forks_event_min_datetime": "2019-09-14T03:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T19:59:32.000Z"} | {"max_stars_count": 17.0, "max_issues_count": 131.0, "max_forks_count": 3.0, "avg_line_length": 44.5609756098, "max_line_length": 167, "alphanum_fraction": 0.6825396825} | #if VRC_SDK_VRCSDK3
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using VRC.Udon;
namespace VitDeck.Exporter.Addons.VRCSDK3
{
public class LinkedUdonManager
{
private const string _udonProgramBasePath = "Assets/SerializedUdonPrograms/";
public static string[] GetLinkedAssetPaths()
{
var paths = new List<string>();
var udonBehaviours = Resources.FindObjectsOfTypeAll<UdonBehaviour>();
foreach (var udonBehaviour in udonBehaviours)
{
if (udonBehaviour.programSource == null) continue;
var programName = udonBehaviour.programSource.SerializedProgramAsset.name;
var assetPath = _udonProgramBasePath + programName + ".asset";
var guid = AssetDatabase.AssetPathToGUID(assetPath);
if (guid != null && Array.IndexOf(_excludeGUIDs, guid) == -1)
{
paths.Add(assetPath);
}
}
return paths.ToArray();
}
private static readonly string[] _excludeGUIDs = new[]
{
"2f916e008aa8f294c991c22b42ea5944", // 73398b290b7c5ec43a2e158bfc1c45db Assets/VketAssets/UdonPrefabs/Udon_PickupObjectSync/Scripts/AutoResetPickup.asset
"2595ee2141e0fc4408caf75680ef9eb5", // 0d2cf2386895ff5499a1660a4327ad75 Assets/VketAssets/UdonPrefabs/Udon_AvatarPedestal/Scripts/AvatarPedestal.asset
"cb458453c6b8c4a4884ba5d3b2f9de56", // 6ea1e8fa7533f9647996810212fa976e Assets/VketAssets/UdonPrefabs/Udon_CirclePageOpener/Scripts/CirclePageOpener.asset
"4c879ab359f0cc54984884027c8a015e", // fe9c6cf6073f2514e82259a4142d6932 Assets/VitDeck/Templates/07_UC/SharedAssets/UC_WorldSetting.asset
};
}
}
#endif
|
||||
TheStack | bd260f8aee4c4f7ac5a935cc79bcc5ca703cd543 | C#code:C# | {"size": 313, "ext": "cs", "max_stars_repo_path": "Sample Apps/TaskRabbits/TaskRabbits/Repositories/Rabbits.cs", "max_stars_repo_name": "ronaldnsabiyera/Oak", "max_stars_repo_stars_event_min_datetime": "2015-01-05T18:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T06:37:13.000Z", "max_issues_repo_path": "Sample Apps/TaskRabbits/TaskRabbits/Repositories/Rabbits.cs", "max_issues_repo_name": "ronaldnsabiyera/Oak", "max_issues_repo_issues_event_min_datetime": "2016-01-08T01:43:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-16T15:17:12.000Z", "max_forks_repo_path": "Sample Apps/TaskRabbits/TaskRabbits/Repositories/Rabbits.cs", "max_forks_repo_name": "ronaldnsabiyera/Oak", "max_forks_repo_forks_event_min_datetime": "2015-02-08T01:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-16T13:57:48.000Z"} | {"max_stars_count": 50.0, "max_issues_count": 4.0, "max_forks_count": 23.0, "avg_line_length": 18.4117647059, "max_line_length": 44, "alphanum_fraction": 0.6517571885} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Massive;
using TaskRabbits.Models;
namespace TaskRabbits.Repositories
{
public class Rabbits : DynamicRepository
{
public Rabbits()
{
Projection = d => new Rabbit(d);
}
}
} |
||||
TheStack | bd280ce3d3a3ebeef29c6588e12230f8f59e073a | C#code:C# | {"size": 1638, "ext": "cs", "max_stars_repo_path": "UnityProject/Injecter.Unity/Assets/Injecter.Unity/IGameObjectFactory.cs", "max_stars_repo_name": "KuraiAndras/Injecter", "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:02:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T15:23:13.000Z", "max_issues_repo_path": "UnityProject/Injecter.Unity/Assets/Injecter.Unity/IGameObjectFactory.cs", "max_issues_repo_name": "KuraiAndras/Injecter", "max_issues_repo_issues_event_min_datetime": "2020-04-14T18:31:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T09:20:30.000Z", "max_forks_repo_path": "UnityProject/Injecter.Unity/Assets/Injecter.Unity/IGameObjectFactory.cs", "max_forks_repo_name": "KuraiAndras/Injecter", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 15.0, "max_issues_count": 50.0, "max_forks_count": null, "avg_line_length": 38.0930232558, "max_line_length": 109, "alphanum_fraction": 0.6556776557} | using UnityEngine;
namespace Injecter.Unity
{
public interface IGameObjectFactory
{
/// <summary>
/// Calls Object.Instantiate with the appropriate parameters
/// Injects into created instance.
/// </summary>
/// <returns>Instantiated GameObject instance</returns>
GameObject Instantiate(GameObject original);
/// <summary>
/// Calls Object.Instantiate with the appropriate parameters
/// Injects into created instance.
/// </summary>
/// <returns>Instantiated GameObject instance</returns>
GameObject Instantiate(GameObject original, Transform parent);
/// <summary>
/// Calls Object.Instantiate with the appropriate parameters
/// Injects into created instance.
/// </summary>
/// <returns>Instantiated GameObject instance</returns>
GameObject Instantiate(GameObject original, Transform parent, bool instantiateInWorldSpace);
/// <summary>
/// Calls Object.Instantiate with the appropriate parameters
/// Injects into created instance.
/// </summary>
/// <returns>Instantiated GameObject instance</returns>
GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation);
/// <summary>
/// Calls Object.Instantiate with the appropriate parameters
/// Injects into created instance.
/// </summary>
/// <returns>Instantiated GameObject instance</returns>
GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation, Transform parent);
}
}
|
||||
TheStack | bd2918430be45c434fbea9f1faaaa9477011710f | C#code:C# | {"size": 5597, "ext": "cs", "max_stars_repo_path": "Assets/QFramework/Framework/2.ResKit/1.ResSystem/Editor/AssetBundleExporter.cs", "max_stars_repo_name": "alexddhuang/QFramework", "max_stars_repo_stars_event_min_datetime": "2019-10-23T10:54:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T10:54:59.000Z", "max_issues_repo_path": "Assets/QFramework/Framework/2.ResKit/1.ResSystem/Editor/AssetBundleExporter.cs", "max_issues_repo_name": "alexddhuang/QFramework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/QFramework/Framework/2.ResKit/1.ResSystem/Editor/AssetBundleExporter.cs", "max_forks_repo_name": "alexddhuang/QFramework", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.2012578616, "max_line_length": 130, "alphanum_fraction": 0.5872788994} | /****************************************************************************
* Copyright (c) 2017 snowcold
* Copyright (c) 2017 ~ 2018.5 liangxie
*
* http://qframework.io
* https://github.com/liangxiegame/QFramework
*
* 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 UnityEditor;
using System.Collections.Generic;
using System.IO;
using QF.Extensions;
using QFramework;
namespace QF.Res
{
public static class AssetBundleExporter
{
public static void BuildDataTable()
{
Log.I("Start BuildAssetDataTable!");
ResDatas table = ResDatas.Create();
ProcessAssetBundleRes(table);
var filePath =
(FilePath.StreamingAssetsPath + ResKitUtil.RELATIVE_AB_ROOT_FOLDER).CreateDirIfNotExists() +
ResKitUtil.EXPORT_ASSETBUNDLE_CONFIG_FILENAME;
table.Save(filePath);
AssetDatabase.Refresh ();
}
#region 指定具体文件构建
public static void BuildAssetBundlesInSelectFolder()
{
var selectPath = EditorUtils.GetSelectedDirAssetsPath();//.CurrentSelectFolder;
if (selectPath == null)
{
Log.W("Not Select Any Folder!");
return;
}
BuildAssetBundlesInFolder(selectPath);
}
private static void BuildAssetBundlesInFolder(string folderPath)
{
if (folderPath == null)
{
Log.W("Folder Path Is Null.");
return;
}
Log.I("Start Build AssetBundle:" + folderPath);
var fullFolderPath = EditorUtils.AssetsPath2ABSPath(folderPath);//EditUtils.GetFullPath4AssetsPath(folderPath);
var assetBundleName = EditorUtils.AssetPath2ReltivePath(folderPath);// EditUtils.GetReltivePath4AssetPath(folderPath);
var filePaths = Directory.GetFiles(fullFolderPath);
AssetBundleBuild abb = new AssetBundleBuild();
abb.assetBundleName = assetBundleName;
List<string> fileNameList = new List<string>();
foreach (var filePath in filePaths)
{
if (!filePath.EndsWith(".meta"))
{
continue;
}
var fileName = Path.GetFileName(filePath);
fileName = string.Format("{0}/{1}", folderPath, fileName);
fileNameList.Add(fileName);
}
if (fileNameList.Count <= 0)
{
Log.W("Not Find Asset In Folder:" + folderPath);
return;
}
abb.assetNames = fileNameList.ToArray();
BuildPipeline.BuildAssetBundles(ResKitUtil.EDITOR_AB_EXPORT_ROOT_FOLDER,
new[] { abb },
BuildAssetBundleOptions.ChunkBasedCompression,
BuildTarget.StandaloneWindows);
}
#endregion
#region 构建 AssetDataTable
private static string AssetPath2Name(string assetPath)
{
int startIndex = assetPath.LastIndexOf("/") + 1;
int endIndex = assetPath.LastIndexOf(".");
if (endIndex > 0)
{
int length = endIndex - startIndex;
return assetPath.Substring(startIndex, length).ToLower();
}
return assetPath.Substring(startIndex).ToLower();
}
private static void ProcessAssetBundleRes(ResDatas table)
{
AssetDataGroup group = null;
AssetDatabase.RemoveUnusedAssetBundleNames();
string[] abNames = AssetDatabase.GetAllAssetBundleNames();
if (abNames != null && abNames.Length > 0)
{
foreach (var abName in abNames)
{
var depends = AssetDatabase.GetAssetBundleDependencies(abName, false);
var abIndex = table.AddAssetBundleName(abName, depends, out @group);
if (abIndex < 0)
{
continue;
}
var assets = AssetDatabase.GetAssetPathsFromAssetBundle(abName);
foreach (var cell in assets)
{
@group.AddAssetData(cell.EndsWith(".unity")
? new AssetData(AssetPath2Name(cell), ResType.ABScene, abIndex, abName)
: new AssetData(AssetPath2Name(cell), ResType.ABAsset, abIndex, abName));
}
}
}
}
#endregion
}
}
|
||||
TheStack | bd2a5abf48d3abdfe7d1d49a5ea84d72d6ca1af4 | C#code:C# | {"size": 7244, "ext": "cs", "max_stars_repo_path": "Source/DontShootTheDead/DontShootTheDead.cs", "max_stars_repo_name": "mad2342/DontShootTheDead", "max_stars_repo_stars_event_min_datetime": "2019-06-09T08:52:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T23:13:19.000Z", "max_issues_repo_path": "Source/DontShootTheDead/DontShootTheDead.cs", "max_issues_repo_name": "mad2342/DontShootTheDead", "max_issues_repo_issues_event_min_datetime": "2019-04-14T20:50:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-30T06:34:45.000Z", "max_forks_repo_path": "Source/DontShootTheDead/DontShootTheDead.cs", "max_forks_repo_name": "mad2342/DontShootTheDead", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 4.0, "max_issues_count": 3.0, "max_forks_count": null, "avg_line_length": 38.328042328, "max_line_length": 175, "alphanum_fraction": 0.6369409166} | using System.Reflection;
using Harmony;
using BattleTech;
using System.IO;
using System.Collections.Generic;
using DontShootTheDead.Extensions;
namespace DontShootTheDead
{
public class DontShootTheDead
{
internal static string LogPath;
internal static string ModDirectory;
internal static bool BuildSupportWeaponSequence = false;
// BEN: DebugLevel (0: nothing, 1: error, 2: debug, 3: info)
internal static int DebugLevel = 1;
public static void Init(string directory, string settings)
{
ModDirectory = directory;
LogPath = Path.Combine(ModDirectory, "DontShootTheDead.log");
Logger.Initialize(LogPath, DebugLevel, ModDirectory, nameof(DontShootTheDead));
HarmonyInstance harmony = HarmonyInstance.Create("de.mad.DontShootTheDead");
harmony.PatchAll(Assembly.GetExecutingAssembly());
}
}
[HarmonyPatch(typeof(MechMeleeSequence), "ExecuteMelee")]
public static class MechMeleeSequence_ExecuteMelee_Patch
{
public static void Prefix(MechMeleeSequence __instance)
{
// Reset flag for weapon sequence
DontShootTheDead.BuildSupportWeaponSequence = false;
}
}
[HarmonyPatch(typeof(MechDFASequence), "ExecuteMelee")]
public static class MechDFASequence_ExecuteMelee_Patch
{
public static void Prefix(MechDFASequence __instance)
{
// Reset flag for weapon sequence
DontShootTheDead.BuildSupportWeaponSequence = false;
}
}
[HarmonyPatch(typeof(MechMeleeSequence), "BuildWeaponDirectorSequence")]
public static class MechMeleeSequence_BuildWeaponDirectorSequence_Patch
{
public static bool Prefix(MechMeleeSequence __instance, ref List<Weapon> ___requestedWeapons)
{
Logger.Info("[MechMeleeSequence_BuildWeaponDirectorSequence_PREFIX] DontShootTheDead.BuildSupportWeaponSequence: " + DontShootTheDead.BuildSupportWeaponSequence);
// Only build a weapon sequence if melee didn't already kill the target
if (DontShootTheDead.BuildSupportWeaponSequence)
{
// Will still only build a weapon sequence if ___requestedWeapons.Count is > 0
return true;
}
else
{
// This always needs to be done for a melee attack
___requestedWeapons.RemoveAll((Weapon x) => x.Type == WeaponType.Melee);
return false;
}
}
}
[HarmonyPatch(typeof(MechDFASequence), "BuildWeaponDirectorSequence")]
public static class MechDFASequence_BuildWeaponDirectorSequence_Patch
{
public static bool Prefix(MechDFASequence __instance, ref List<Weapon> ___requestedWeapons)
{
Logger.Info("[MechDFASequence_BuildWeaponDirectorSequence_PREFIX] DontShootTheDead.BuildSupportWeaponSequence: " + DontShootTheDead.BuildSupportWeaponSequence);
// Only build a weapon sequence if melee didn't already kill the target
if (DontShootTheDead.BuildSupportWeaponSequence)
{
// Will still only build a weapon sequence if ___requestedWeapons.Count is > 0
return true;
}
else
{
return false;
}
}
}
[HarmonyPatch(typeof(MechMeleeSequence), "OnMeleeComplete")]
public static class MechMeleeSequence_OnMeleeComplete_Patch
{
public static void Prefix(MechMeleeSequence __instance, ref List<Weapon> ___requestedWeapons)
{
if (___requestedWeapons.Count < 1)
{
return;
}
AbstractActor actor = __instance.owningActor;
ICombatant MeleeTarget = __instance.MeleeTarget;
bool TargetIsDead = MeleeTarget.IsDead;
bool TargetIsFlaggedForDeath = MeleeTarget.IsFlaggedForDeath;
Logger.Info("[MechMeleeSequence_OnMeleeComplete_PREFIX] TargetIsDead: " + TargetIsDead);
Logger.Info("[MechMeleeSequence_OnMeleeComplete_PREFIX] TargetIsFlaggedForDeath: " + TargetIsFlaggedForDeath);
if (TargetIsDead || TargetIsFlaggedForDeath)
{
___requestedWeapons.Clear();
actor.Combat.MessageCenter.PublishMessage(new FloatieMessage(actor.GUID, actor.GUID, "SUSPENDED SUPPORT WEAPONS", FloatieMessage.MessageNature.Neutral));
}
else
{
DontShootTheDead.BuildSupportWeaponSequence = true;
Traverse BuildWeaponDirectorSequence = Traverse.Create(__instance).Method("BuildWeaponDirectorSequence");
BuildWeaponDirectorSequence.GetValue();
}
}
}
[HarmonyPatch(typeof(MechDFASequence), "OnMeleeComplete")]
public static class MechDFASequence_OnMeleeComplete_Patch
{
public static void Prefix(MechDFASequence __instance, ref List<Weapon> ___requestedWeapons)
{
if (___requestedWeapons.Count < 1)
{
return;
}
AbstractActor actor = __instance.owningActor;
ICombatant MeleeTarget = __instance.DFATarget;
bool TargetIsDead = MeleeTarget.IsDead;
bool TargetIsFlaggedForDeath = MeleeTarget.IsFlaggedForDeath;
Logger.Info("[MechMeleeSequence_OnMeleeComplete_PREFIX] TargetIsDead: " + TargetIsDead);
Logger.Info("[MechMeleeSequence_OnMeleeComplete_PREFIX] TargetIsFlaggedForDeath: " + TargetIsFlaggedForDeath);
if (TargetIsDead || TargetIsFlaggedForDeath)
{
___requestedWeapons.Clear();
actor.Combat.MessageCenter.PublishMessage(new FloatieMessage(actor.GUID, actor.GUID, "SUSPENDED SUPPORT WEAPONS", FloatieMessage.MessageNature.Neutral));
}
else
{
DontShootTheDead.BuildSupportWeaponSequence = true;
Traverse BuildWeaponDirectorSequence = Traverse.Create(__instance).Method("BuildWeaponDirectorSequence");
BuildWeaponDirectorSequence.GetValue();
}
}
}
[HarmonyPatch(typeof(MechMeleeSequence), "DelayFireWeapons")]
public static class MechMeleeSequence_DelayFireWeapons_Patch
{
public static void Prefix(MechMeleeSequence __instance, ref float timeout)
{
// Was a hardcoded 5f
timeout = 3f;
Logger.Debug("[MechMeleeSequence_DelayFireWeapons_PREFIX] timeout: " + timeout);
}
}
[HarmonyPatch(typeof(MechDFASequence), "DelayFireWeapons")]
public static class MechDFASequence_DelayFireWeapons_Patch
{
public static void Prefix(MechDFASequence __instance, ref float timeout)
{
// Was a hardcoded 10f
timeout = 6f;
Logger.Debug("[MechDFASequence_DelayFireWeapons_PREFIX] timeout: " + timeout);
}
}
}
|
||||
TheStack | bd2ad50ef52b7a039ba9c9fee7d42115b834d819 | C#code:C# | {"size": 904, "ext": "cs", "max_stars_repo_path": "src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs", "max_stars_repo_name": "bharanijayasuri/umbraco8", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs", "max_issues_repo_name": "bharanijayasuri/umbraco8", "max_issues_repo_issues_event_min_datetime": "2017-06-30T19:46:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-25T11:04:50.000Z", "max_forks_repo_path": "src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs", "max_forks_repo_name": "bharanijayasuri/umbraco8", "max_forks_repo_forks_event_min_datetime": "2018-03-06T09:19:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-06T09:19:52.000Z"} | {"max_stars_count": null, "max_issues_count": 3.0, "max_forks_count": 1.0, "avg_line_length": 28.25, "max_line_length": 115, "alphanum_fraction": 0.7157079646} | using System;
using System.ComponentModel;
using Umbraco.Core.Cache;
namespace Umbraco.Web.Cache
{
[Obsolete("This is no longer used and will be removed from the codebase in the future")]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class UserGroupPermissionsCacheRefresher : CacheRefresherBase<UserGroupPermissionsCacheRefresher>
{
public UserGroupPermissionsCacheRefresher(CacheHelper cacheHelper)
: base(cacheHelper)
{ }
#region Define
protected override UserGroupPermissionsCacheRefresher This => this;
public static readonly Guid UniqueId = Guid.Parse("840AB9C5-5C0B-48DB-A77E-29FE4B80CD3A");
public override Guid RefresherUniqueId => UniqueId;
public override string Name => "User Group Permissions Cache Refresher";
#endregion
#region Refresher
#endregion
}
}
|
||||
TheStack | bd2c54cdaef0c0dab03dc8795d717822bf0f1d2a | C#code:C# | {"size": 1227, "ext": "cs", "max_stars_repo_path": "sample/Hello/Program.cs", "max_stars_repo_name": "lc8882972/RateLimiters", "max_stars_repo_stars_event_min_datetime": "2018-08-10T13:36:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-10T13:36:35.000Z", "max_issues_repo_path": "sample/Hello/Program.cs", "max_issues_repo_name": "lc8882972/RateLimiters", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/Hello/Program.cs", "max_forks_repo_name": "lc8882972/RateLimiters", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.8863636364, "max_line_length": 77, "alphanum_fraction": 0.533007335} | using Bert.RateLimiters;
using System;
namespace Hello
{
class Program
{
static void Main(string[] args)
{
// int x =10;
IThrottleStrategy strategy = new FixedTokenBucket(100, 10, 1000);
Throttler throttle = new Throttler(strategy);
if (!throttle.CanConsume())
{
Console.WriteLine("CanConsume");
}
// 策略模式
Context context = new Context(new ConcreateStrategyA());
context.ContextInterfact();
// 备忘录模式
Originator originator = new Originator();
originator.State = "on";
originator.Show();
Caretaker caretaker = new Caretaker();
caretaker.Memento = originator.CreateMemento();
originator.State = "off";
originator.Show();
originator.SetMemento(caretaker.Memento);
originator.Show();
// 命令模式
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoke invoke = new Invoke(command);
invoke.Execute();
Console.WriteLine("Hello World!");
}
}
} |
||||
TheStack | bd2daed8df54a482e287e5c357e043c499a8b0fd | C#code:C# | {"size": 7085, "ext": "cs", "max_stars_repo_path": "EspionSpotify.Tests/SpotifyHandlerTests.cs", "max_stars_repo_name": "1242637/spy-spotify", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EspionSpotify.Tests/SpotifyHandlerTests.cs", "max_issues_repo_name": "1242637/spy-spotify", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EspionSpotify.Tests/SpotifyHandlerTests.cs", "max_forks_repo_name": "1242637/spy-spotify", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.1074766355, "max_line_length": 100, "alphanum_fraction": 0.5648553282} | using EspionSpotify.Events;
using EspionSpotify.Models;
using EspionSpotify.Spotify;
using System.Threading.Tasks;
using System.Timers;
using Xunit;
namespace EspionSpotify.Tests
{
public class SpotifyHandlerTests
{
[Fact]
private void SpotifyHandler_ReturnsSpotifyProcess()
{
var spotifyProcessMock = new Moq.Mock<ISpotifyProcess>();
var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object)
{
ListenForEvents = true
};
Assert.True(spotifyHandler.ListenForEvents);
Assert.Same(spotifyProcessMock.Object, spotifyHandler.SpotifyProcess);
}
[Fact]
private void Dispose_ReturnsTimerOff()
{
var spotifyProcessMock = new Moq.Mock<ISpotifyProcess>();
var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object);
spotifyHandler.Dispose();
Assert.False(spotifyHandler.EventTimer.Enabled);
Assert.False(spotifyHandler.SongTimer.Enabled);
}
[Fact]
private async void TickEventSpotifyIdling_ReturnsNoEvent()
{
var track = new Track();
var spotifyStatusMock = new Moq.Mock<ISpotifyStatus>();
spotifyStatusMock.Setup(x => x.CurrentTrack).Returns(track);
spotifyStatusMock.Setup(x => x.GetTrack()).Returns(track);
var spotifyProcessMock = new Moq.Mock<ISpotifyProcess>();
spotifyProcessMock.Setup(x => x.GetSpotifyStatus()).Returns(spotifyStatusMock.Object);
var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object)
{
ListenForEvents = true
};
spotifyHandler.SongTimer.Start();
var eventPlaying = false;
spotifyHandler.OnPlayStateChange += delegate (object sender, PlayStateEventArgs e)
{
eventPlaying = e.Playing;
};
Track eventNewTrack = null;
Track eventOldTrack = null;
spotifyHandler.OnTrackChange += delegate (object sender, TrackChangeEventArgs e)
{
eventNewTrack = e.NewTrack;
eventOldTrack = e.OldTrack;
};
int? eventTrackTime = null;
spotifyHandler.OnTrackTimeChange += delegate (object sender, TrackTimeChangeEventArgs e)
{
eventTrackTime = e.TrackTime;
};
// initial track
Assert.Null(spotifyHandler.Track);
await Task.Delay(500);
// updated track
Assert.Equal(track, spotifyHandler.Track);
// events
Assert.False(eventPlaying);
Assert.Null(eventNewTrack);
Assert.Null(eventOldTrack);
Assert.Equal(0, eventTrackTime);
}
[Fact]
private async void NewTrack_ReturnsAllEvents()
{
var previousTrack = new Track();
var currentTrack = new Track
{
Title = "Song Title",
Artist = "Artist Name",
Ad = false,
Playing = true,
TitleExtended = "Live"
};
var spotifyStatusMock = new Moq.Mock<ISpotifyStatus>();
spotifyStatusMock.Setup(x => x.CurrentTrack).Returns(currentTrack);
spotifyStatusMock.Setup(x => x.GetTrack()).Returns(currentTrack);
var spotifyProcessMock = new Moq.Mock<ISpotifyProcess>();
spotifyProcessMock.Setup(x => x.GetSpotifyStatus()).Returns(spotifyStatusMock.Object);
var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object)
{
ListenForEvents = true,
Track = previousTrack
};
var eventPlaying = false;
spotifyHandler.OnPlayStateChange += delegate (object sender, PlayStateEventArgs e)
{
eventPlaying = e.Playing;
};
Track eventNewTrack = null;
Track eventOldTrack = null;
spotifyHandler.OnTrackChange += delegate (object sender, TrackChangeEventArgs e)
{
eventNewTrack = e.NewTrack;
eventOldTrack = e.OldTrack;
};
int? eventTrackTime = null;
spotifyHandler.OnTrackTimeChange += delegate (object sender, TrackTimeChangeEventArgs e)
{
eventTrackTime = e.TrackTime;
};
// initial track
Assert.Equal(previousTrack, spotifyHandler.Track);
await Task.Delay(500);
// updated track
Assert.Equal(currentTrack, spotifyHandler.Track);
// events
Assert.True(eventPlaying);
Assert.Equal(currentTrack, eventNewTrack);
Assert.Equal(previousTrack, eventOldTrack);
Assert.Equal(0, eventTrackTime);
}
[Fact]
private async void TickEventSameTrackPlaying_ReturnsTrackTimeEvent()
{
var track = new Track
{
Title = "Song Title",
Artist = "Artist Name",
Ad = false,
Playing = true,
TitleExtended = "Live"
};
var spotifyStatusMock = new Moq.Mock<ISpotifyStatus>();
spotifyStatusMock.Setup(x => x.CurrentTrack).Returns(track);
spotifyStatusMock.Setup(x => x.GetTrack()).Returns(track);
var spotifyProcessMock = new Moq.Mock<ISpotifyProcess>();
spotifyProcessMock.Setup(x => x.GetSpotifyStatus()).Returns(spotifyStatusMock.Object);
var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object)
{
ListenForEvents = true,
Track = track
};
spotifyHandler.SongTimer.Start();
var eventPlaying = false;
spotifyHandler.OnPlayStateChange += delegate (object sender, PlayStateEventArgs e)
{
eventPlaying = e.Playing;
};
Track eventNewTrack = null;
Track eventOldTrack = null;
spotifyHandler.OnTrackChange += delegate (object sender, TrackChangeEventArgs e)
{
eventNewTrack = e.NewTrack;
eventOldTrack = e.OldTrack;
};
int? eventTrackTime = null;
spotifyHandler.OnTrackTimeChange += delegate(object sender, TrackTimeChangeEventArgs e)
{
eventTrackTime = e.TrackTime;
};
// initial track
Assert.Equal(track, spotifyHandler.Track);
await Task.Delay(1500);
// updated track
Assert.Equal(track, spotifyHandler.Track);
// events
Assert.False(eventPlaying);
Assert.Null(eventNewTrack);
Assert.Null(eventOldTrack);
Assert.Equal(1, eventTrackTime);
}
}
}
|
||||
TheStack | bd2db7dd62ae0053ad50a9d268de52f8c1188ff7 | C#code:C# | {"size": 4374, "ext": "cs", "max_stars_repo_path": "Scribble.Functions/Functions/GameFunctions.cs", "max_stars_repo_name": "Bjorneer/serverless-scribble", "max_stars_repo_stars_event_min_datetime": "2020-11-27T18:24:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-27T18:24:57.000Z", "max_issues_repo_path": "Scribble.Functions/Functions/GameFunctions.cs", "max_issues_repo_name": "Bjorneer/serverless-scribble", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scribble.Functions/Functions/GameFunctions.cs", "max_forks_repo_name": "Bjorneer/serverless-scribble", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.7079646018, "max_line_length": 167, "alphanum_fraction": 0.6019661637} | using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Scribble.Functions.Models;
using Scribble.Functions.Requests;
using Scribble.Functions.Responses;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Scribble.Functions.Functions
{
public static class GameFunctions
{
[FunctionName("draw")]
public static async Task<ActionResult> Draw(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
[DurableClient] IDurableOrchestrationClient client,
[SignalR(HubName = "game")] IAsyncCollector<SignalRMessage> signalRMessages)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var data = JsonConvert.DeserializeObject<DrawRequest>(requestBody);
if (data.GameCode == null)
return new BadRequestResult();
var status = await client.GetStatusAsync("g" + data.GameCode);
if (status == null)
return new NotFoundResult();
if (status.RuntimeStatus != OrchestrationRuntimeStatus.Running)
return new BadRequestResult();
var state = status.CustomStatus.ToObject<RoundState>();
if (state == null)
return new BadRequestResult();
if (state.PainterId != data.PlayerID)
return new BadRequestResult();
await signalRMessages.AddAsync(new SignalRMessage
{
GroupName = data.GameCode,
Target = "draw",
Arguments = new[] { data.DrawObjects }
});
return new OkResult();
}
[FunctionName("guess")]
public static async Task<IActionResult> Guess(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
[DurableClient] IDurableOrchestrationClient client,
[SignalR(HubName = "game")] IAsyncCollector<SignalRMessage> signalRMessages)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var data = JsonConvert.DeserializeObject<GuessRequest>(requestBody);
if (data.GameCode == null ||data.Guess == null || data.Guess.Length > 35)
return new BadRequestResult();
var status = await client.GetStatusAsync("g" + data.GameCode);
if (status == null)
return new NotFoundResult();
if (status.RuntimeStatus != OrchestrationRuntimeStatus.Running)
return new BadRequestResult();
var state = status.CustomStatus.ToObject<RoundState>();
if (state == null || !state.Players.Any(p => p.ID == data.PlayerID && p.IsCorrect == false) || state.PainterId == data.PlayerID)
return new BadRequestResult();
if (state.Word.ToLower() != data.Guess.ToLower())
{
await signalRMessages.AddAsync(new SignalRMessage
{
GroupName = data.GameCode,
Target = "inMessage",
Arguments = new[] { new MessageItem {User=state.Players.First(p =>p.ID == data.PlayerID).UserName, Message = data.Guess } }
});
return new BadRequestResult();
}
await client.RaiseEventAsync("g" + data.GameCode, "CorrectGuess", data.PlayerID);
await signalRMessages.AddAsync(new SignalRMessage
{
GroupName = data.GameCode,
Target = "guessCorrect",
Arguments = new[] { state.Players.First(p => p.ID == data.PlayerID).UserName }
});
await signalRMessages.AddAsync(new SignalRMessage
{
GroupName = data.GameCode,
Target = "inMessage",
Arguments = new[] { new MessageItem { User = "GAME_EVENT", Message = $"{state.Players.First(p => p.ID == data.PlayerID).UserName} guessed correctly"} }
});
return new OkResult();
}
}
}
|
||||
TheStack | bd2e1b8854c7a00fe91fb28a922360381fc17b05 | C#code:C# | {"size": 379, "ext": "cs", "max_stars_repo_path": "src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs", "max_stars_repo_name": "albertosam/Ocelot", "max_stars_repo_stars_event_min_datetime": "2021-05-01T02:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-01T17:27:00.000Z", "max_issues_repo_path": "src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs", "max_issues_repo_name": "MykhailoKyrychenko/Ocelot", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs", "max_forks_repo_name": "MykhailoKyrychenko/Ocelot", "max_forks_repo_forks_event_min_datetime": "2021-03-11T09:27:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T09:27:11.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 25.2666666667, "max_line_length": 62, "alphanum_fraction": 0.6279683377} | using Ocelot.Values;
namespace Ocelot.LoadBalancer.LoadBalancers
{
public class Lease
{
public Lease(HostAndPort hostAndPort, int connections)
{
HostAndPort = hostAndPort;
Connections = connections;
}
public HostAndPort HostAndPort { get; private set; }
public int Connections { get; private set; }
}
} |
||||
TheStack | bd2f4650374f934e5167e2252a794e6963b51a80 | C#code:C# | {"size": 296, "ext": "cs", "max_stars_repo_path": "netcore/tests/Koralium.SqlToExpression.Tests/Models/ObjectTest.cs", "max_stars_repo_name": "rs-swc/Koralium", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "netcore/tests/Koralium.SqlToExpression.Tests/Models/ObjectTest.cs", "max_issues_repo_name": "rs-swc/Koralium", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "netcore/tests/Koralium.SqlToExpression.Tests/Models/ObjectTest.cs", "max_forks_repo_name": "rs-swc/Koralium", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 18.5, "max_line_length": 52, "alphanum_fraction": 0.6655405405} | using System;
using System.Collections.Generic;
using System.Text;
namespace Koralium.SqlToExpression.Tests.Models
{
public class InnerObject
{
public string Name { get; set; }
}
public class ObjectTest
{
public InnerObject InnerObject { get; set; }
}
}
|
||||
TheStack | bd317927fd5c2cce95e80b7679a1b40f09bac145 | C#code:C# | {"size": 13928, "ext": "cs", "max_stars_repo_path": "WhatSearch/Controllers/UploadController.cs", "max_stars_repo_name": "uni2tw/WhatSearch", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WhatSearch/Controllers/UploadController.cs", "max_issues_repo_name": "uni2tw/WhatSearch", "max_issues_repo_issues_event_min_datetime": "2021-03-05T04:30:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T04:30:18.000Z", "max_forks_repo_path": "WhatSearch/Controllers/UploadController.cs", "max_forks_repo_name": "uni2tw/WhatSearch", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 33.8880778589, "max_line_length": 110, "alphanum_fraction": 0.4292073521} | using log4net;
using log4net.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Threading;
using WhatSearch.Core;
using WhatSearch.Utility;
namespace WhatSearch.Controllers
{
public class UploadController : Controller
{
static SystemConfig config = Ioc.GetConfig();
static ILog logger = LogManager.GetLogger(typeof(UploadController));
public long LimitMb
{
get
{
return config.Upload.LimitMb ?? 200;
}
}
static UploadController()
{
//10分鐘清一次
System.Timers.Timer timer = new System.Timers.Timer(1000 * 60 * 10);
timer.AutoReset = false;
timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e)
{
try
{
RemoveOldFiles();
}
catch
{
}
finally
{
(sender as System.Timers.Timer).Start();
}
};
timer.Start();
}
public static void RemoveOldFiles()
{
DirectoryInfo diTemp = GetWorkTempFolder(null);
DateTime now = DateTime.Now;
{
foreach (var dirInfo in diTemp.GetDirectories())
{
if (dirInfo != null)
{
foreach (var fi2 in dirInfo.GetFiles())
{
DateTime lastWriteTime;
if (UploadUtil.CheckFileIsOld(fi2, out lastWriteTime))
{
logger.InfoFormat("Delete(1) {0} - {1}",
fi2.FullName, lastWriteTime.ToString("yyyy-MM-dd HH:mm"));
fi2.Delete();
}
}
if (dirInfo.GetFileSystemInfos("*.*", SearchOption.AllDirectories).Length == 0)
{
logger.Info("Delete(2) " + dirInfo.FullName);
//dirInfo.Delete();
}
}
}
}
DirectoryInfo diWork = GetWorkFolder(null);
{
foreach (var fsi in diWork.GetFileSystemInfos())
{
var diWorkSub = fsi as DirectoryInfo;
if (diWorkSub != null)
{
foreach (var fi2 in diWorkSub.GetFiles())
{
DateTime lastWriteTime;
if (UploadUtil.CheckFileIsOld(fi2, out lastWriteTime))
{
logger.Info("Delete(4) " + fi2.FullName);
fi2.Delete();
}
}
if (diWorkSub.GetFileSystemInfos("*.*", SearchOption.AllDirectories).Length == 0)
{
logger.Info("Delete(5) " + diWorkSub.FullName);
//diWorkSub.Delete();
}
}
else
{
DateTime lastWriteTime;
if (UploadUtil.CheckFileIsOld(fsi, out lastWriteTime))
{
logger.Info("Delete(6) " + fsi.FullName);
fsi.Delete();
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[Route("{secret}/upload")]
[Route("upload")]
public IActionResult List([FromRoute]Guid? secret)
{
string errorMessage;
if (IsEnabled(out errorMessage) == false)
{
return Content(errorMessage);
}
DirectoryInfo di = GetWorkFolder(secret);
DateTime now = DateTime.Now;
List<FileInfo> fiInfos = new List<FileInfo>();
if (di.Exists)
{
fiInfos.AddRange(di.GetFiles().OrderByDescending(t => t.CreationTime));
}
List<FileDownloadInfoModel> files = new List<FileDownloadInfoModel>();
foreach (var fi in fiInfos)
{
TimeSpan deleteAfter;
if (UploadUtil.CheckFileIsOld(fi, out deleteAfter))
{
fi.Delete();
continue;
}
files.Add(new FileDownloadInfoModel
{
Title = fi.Name,
Id = fi.Name,
Size = Helper.GetReadableByteSize(fi.Length),
Time = fi.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
DeleteAfter = Helper.GetReadableTimeSpan(deleteAfter)
});
}
ViewBag.LimitMb = LimitMb;
ViewBag.Secret = secret?.ToString();
ViewBag.Items = files;
return View();
}
private static DirectoryInfo GetWorkFolder(Guid? secret)
{
DirectoryInfo result;
if (secret == null)
{
result = new DirectoryInfo(Path.Combine(config.Upload.Folder, "work"));
}
else
{
result = new DirectoryInfo(Path.Combine(config.Upload.Folder, "work", secret.ToString()));
}
if (result.Exists == false)
{
result.Create();
}
return result;
}
private static DirectoryInfo GetWorkTempFolder(Guid? secret)
{
DirectoryInfo result;
string tempRootPath = Path.Combine(config.Upload.Folder, "temp");
if (secret == null)
{
result = new DirectoryInfo(Path.Combine(config.Upload.Folder, "temp"));
}
else
{
result = new DirectoryInfo(Path.Combine(config.Upload.Folder, "temp",secret.ToString()));
}
if (result.Exists == false)
{
result.Create();
}
return result;
}
[HttpGet]
[Route("upload/secret")]
public IActionResult CreateSecret()
{
return Redirect(string.Format("/{0}/upload", Guid.NewGuid().ToString()));
}
/// <summary>
///
/// </summary>
/// <param name="file_name"></param>
/// <returns></returns>
[HttpPost]
[Route("upload/status")]
[Route("upload/{secret}/status")]
public dynamic Status(string file_name, [FromRoute]Guid? secret)
{
var tempFolder = GetWorkTempFolder(secret);
if (tempFolder.Exists == false)
{
tempFolder.Create();
}
string filePath = Path.Combine(tempFolder.FullName, file_name);
if (System.IO.File.Exists(filePath))
{
return Ok(new
{
file = file_name,
loc = "temp",
len = new FileInfo(filePath).Length,
message = string.Format("先前上傳的檔案 {0} 未完成,你想要續傳嗎 ?", file_name)
});
}
var workFolder = GetWorkFolder(secret);
if (workFolder.Exists == false)
{
workFolder.Create();
}
filePath = Path.Combine(workFolder.FullName, file_name);
if (System.IO.File.Exists(filePath))
{
return Ok(new
{
file = file_name,
loc = "folder",
len = new FileInfo(filePath).Length,
message = string.Format("檔案 {0} 已存在,你要重新上傳嗎 ?", file_name)
});
}
return Ok(new
{
file = file_name,
loc = string.Empty,
len = 0,
message = string.Empty
});
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <param name="file_name"></param>
/// <returns></returns>
[HttpPost]
[Route("upload/post")]
[Route("upload/{secret}/post")]
public dynamic PostFile(IFormFile file, bool is_start, bool is_end, string file_name,
[FromRoute] Guid? secret)
{
string errorMessage;
if (IsEnabled(out errorMessage) == false)
{
return Content(errorMessage);
}
try
{
string filePath = Path.Combine(GetWorkTempFolder(secret).FullName, file_name);
FileStream fs;
if (is_start)
{
fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
}
else
{
fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
}
file.CopyTo(fs);
long fileLen = fs.Length;
fs.Close();
if (fileLen > 1024 * 1024 * LimitMb)
{
try
{
System.IO.File.Delete(filePath);
}
catch
{
}
return BadRequest(string.Format("發生錯誤, 檔案超過限制 {0} MB",
LimitMb));
}
if (is_end)
{
string destFilePath = Path.Combine(GetWorkFolder(secret).FullName, file_name);
try
{
logger.InfoFormat("檔案搬動中 from={0} to={1}",
filePath,
destFilePath);
System.IO.File.Move(filePath, destFilePath, true);
}
catch(Exception ex)
{
try
{
logger.WarnFormat("檔案因異外被刪除了 from={0} to={1}, ex={2}",
filePath,
destFilePath,
ex);
System.IO.File.Delete(filePath);
}
catch
{
}
return BadRequest("檔案正在被使用,無法覆蓋");
}
}
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("upload/{secret}/file/{*pathInfo}")]
[Route("upload/file/{*pathInfo}")]
public dynamic GetUploadFile(string pathInfo, Guid? secret)
{
string errorMessage;
if (IsEnabled(out errorMessage) == false)
{
return Content(errorMessage);
}
string targetPath = Path.Combine(GetWorkFolder(secret).FullName, pathInfo);
if (System.IO.File.Exists(targetPath) == false)
{
return NotFound();
}
string extension = Path.GetExtension(targetPath).ToLower();
string mimeType = null;
if (extension == ".png")
{
mimeType = "image/png";
}
else if (extension == ".jpg" || extension == ".jepg")
{
mimeType = "image/jpeg";
}
else
{
mimeType = "application/octet-stream";
}
return this.PhysicalFile(targetPath, mimeType);
}
private bool IsEnabled(out string message)
{
message = string.Empty;
if (config.Upload == null || config.Upload.Enabled == false)
{
message = "上傳功能未啟用";
return false;
}
if (string.IsNullOrEmpty(config.Upload.Folder) || Directory.Exists(config.Upload.Folder) == false)
{
message = "路徑參數未設定正確 Folder, TempFolder";
return false;
}
return true;
}
public class FileDownloadInfoModel
{
public string Id { get; set; }
public string Title { get; set; }
public string Size { get; set; }
public string Time { get; set; }
public string DeleteAfter { get; set; }
}
}
public class UploadUtil
{
public static bool CheckFileIsOld(FileSystemInfo fi, out DateTime lastWriteTime)
{
lastWriteTime = fi.CreationTime > fi.LastWriteTime ? fi.CreationTime : fi.LastWriteTime;
return (DateTime.Now - lastWriteTime).TotalDays >= 3;
}
public static bool CheckFileIsOld(FileSystemInfo fi, out TimeSpan delteAfter)
{
DateTime lastWriteTime = fi.CreationTime > fi.LastWriteTime ? fi.CreationTime : fi.LastWriteTime;
delteAfter = DateTime.Now - lastWriteTime;
return delteAfter.TotalDays >= 3;
}
}
}
|
||||
TheStack | bd326d7aa679e084f4aa561b9fde7aab345f3550 | C#code:C# | {"size": 2134, "ext": "cs", "max_stars_repo_path": "src/Nest/CommonAbstractions/Infer/IndexName/IndexName.cs", "max_stars_repo_name": "BedeGaming/elasticsearch-net", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Nest/CommonAbstractions/Infer/IndexName/IndexName.cs", "max_issues_repo_name": "BedeGaming/elasticsearch-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Nest/CommonAbstractions/Infer/IndexName/IndexName.cs", "max_forks_repo_name": "BedeGaming/elasticsearch-net", "max_forks_repo_forks_event_min_datetime": "2020-05-07T20:54:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T20:54:44.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 27.358974359, "max_line_length": 134, "alphanum_fraction": 0.6879100281} | using System;
using Elasticsearch.Net;
namespace Nest
{
[ContractJsonConverter(typeof(IndexNameJsonConverter))]
public class IndexName : IEquatable<IndexName>, IUrlParameter
{
public string Name { get; set; }
public Type Type { get; set; }
public static implicit operator IndexName(string typeName) => typeName.IsNullOrEmpty()
? null
: new IndexName { Name = typeName.Trim() };
public static implicit operator IndexName(Type type) => type == null
? null
: new IndexName { Type = type };
bool IEquatable<IndexName>.Equals(IndexName other) => EqualsMarker(other);
public override bool Equals(object obj)
{
var s = obj as string;
if (!s.IsNullOrEmpty()) return this.EqualsString(s);
var pp = obj as IndexName;
return EqualsMarker(pp);
}
public override int GetHashCode()
{
if (this.Name != null)
return this.Name.GetHashCode();
if (this.Type != null)
return this.Type.GetHashCode();
return 0;
}
public override string ToString()
{
if (!this.Name.IsNullOrEmpty())
return this.Name;
if (this.Type != null)
return this.Type.Name;
return string.Empty;
}
public bool EqualsString(string other)
{
return !other.IsNullOrEmpty() && other == this.Name;
}
public bool EqualsMarker(IndexName other)
{
if (!this.Name.IsNullOrEmpty() && other != null && !other.Name.IsNullOrEmpty())
return EqualsString(other.Name);
if (this.Type != null && other != null && other.Type != null)
return this.GetHashCode() == other.GetHashCode();
return false;
}
public string GetString(IConnectionConfigurationValues settings)
{
var nestSettings = settings as IConnectionSettingsValues;
if (nestSettings == null)
throw new Exception("Tried to pass index name on querysting but it could not be resolved because no nest settings are available");
return nestSettings.Inferrer.IndexName(this);
}
public static IndexName From<T>() => typeof(T);
public Indices And<T>() => new Indices(new IndexName[] { this, typeof(T) });
public Indices And(IndexName index) => new Indices(new IndexName[] { this, index });
}
}
|
||||
TheStack | bd3270065cfc3feeaf76487dff3497babb8420b0 | C#code:C# | {"size": 18554, "ext": "cs", "max_stars_repo_path": "GraphEditor/GraphNode.cs", "max_stars_repo_name": "ZingBallyhoo/GraphEditor", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphEditor/GraphNode.cs", "max_issues_repo_name": "ZingBallyhoo/GraphEditor", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphEditor/GraphNode.cs", "max_forks_repo_name": "ZingBallyhoo/GraphEditor", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.6541666667, "max_line_length": 217, "alphanum_fraction": 0.5541662175} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
namespace GraphEditor
{
public enum GraphNodeSelectionType
{
None,
Single,
Multi
}
public class GraphNode : IGraphNode
{
public bool Dirty { get; set; } = true;
public long Id => _id;
public Vector2 Position { get; set; } = Vector2.Zero;
public Vector2 Size => _size;
public string Name
{
get => string.IsNullOrEmpty(CustomName) ? _name : CustomName;
set { _name = value; Dirty = true; }
}
public string CustomName
{
get => _customName;
set { _customName = value; Dirty = true; }
}
public string Comment
{
get => _comment;
set { _comment = value; Dirty = true; }
}
public string Description
{
get => _description;
set { _description = value; Dirty = true; }
}
public GraphNodeSelectionType SelectionType
{
get => _selectionType;
set
{
if (!IsHidden)
_selectionType = value;
if (value == GraphNodeSelectionType.None)
_isDragStarted = false;
}
}
public IGraphSocket ActiveSocket { get; protected set; }
public IReadOnlyDictionary<long, IGraphSocket> InSockets => _inSockets;
public IReadOnlyDictionary<long, IGraphSocket> OutSockets => _outSockets;
public bool IsSelected => SelectionType != GraphNodeSelectionType.None;
public bool IsHidden { get; set; }
protected readonly long _id;
protected string _altName;
protected string _name;
protected string _customName;
protected string _comment;
protected string _description; // under name, dont know what to call it
protected Vector2 _size = Vector2.Zero;
protected bool _isHovered;
protected bool _isDragStarted;
protected bool _isAnySocketHovered;
protected SortedDictionary<long, IGraphSocket> _inSockets = new SortedDictionary<long, IGraphSocket>();
protected SortedDictionary<long, IGraphSocket> _outSockets = new SortedDictionary<long, IGraphSocket>();
protected IGraphSocket _contextMenuSocket;
GraphNodeSelectionType _selectionType;
// ---- For default CalculateSize and DrawNode ----
Vector2 _namePlateSize;
public GraphNode(long id, string name = null)
{
_id = id;
_altName = string.IsNullOrEmpty(name) ? "Node" : name;
}
public virtual void AddInputSocket(IGraphSocket socket)
{
Dirty = true;
socket.Parent = this;
socket.Type = SocketType.Input;
_inSockets.Add(socket.Id, socket);
}
public virtual void RemoveInputSocket(IGraphSocket socket)
{
Dirty = true;
_inSockets.Remove(socket.Id);
socket.Remove_DONOTUSE_ONLYNODE();
if (ActiveSocket != null && ActiveSocket.Id == socket.Id)
ActiveSocket = null;
}
public virtual void AddOutputSocket(IGraphSocket socket)
{
Dirty = true;
socket.Parent = this;
socket.Type = SocketType.Output;
_outSockets.Add(socket.Id, socket);
}
public virtual void RemoveOutputSocket(IGraphSocket socket)
{
Dirty = true;
_outSockets.Remove(socket.Id);
socket.Remove_DONOTUSE_ONLYNODE();
if (ActiveSocket != null && ActiveSocket.Id == socket.Id)
ActiveSocket = null;
}
public void RemoveInputSocket(long id)
=> RemoveInputSocket(_inSockets[id]);
public void RemoveOutputSocket(long id)
=> RemoveOutputSocket(_outSockets[id]);
public Vector2 GetLocalPosition()
{
var context = GraphContext.CurrentContext;
return (Position * context.UIScale) + context.ViewOffset + ImGui.GetWindowContentRegionMin();
}
public Vector2 GetScreenPosition()
{
return GetLocalPosition() + ImGui.GetWindowPos();
}
public virtual void Draw()
{
_isHovered = false;
_isAnySocketHovered = false;
if (Dirty)
{
CalculateSize();
Dirty = false;
}
ImGuiExtensions.PushID(Id);
ImGui.SetCursorPos(GetLocalPosition());
DrawHitboxArea(Size);
ImGui.PopID();
if (ImGui.IsItemVisible())
{
_isHovered = ImGuiExtensions.IsItemHovered_Overlap();
DrawNode();
DrawSockets();
}
if (!_isAnySocketHovered)
ActiveSocket = null;
// hacked together so context menus arent scaled
// alternatively, could let graph call this function after rendering all nodes
// but it would loop over the nodes twice.
ImGui.SetWindowFontScale(1.0f);
DrawContextMenu();
ImGui.SetWindowFontScale(GraphContext.CurrentContext.UIScale);
HandleMouseKeyboardEvents();
}
public virtual void Remove_DONOTUSE_ONLYGRAPH()
{
foreach (var (_, socket) in InSockets)
socket.Remove_DONOTUSE_ONLYNODE();
foreach (var (_, socket) in OutSockets)
socket.Remove_DONOTUSE_ONLYNODE();
_inSockets.Clear();
_outSockets.Clear();
ActiveSocket = null;
}
public virtual string GenerateNodeName()
{
var context = GraphContext.CurrentContext;
return context.IncludeIDInNodeName ? $"{_altName} #{Id}" : _altName;
}
public virtual void UpdateNode(bool manual = false)
{
// Useful if node definition was manually modified
}
public virtual void DrawProperties()
{
}
// Just an InvisibleButton with a check to make it visible or not
protected bool DrawHitboxArea(Vector2 size, uint color = 0xFF00FF00)
{
var context = GraphContext.CurrentContext;
if (context.DrawHitbox)
{
var drawList = ImGui.GetWindowDrawList();
var position = ImGui.GetCursorScreenPos();
drawList.AddRectFilled(position, position + size, color);
}
return ImGui.InvisibleButton("##HitBox", size);
}
protected virtual void DrawContextMenu()
{
if (ImGui.BeginPopup("node_context_menu"))
{
if (ImGui.MenuItem("Update"))
{
UpdateNode(manual: true);
}
ImGui.EndPopup();
}
if (ImGui.BeginPopup("socket_context_menu"))
{
var linksToBeDeleted = new List<IGraphLink>();
ImGuiExtensions.AlignedDisabledText(_contextMenuSocket.Name);
ImGui.SameLine();
if (ImGuiExtensions.RightAlignedButton("Clear"))
{
linksToBeDeleted.AddRange(_contextMenuSocket.Connections);
ImGui.CloseCurrentPopup();
}
ImGui.Separator();
if (_contextMenuSocket.Connections.Count != 0)
{
var isInputSocket = _contextMenuSocket.Type == SocketType.Input;
for (var i = 0; i != _contextMenuSocket.Connections.Count; ++i)
{
var connection = _contextMenuSocket.Connections[i];
IGraphSocket connectedToSocket;
if (isInputSocket)
connectedToSocket = connection.Source;
else
connectedToSocket = connection.Destination;
if (ImGuiExtensions.AlignedSelectableText($"{connectedToSocket.Parent.Name}::{connectedToSocket.Name}"))
{
connection.IsHighlighted = false;
var graph = GraphContext.CurrentContext.Graph;
graph.SelectNode(connectedToSocket.Parent);
graph.ScrollToNode(connectedToSocket.Parent);
ImGui.CloseCurrentPopup();
}
else
{
connection.IsHighlighted = ImGui.IsItemHovered();
}
ImGui.SameLine();
ImGui.PushStyleColor(ImGuiCol.FrameBg, 0);
if (ImGuiExtensions.IconButton_Remove(i))
{
linksToBeDeleted.Add(connection);
//ImGui.CloseCurrentPopup();
}
ImGui.PopStyleColor();
}
}
foreach (var connection in linksToBeDeleted)
{
GraphContext.CurrentContext.Graph.RemoveLink(connection);
}
ImGui.EndPopup();
}
}
protected virtual void HandleMouseKeyboardEvents()
{
var context = GraphContext.CurrentContext;
var io = ImGui.GetIO();
var isHoveringGraph = ImGui.IsWindowHovered();
var isHoveringAnyItem = ImGui.IsAnyItemHovered();
// Off by 1 frame
// If a node is single-selected and it's not us
// Fixes an issue with multi-selection
if (context.Graph.ActiveNode != null && context.Graph.ActiveNode.Id != Id)
{
SelectionType = GraphNodeSelectionType.None;
}
if (!_isHovered && isHoveringGraph && ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
if (SelectionType == GraphNodeSelectionType.Single ||
(SelectionType == GraphNodeSelectionType.Multi && !isHoveringAnyItem))
{
SelectionType = GraphNodeSelectionType.None;
}
}
if (!_isDragStarted)
{
if (isHoveringGraph && (_isHovered || IsSelected) && ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_isDragStarted = true;
if (!IsSelected)
SelectionType = GraphNodeSelectionType.Single;
}
}
else if (isHoveringGraph && ImGui.IsMouseDragging(ImGuiMouseButton.Left))
{
Position += io.MouseDelta / new Vector2(context.UIScale);
}
else if (ImGui.IsMouseReleased(ImGuiMouseButton.Left))
{
_isDragStarted = false;
}
if (ImGui.IsMouseReleased(ImGuiMouseButton.Right))
{
if (ImGuiExtensions.IsMouseClickedNoDrag(ImGuiMouseButton.Right))
{
if (ActiveSocket != null)
{
_contextMenuSocket = ActiveSocket;
ImGui.OpenPopup("socket_context_menu");
}
else if (_isHovered)
{
ImGui.OpenPopup("node_context_menu");
}
}
}
}
protected virtual void CalculateSize()
{
var context = GraphContext.CurrentContext;
var style = context.Style;
float NodeTextPaddingX = style.NodeTextPadding.X * context.UIScale;
float NodeTextPaddingY = style.NodeTextPadding.Y * context.UIScale;
float NodeSocketLabelSpacing = style.NodeSocketLabelSpacing * context.UIScale;
float NodeSocketRadius = style.NodeSocketRadius * context.UIScale;
float NodeSocketStartX = style.NodeSocketStartX * context.UIScale;
float NodeSocketSpacingX = style.NodeSocketSpacing.X * context.UIScale;
float NodeSocketSpacingY = style.NodeSocketSpacing.Y * context.UIScale;
float NodeBoxPadding = style.NodeBoxPadding * context.UIScale;
float BorderThickness = style.BorderThickness * context.UIScale;
var nameSize = ImGui.CalcTextSize(Name);
var descriptionSize = string.IsNullOrEmpty(Description) ? Vector2.Zero : ImGui.CalcTextSize(Description);
float widthRequiredForSockets = 0.0f;
float heightRequiredForSockets = NodeSocketSpacingY * Math.Max(InSockets.Count, OutSockets.Count);
for (var i = 0; i != Math.Max(InSockets.Count, OutSockets.Count); ++i)
{
float inputSocketNameWidth = 0.0f;
if (i < InSockets.Count)
inputSocketNameWidth = NodeSocketRadius + NodeSocketLabelSpacing + ImGui.CalcTextSize(InSockets.ElementAt(i).Value.Name).X;
float outputSocketNameWidth = 0.0f;
if (i < OutSockets.Count)
outputSocketNameWidth = NodeSocketRadius + NodeSocketLabelSpacing + ImGui.CalcTextSize(OutSockets.ElementAt(i).Value.Name).X;
float width = inputSocketNameWidth + NodeSocketSpacingX + outputSocketNameWidth;
widthRequiredForSockets = Math.Max(widthRequiredForSockets, width);
}
var textSizeX = Math.Max(nameSize.X, descriptionSize.X);
var textSizeY = nameSize.Y;
if (!string.IsNullOrEmpty(Description))
{
textSizeY += NodeTextPaddingY + descriptionSize.Y;
}
var hasSockets = widthRequiredForSockets != 0.0f;
var bottomPadding = NodeBoxPadding - (hasSockets ? NodeSocketSpacingY : 0.0f);
_size = new Vector2(Math.Max(textSizeX + NodeTextPaddingX * 2, widthRequiredForSockets),
textSizeY + NodeTextPaddingY * 2
+ heightRequiredForSockets
+ bottomPadding);
_namePlateSize = new Vector2(Size.X, textSizeY + NodeTextPaddingY * 2) - new Vector2(BorderThickness / 2);
var socketsYOffset = _namePlateSize.Y + NodeSocketStartX;
void UpdateSocketPosition(IReadOnlyDictionary<long, IGraphSocket> sockets, bool isRightAligned)
{
var socketPosition = new Vector2(isRightAligned ? Size.X : 0.0f, socketsYOffset);
foreach (var (_, socket) in sockets)
{
socket.RelativePosition = socketPosition;
socketPosition.Y += NodeSocketSpacingY;
}
}
UpdateSocketPosition(InSockets, false);
UpdateSocketPosition(OutSockets, true);
}
protected virtual void DrawNode()
{
var context = GraphContext.CurrentContext;
var style = context.Style;
float BorderRoundness = style.BorderRoundness * context.UIScale;
float BorderThickness = style.BorderThickness * context.UIScale;
var drawList = ImGui.GetWindowDrawList();
var renderPosition = GetScreenPosition();
{
var nodeBoxStart = renderPosition;
var nodeBoxEnd = nodeBoxStart + Size;
drawList.AddRectFilled(nodeBoxStart, nodeBoxEnd, style.GetColor(GraphStyle.Color.NodeBg), style.BorderRoundness);
var borderColor = style.GetColor(IsSelected ? GraphStyle.Color.ActiveNodeBorder : GraphStyle.Color.NodeBorder);
drawList.AddRect(nodeBoxStart, nodeBoxEnd, borderColor, BorderRoundness, ImDrawFlags.None, BorderThickness);
}
{
float NodeTextPaddingY = style.NodeTextPadding.Y * context.UIScale;
var nameSize = ImGui.CalcTextSize(Name);
var namePos = new Vector2(Size.X / 2 - nameSize.X / 2, NodeTextPaddingY);
drawList.AddRectFilled(renderPosition + new Vector2(BorderThickness / 2), renderPosition + _namePlateSize, style.GetColor(GraphStyle.Color.NodeNameplate), BorderRoundness, ImDrawFlags.RoundCornersTop);
drawList.AddText(renderPosition + namePos, style.GetColor(GraphStyle.Color.NodeName), Name);
if (!string.IsNullOrEmpty(Description))
{
var descriptionPosY = namePos.Y + nameSize.Y + NodeTextPaddingY;
var splitDescriptions = Description.Split('\n');
foreach (var splitDescription in splitDescriptions)
{
var descriptionSize = ImGui.CalcTextSize(splitDescription);
var descriptionPos = new Vector2(Size.X / 2 - descriptionSize.X / 2, descriptionPosY);
drawList.AddText(renderPosition + descriptionPos, style.GetColor(GraphStyle.Color.NodeDescription), splitDescription);
descriptionPosY += descriptionSize.Y; // padded
}
}
}
if (!string.IsNullOrEmpty(Comment))
{
float NodeTextPaddingY = style.NodeTextPadding.Y * context.UIScale;
var commentSize = ImGui.CalcTextSize(Comment);
var commentPosition = renderPosition - new Vector2(0.0f, commentSize.Y + NodeTextPaddingY);
drawList.AddText(commentPosition, style.GetColor(GraphStyle.Color.NodeComment), Comment);
}
}
protected virtual void DrawSockets(bool drawSocketNames = true)
{
void DrawSocketsDict(SortedDictionary<long, IGraphSocket> sockets)
{
foreach (var (_, socket) in sockets)
{
socket.Draw(drawSocketNames);
if (socket.IsHovered)
{
ActiveSocket = socket;
_isAnySocketHovered = true;
}
}
}
DrawSocketsDict(_inSockets);
DrawSocketsDict(_outSockets);
}
}
}
|
||||
TheStack | bd34f3460c25b94e16d2670ef8c136e825ee9e1e | C#code:C# | {"size": 4710, "ext": "cs", "max_stars_repo_path": "src/Tests/Gaucho.Integration.Tests/LoadTests.cs", "max_stars_repo_name": "WickedFlame/MessageMap", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Tests/Gaucho.Integration.Tests/LoadTests.cs", "max_issues_repo_name": "WickedFlame/MessageMap", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tests/Gaucho.Integration.Tests/LoadTests.cs", "max_forks_repo_name": "WickedFlame/MessageMap", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.9756097561, "max_line_length": 128, "alphanum_fraction": 0.5859872611} | using System;
using System.Diagnostics;
using System.Threading;
using Gaucho.Handlers;
using Gaucho.Server.Monitoring;
using NUnit.Framework;
using MeasureMap;
namespace Gaucho.Integration.Tests
{
public class LoadTests
{
private static object _lock = new object();
[SetUp]
public void Setup()
{
}
[Test]
[Explicit]
public void LoadTest_HeavyWork()
{
// start with the warmup...
var cnt = 0;
var proc = 0;
var pipelineId = Guid.NewGuid().ToString();
var server = new ProcessingServer();
server.Register(pipelineId, () =>
{
var pipeline = new EventPipeline();
pipeline.AddHandler(new LoadTestOuptuHandler(e =>
{
proc += 1;
// do some heavy work
Trace.WriteLine($"WORK TASK {proc}");
Thread.Sleep(10);
}));
return pipeline;
}, new PipelineOptions { MinProcessors = 10 });
server.Register(pipelineId, new InputHandler<InputItem>());
var client = new EventDispatcher(server);
var profiler = ProfilerSession.StartSession()
.SetIterations(1000)
.SetThreads(5)
.Task(() =>
{
lock(pipelineId)
{
cnt += 1;
}
Trace.WriteLine($"SEND {cnt}");
client.Process(pipelineId, new InputItem
{
Value = "StaticServer",
Name = "test",
Number = cnt
});
}).RunSession();
server.WaitAll(pipelineId);
profiler.Trace();
var monitor = new StatisticsApi(pipelineId);
var processed = monitor.GetMetricValue<long>(MetricType.ProcessedEvents);
Assert.AreEqual(processed, cnt, "Processed events are not equal to sent events {0} to {1}", processed, cnt);
}
[Test]
[Explicit]
public void LoadTest_MetricCounter()
{
// start with the warmup...
var sent = 0;
var processed = 0;
var pipelineId = Guid.NewGuid().ToString();
var server = new ProcessingServer();
server.Register(pipelineId, () =>
{
var pipeline = new EventPipeline();
pipeline.AddHandler(new LoadTestOuptuHandler(e =>
{
lock (_lock)
{
processed += 1;
}
// to some heavy work
Thread.Sleep(100);
}));
return pipeline;
});
server.Register(pipelineId, new InputHandler<InputItem>());
var client = new EventDispatcher(server);
var profiler = ProfilerSession.StartSession()
.SetIterations(1000)
.SetThreads(5)
.Task(() =>
{
client.Process(pipelineId, new InputItem
{
Value = "StaticServer",
Name = "test",
Number = sent
});
sent += 1;
}).RunSession();
server.WaitAll(pipelineId);
profiler.Trace();
var monitor = new StatisticsApi(pipelineId);
var metrics = monitor.GetMetricValue<long>(MetricType.ProcessedEvents);
Assert.AreEqual(metrics, processed, "Metric event counter is not equal to processed events {0} to {1}", metrics, processed);
}
[Test]
[Explicit]
public void LoadTest_Simple()
{
// start with the warmup...
var cnt = 0;
var pipelineId = Guid.NewGuid().ToString();
var server = new ProcessingServer();
server.Register(pipelineId, () =>
{
var pipeline = new EventPipeline();
pipeline.AddHandler(new LoadTestOuptuHandler(e=>{}));
return pipeline;
});
server.Register(pipelineId, new InputHandler<InputItem>());
var client = new EventDispatcher(server);
var profiler = ProfilerSession.StartSession()
.SetIterations(1000)
.SetThreads(5)
.Settings(s => s.RunWarmup = false)
.Task(() =>
{
client.Process(pipelineId, new InputItem
{
Value = "StaticServer",
Name = "test",
Number = 1
});
lock(pipelineId)
{
cnt += 1;
}
}).RunSession();
server.WaitAll(pipelineId);
profiler.Trace();
var monitor = new StatisticsApi(pipelineId);
var metrics = monitor.GetMetricValue<long>(MetricType.ProcessedEvents);
Assert.AreEqual(metrics, cnt, "Processed events are not equal to sent events {0} to {1}", metrics, cnt);
}
}
public class LoadTestOuptuHandler : IOutputHandler
{
private Action<Event> _task;
public LoadTestOuptuHandler(Action<Event> task)
{
_task = task;
}
public void Handle(Event @event)
{
_task(@event);
}
}
public class InputItem
{
public string Value { get; set; }
public string Name { get; set; }
public int Number { get; set; }
}
} |
||||
TheStack | bd35a28291771f49fd73835982ec352ee403c660 | C#code:C# | {"size": 101, "ext": "cshtml", "max_stars_repo_path": "tests/SampleApps/multilanguage/dotnetreact/Pages/_ViewImports.cshtml", "max_stars_repo_name": "cormacpayne/Oryx", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/SampleApps/multilanguage/dotnetreact/Pages/_ViewImports.cshtml", "max_issues_repo_name": "cormacpayne/Oryx", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/SampleApps/multilanguage/dotnetreact/Pages/_ViewImports.cshtml", "max_forks_repo_name": "cormacpayne/Oryx", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.25, "max_line_length": 52, "alphanum_fraction": 0.8415841584} | @using dotnetreact
@namespace dotnetreact.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
||||
TheStack | bd38707a4936daa4618488106153c3da4014b9f5 | C#code:C# | {"size": 807, "ext": "cs", "max_stars_repo_path": "Serenity.Core/Munq/IContainerFluent.cs", "max_stars_repo_name": "gsaielli/Serenity", "max_stars_repo_stars_event_min_datetime": "2021-04-08T01:34:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T04:17:16.000Z", "max_issues_repo_path": "Serenity.Core/Munq/IContainerFluent.cs", "max_issues_repo_name": "mkWong925/Serenity", "max_issues_repo_issues_event_min_datetime": "2021-05-11T21:59:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T21:59:36.000Z", "max_forks_repo_path": "Serenity.Core/Munq/IContainerFluent.cs", "max_forks_repo_name": "mijaved/Serenity", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 36.6818181818, "max_line_length": 102, "alphanum_fraction": 0.4659231722} | #if NET45
// --------------------------------------------------------------------------------------------------
// © Copyright 2011 by Matthew Dennis.
// Released under the Microsoft Public License (Ms-PL) http://www.opensource.org/licenses/ms-pl.html
// --------------------------------------------------------------------------------------------------
namespace Munq
{
/// <summary>
/// Fluent container
/// </summary>
public interface IContainerFluent
{
/// <summary>
/// Gets uses the default lifetime manager of.
/// </summary>
/// <param name="lifetimeManager">The lifetime manager.</param>
/// <returns></returns>
IContainerFluent UsesDefaultLifetimeManagerOf(ILifetimeManager lifetimeManager);
}
}
#endif |
||||
TheStack | bd3901b9b6f47a94e911c4581fda40d1cd6abb4e | C#code:C# | {"size": 352, "ext": "cs", "max_stars_repo_path": "mcs/errors/cs0075.cs", "max_stars_repo_name": "nataren/mono", "max_stars_repo_stars_event_min_datetime": "2021-08-05T04:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T04:41:05.000Z", "max_issues_repo_path": "mcs/errors/cs0075.cs", "max_issues_repo_name": "nataren/mono", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcs/errors/cs0075.cs", "max_forks_repo_name": "nataren/mono", "max_forks_repo_forks_event_min_datetime": "2016-10-20T19:06:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T23:28:53.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 14.6666666667, "max_line_length": 81, "alphanum_fraction": 0.6164772727} | // cs0075.cs: To cast a negative value, you must enclose the value in parentheses
// Line: 20
class X
{
public readonly int i;
public X (int i)
{
this.i = i;
}
public static implicit operator X (int value)
{
return new X (value);
}
public static void Main ()
{
int a = 4, b = 5;
X x = (X) -a;
System.Console.WriteLine (x.i);
}
}
|
||||
TheStack | bd3c162ebea0a530b0f04aa0a946eaed3e64a466 | C#code:C# | {"size": 94, "ext": "cs", "max_stars_repo_path": "src/Binance.NET/Responses/CandlesticksStreamResponse.cs", "max_stars_repo_name": "pgibler/Binance.NET", "max_stars_repo_stars_event_min_datetime": "2017-11-06T18:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T15:26:40.000Z", "max_issues_repo_path": "src/Binance.NET/Responses/CandlesticksStreamResponse.cs", "max_issues_repo_name": "pgibler/Binance.NET", "max_issues_repo_issues_event_min_datetime": "2018-03-04T13:22:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T03:32:09.000Z", "max_forks_repo_path": "src/Binance.NET/Responses/CandlesticksStreamResponse.cs", "max_forks_repo_name": "pgibler/Binance.NET", "max_forks_repo_forks_event_min_datetime": "2018-02-11T13:45:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T08:38:00.000Z"} | {"max_stars_count": 5.0, "max_issues_count": 1.0, "max_forks_count": 4.0, "avg_line_length": 11.75, "max_line_length": 43, "alphanum_fraction": 0.6914893617} | namespace Binance.NET.Responses
{
public class CandlesticksStreamResponse
{
}
}
|
||||
TheStack | bd40b92d46f4f841cee749ca04049c9e45e9d78c | C#code:C# | {"size": 247, "ext": "cs", "max_stars_repo_path": "src/ExpectedObjects/Strategies/IComparisonStrategy.cs", "max_stars_repo_name": "nsarris/expectedObjects", "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:55:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-02T01:55:36.000Z", "max_issues_repo_path": "src/ExpectedObjects/Strategies/IComparisonStrategy.cs", "max_issues_repo_name": "nsarris/expectedObjects", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ExpectedObjects/Strategies/IComparisonStrategy.cs", "max_forks_repo_name": "nsarris/expectedObjects", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.7, "max_line_length": 93, "alphanum_fraction": 0.7044534413} | using System;
namespace ExpectedObjects.Strategies
{
public interface IComparisonStrategy
{
bool CanCompare(Type type);
bool AreEqual(object expected, object actual, IComparisonContext comparisonContext);
}
} |
||||
TheStack | bd411d074c6d623b5f1425dbf504df6562cf9ee1 | C#code:C# | {"size": 1247, "ext": "cs", "max_stars_repo_path": "tests/Oryx.Integration.Tests/Php/PhpPostgreSqlIntegrationTests.cs", "max_stars_repo_name": "kumaramit-msft/Oryx", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Oryx.Integration.Tests/Php/PhpPostgreSqlIntegrationTests.cs", "max_issues_repo_name": "kumaramit-msft/Oryx", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Oryx.Integration.Tests/Php/PhpPostgreSqlIntegrationTests.cs", "max_forks_repo_name": "kumaramit-msft/Oryx", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.6388888889, "max_line_length": 121, "alphanum_fraction": 0.5060144346} | // --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// --------------------------------------------------------------------------------------------
using System.IO;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Oryx.Integration.Tests
{
[Trait("category", "php")]
[Trait("db", "postgres")]
public class PhpPostgreSqlIntegrationTests : DatabaseTestsBase, IClassFixture<Fixtures.PostgreSqlDbContainerFixture>
{
public PhpPostgreSqlIntegrationTests(ITestOutputHelper output, Fixtures.PostgreSqlDbContainerFixture dbFixture)
: base(output, dbFixture)
{
}
[Theory(Skip = "Bug 1410367") ]
[InlineData("7.2")]
[InlineData("7.3")]
[InlineData("7.4")]
public async Task PhpApp(string phpVersion)
{
await RunTestAsync(
"php",
phpVersion,
Path.Combine(HostSamplesDir, "php", "pgsql-example"),
8080,
specifyBindPortFlag: false);
}
}
} |
||||
TheStack | bd419c38eb7271184766f803bd3bc8f63438c657 | C#code:C# | {"size": 149, "ext": "cs", "max_stars_repo_path": "Editor/BuildPipelines/CustomBuildTarget.cs", "max_stars_repo_name": "JRahmatiNL/Unity3D.CustomEditorTools", "max_stars_repo_stars_event_min_datetime": "2020-12-20T18:31:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T18:31:32.000Z", "max_issues_repo_path": "Editor/BuildPipelines/CustomBuildTarget.cs", "max_issues_repo_name": "JRahmatiNL/Unity3D.CustomEditorTools", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Editor/BuildPipelines/CustomBuildTarget.cs", "max_forks_repo_name": "JRahmatiNL/Unity3D.CustomEditorTools", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 18.625, "max_line_length": 61, "alphanum_fraction": 0.644295302} | namespace JRahmatiNL.Unity3D.CustomEditorTools.BuildPipelines
{
public enum CustomBuildTarget
{
iOS = 0,
Android = 1,
}
} |
||||
TheStack | bd41e75060e84749194ba50f09a9bd62003f7d86 | C#code:C# | {"size": 10215, "ext": "cs", "max_stars_repo_path": "Sample/Koudai/Server/src/ZyGames.Tianjiexing.Model/DataModel/ServerFight.cs", "max_stars_repo_name": "wenhulove333/ScutServer", "max_stars_repo_stars_event_min_datetime": "2017-05-27T13:32:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-28T15:11:33.000Z", "max_issues_repo_path": "Sample/Koudai/Server/src/ZyGames.Tianjiexing.Model/DataModel/ServerFight.cs", "max_issues_repo_name": "Jesse1205/Scut", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sample/Koudai/Server/src/ZyGames.Tianjiexing.Model/DataModel/ServerFight.cs", "max_forks_repo_name": "Jesse1205/Scut", "max_forks_repo_forks_event_min_datetime": "2016-08-27T05:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T07:07:09.000Z"} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 4.0, "avg_line_length": 28.6938202247, "max_line_length": 119, "alphanum_fraction": 0.4133137543} | /****************************************************************************
Copyright (c) 2013-2015 scutgame.com
http://www.scutgame.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由Codesmith工具生成。
// 此文件的更改可能会导致不正确的行为,如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using ZyGames.Framework.Common;
using ZyGames.Framework.Collection;
using ZyGames.Framework.Model;
using ProtoBuf;
using System.Runtime.Serialization;
namespace ZyGames.Tianjiexing.Model
{
/// <summary>
/// 公会城市争夺战全局表
/// </summary>
[Serializable, ProtoContract]
[EntityTable(CacheType.Entity, DbConfig.Data, "ServerFight", Condition = "IsRemove=0")]
public class ServerFight : ShareEntity
{
public const string Index_FastID = "Index_FastID";
public ServerFight()
: base(AccessLevel.ReadWrite)
{
}
public ServerFight(Int32 FastID, String GuildID)
: this()
{
this.FastID = FastID;
this.GuildID = GuildID;
}
#region 自动生成属性
private Int32 _FastID;
/// <summary>
///
/// </summary>
[ProtoMember(1)]
[EntityField("FastID", IsKey = true)]
public Int32 FastID
{
get { return _FastID; }
private set
{
SetChange("FastID", value);
}
}
private String _GuildID;
/// <summary>
///
/// </summary>
[ProtoMember(2)]
[EntityField("GuildID", IsKey = true)]
public String GuildID
{
get
{
return _GuildID;
}
private set
{
SetChange("GuildID", value);
}
}
private Int32 _CityID;
/// <summary>
///
/// </summary>
[ProtoMember(3)]
[EntityField("CityID")]
public Int32 CityID
{
get
{
return _CityID;
}
set
{
SetChange("CityID", value);
}
}
private String _GuildBanner;
/// <summary>
///
/// </summary>
[ProtoMember(4)]
[EntityField("GuildBanner")]
public String GuildBanner
{
get
{
return _GuildBanner;
}
set
{
SetChange("GuildBanner", value);
}
}
private Int16 _RankID;
/// <summary>
///
/// </summary>
[ProtoMember(5)]
[EntityField("RankID")]
public Int16 RankID
{
get
{
return _RankID;
}
set
{
SetChange("RankID", value);
}
}
private DateTime _ApplyDate;
/// <summary>
///
/// </summary>
[ProtoMember(6)]
[EntityField("ApplyDate")]
public DateTime ApplyDate
{
get
{
return _ApplyDate;
}
set
{
SetChange("ApplyDate", value);
}
}
private String _CombatMember;
/// <summary>
///
/// </summary>
[ProtoMember(7)]
[EntityField("CombatMember")]
public String CombatMember
{
get
{
return _CombatMember;
}
set
{
SetChange("CombatMember", value);
}
}
private FightStage _Stage;
/// <summary>
///
/// </summary>
[ProtoMember(8)]
[EntityField("Stage")]
public FightStage Stage
{
get
{
return _Stage;
}
set
{
SetChange("Stage", value);
}
}
private Int16 _LostCount = 0;
/// <summary>
/// 胜利次数
/// </summary>
[ProtoMember(9)]
[EntityField("LostCount")]
public Int16 LostCount
{
get
{
return _LostCount;
}
set
{
SetChange("LostCount", value);
}
}
private bool _IsRemove;
/// <summary>
/// 是否移除
/// </summary>
[ProtoMember(10)]
[EntityField("IsRemove")]
public bool IsRemove
{
get
{
return _IsRemove;
}
set
{
SetChange("IsRemove", value);
}
}
private bool _IsBanner;
/// <summary>
/// 旗帜名称是否变换
/// </summary>
[ProtoMember(11)]
[EntityField("IsBanner")]
public bool IsBanner
{
get
{
return _IsBanner;
}
set
{
SetChange("IsBanner", value);
}
}
protected override object this[string index]
{
get
{
#region
switch (index)
{
case "FastID": return FastID;
case "GuildID": return GuildID;
case "CityID": return CityID;
case "GuildBanner": return GuildBanner;
case "RankID": return RankID;
case "ApplyDate": return ApplyDate;
case "CombatMember": return CombatMember;
case "Stage": return Stage;
case "LostCount": return LostCount;
case "IsRemove": return IsRemove;
case "IsBanner": return IsBanner;
default: throw new ArgumentException(string.Format("ServerFight index[{0}] isn't exist.", index));
}
#endregion
}
set
{
#region
switch (index)
{
case "FastID":
_FastID = value.ToInt();
break;
case "GuildID":
_GuildID = value.ToNotNullString();
break;
case "CityID":
_CityID = value.ToInt();
break;
case "GuildBanner":
_GuildBanner = value.ToNotNullString();
break;
case "RankID":
_RankID = value.ToShort();
break;
case "ApplyDate":
_ApplyDate = value.ToDateTime();
break;
case "CombatMember":
_CombatMember = value.ToNotNullString();
break;
case "Stage":
_Stage = value.ToEnum<FightStage>();
break;
case "LostCount":
_LostCount = value.ToShort();
break;
case "IsRemove":
_IsRemove = value.ToBool();
break;
case "IsBanner":
_IsBanner = value.ToBool();
break;
default: throw new ArgumentException(string.Format("ServerFight index[{0}] isn't exist.", index));
}
#endregion
}
}
#endregion
protected override int GetIdentityId()
{
//allow modify return value
return DefIdentityId;
}
/// <summary>
/// 结果
/// </summary>
public bool GetResult(FightStage stage)
{
switch (stage)
{
case FightStage.Close:
case FightStage.Apply:
return true;
case FightStage.quarter_final:
return LostCount >= 1;
case FightStage.semi_final:
return LostCount >= 2;
case FightStage.final:
return LostCount >= 3;
default:
break;
}
return true;
}
}
} |
||||
TheStack | bd43af49e7cafb5bdc48b0c9baad765a350027c1 | C#code:C# | {"size": 4625, "ext": "cs", "max_stars_repo_path": "Program.cs", "max_stars_repo_name": "Bansaidnes/Episode-Grabber---C-", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Program.cs", "max_issues_repo_name": "Bansaidnes/Episode-Grabber---C-", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Program.cs", "max_forks_repo_name": "Bansaidnes/Episode-Grabber---C-", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 45.3431372549, "max_line_length": 341, "alphanum_fraction": 0.5507027027} | using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
namespace C__episode_grabber
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Episode grabber";
Console.ForegroundColor = ConsoleColor.DarkCyan;
String baseurl = "https://gogoplay1.com/videos/";
Console.WriteLine("Hello! Please enter the title you want to give your page\n");
String title = Console.ReadLine();
Console.WriteLine("\nPlease enter the show's name\n");
String show = Console.ReadLine().Trim();
show = show.Replace(" ", "-");
Console.WriteLine("\nPlease enter the episode you want to start from\n");
int start = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nPlease enter the episode you want to stop at (or last episode of show)\n");
int end = Convert.ToInt32(Console.ReadLine());
for (int i = start; i < end + 1; i++)
{
File.Delete("Balls.txt");
Console.WriteLine("Current episode: ep" + i + "\n");
String url = baseurl + show + "-episode-" + i;
WebRequest request = WebRequest.Create (url);
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Console.WriteLine (response.StatusDescription);
Stream dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
File.WriteAllText("Balls.txt",responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();
IEnumerable<string> lines = File.ReadAllLines("Balls.txt");
string keyword = "iframe";
IEnumerable<string> matches = !String.IsNullOrEmpty(keyword)
? lines.Where(line => line.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
: Enumerable.Empty<string>();
String src = String.Format("{0}", String.Join("",matches));
String src2 = src.Replace("<iframe src=\"//gogoplay1.com/streaming.php?id=", "").Replace("\" allowfullscreen=\"true\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe>", "").Replace(" ", "");
Console.WriteLine("Show ID: " + src2);
int prev = i-1;
int next = i+1;
String value1 = File.ReadAllText(@"value1.txt");
String value1m = "<title>"+title+"</title>";
String value1f = File.ReadAllText(@"value1f.txt");
String epis = show.Replace("-", " ");
String value2 = "<p>You are watching: " + epis + " episode "+i+"</p>";
String value22= "<iframe style=\"border: 3px solid #FFFFFF;\" width=\"562\" height=\"315\" sandbox=\"allow-scripts allow-same-origin allow-forms\"; "+"src=\"https://gogoplay1.com/streaming.php?id="+src2+"\" style=\"overflow:hidden;height:70%;width:50%\" height=\"70%\" width=\"50%\" scrolling=\"no\" allowfullscreen></iframe>";
String value3 = File.ReadAllText(@"value3.txt");
String value4 = "<button onClick=\"window.location.href='"+prev+".html';\">Previous</button>";
String value5 = "<button onClick=\"window.location.href='index.html';\">Episode selector</button>";
String value6 = "<button onClick=\"window.location.href='"+next+".html';\">Next</button>";
String value7 = File.ReadAllText(@"value7.txt");
String value8 = value1 + value1m + value1f + value2 + value22 + value3 + value4 + value5 + value6 + value7;
File.WriteAllText(i+".html", value8);
File.Delete("Balls.txt");
Thread.Sleep(1000);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nEpisode complete!\n");
Console.ForegroundColor = ConsoleColor.DarkCyan;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nProcess complete!");
Console.ReadKey();
}
}
}
|
||||
TheStack | bd43c06b23d523c3b92f76c18937bb6c1ae9814d | C#code:C# | {"size": 16970, "ext": "cs", "max_stars_repo_path": "tests/SideBySide.New/DataTypes.cs", "max_stars_repo_name": "ejball/MySqlConnector", "max_stars_repo_stars_event_min_datetime": "2022-02-02T15:31:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:31:12.000Z", "max_issues_repo_path": "tests/SideBySide.New/DataTypes.cs", "max_issues_repo_name": "ejball/MySqlConnector", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/SideBySide.New/DataTypes.cs", "max_forks_repo_name": "ejball/MySqlConnector", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.6560364465, "max_line_length": 289, "alphanum_fraction": 0.6730111962} | using System;
using System.Data.Common;
using System.Globalization;
using System.Linq;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
using static System.FormattableString;
// mysql-connector-net will throw SqlNullValueException, which is an exception type related to SQL Server:
// "The exception that is thrown when the Value property of a System.Data.SqlTypes structure is set to null."
// However, DbDataReader.GetString etc. are documented as throwing InvalidCastException: https://msdn.microsoft.com/en-us/library/system.data.common.dbdatareader.getstring.aspx
// Additionally, that is what DbDataReader.GetFieldValue<T> throws. For consistency, we prefer InvalidCastException.
#if BASELINE
using GetValueWhenNullException = System.Data.SqlTypes.SqlNullValueException;
#else
using GetValueWhenNullException = System.InvalidCastException;
#endif
namespace SideBySide
{
public class DataTypes : IClassFixture<DataTypesFixture>
{
public DataTypes(DataTypesFixture database)
{
m_database = database;
}
#if BASELINE
[Theory(Skip = "Broken by https://bugs.mysql.com/bug.php?id=78917")]
#else
[Theory]
#endif
[InlineData("Boolean", new object[] { null, false, true, false, true, true, true })]
[InlineData("TinyInt1", new object[] { null, false, true, false, true, true, true })]
public void QueryBoolean(string column, object[] expected)
{
DoQuery("bools", column, expected, reader => reader.GetBoolean(0));
}
[Theory]
[InlineData("SByte", new object[] { null, default(sbyte), sbyte.MinValue, sbyte.MaxValue, (sbyte) 123 })]
public void QuerySByte(string column, object[] expected)
{
DoQuery("integers", column, expected, reader => ((MySqlDataReader) reader).GetSByte(0), baselineCoercedNullValue: default(sbyte));
}
[Theory]
[InlineData("Byte", new object[] { null, default(byte), byte.MinValue, byte.MaxValue, (byte) 123 })]
public void QueryByte(string column, object[] expected)
{
DoQuery("integers", column, expected, reader => reader.GetByte(0), baselineCoercedNullValue: default(byte));
}
[Theory]
[InlineData("Int16", new object[] { null, default(short), short.MinValue, short.MaxValue, (short) 12345 })]
public void QueryInt16(string column, object[] expected)
{
DoQuery("integers", column, expected, reader => reader.GetInt16(0));
}
[Theory]
[InlineData("UInt16", new object[] { null, default(ushort), ushort.MinValue, ushort.MaxValue, (ushort) 12345 })]
public void QueryUInt16(string column, object[] expected)
{
DoQuery<InvalidCastException>("integers", column, expected, reader => reader.GetFieldValue<ushort>(0));
}
[Theory]
[InlineData("Int24", new object[] { null, default(int), -8388608, 8388607, 1234567 })]
[InlineData("Int32", new object[] { null, default(int), int.MinValue, int.MaxValue, 123456789 })]
public void QueryInt32(string column, object[] expected)
{
DoQuery("integers", column, expected, reader => reader.GetInt32(0));
}
[Theory]
[InlineData("UInt24", new object[] { null, default(uint), 0u, 16777215u, 1234567u })]
[InlineData("UInt32", new object[] { null, default(uint), uint.MinValue, uint.MaxValue, 123456789u })]
public void QueryUInt32(string column, object[] expected)
{
DoQuery<InvalidCastException>("integers", column, expected, reader => reader.GetFieldValue<uint>(0));
}
[Theory]
[InlineData("Int64", new object[] { null, default(long), long.MinValue, long.MaxValue, 1234567890123456789 })]
public void QueryInt64(string column, object[] expected)
{
DoQuery("integers", column, expected, reader => reader.GetInt64(0));
}
[Theory]
[InlineData("UInt64", new object[] { null, default(ulong), ulong.MinValue, ulong.MaxValue, 1234567890123456789u })]
public void QueryUInt64(string column, object[] expected)
{
DoQuery<InvalidCastException>("integers", column, expected, reader => reader.GetFieldValue<ulong>(0));
}
[Theory]
[InlineData("Bit1", new object[] { null, 0UL, 1UL, 1UL })]
[InlineData("Bit32", new object[] { null, 0UL, 1UL, (ulong) uint.MaxValue })]
[InlineData("Bit64", new object[] { null, 0UL, 1UL, ulong.MaxValue })]
public void QueryBits(string column, object[] expected)
{
DoQuery<InvalidCastException>("bits", column, expected, reader => reader.GetFieldValue<ulong>(0));
}
[Theory]
[InlineData("Single", new object[] { null, default(float), -3.40282e38f, -1.4013e-45f, 3.40282e38f, 1.4013e-45f })]
public void QueryFloat(string column, object[] expected)
{
DoQuery("reals", column, expected, reader => reader.GetFloat(0));
}
[Theory]
[InlineData("`Double`", new object[] { null, default(double), -1.7976931348623157e308, -5e-324, 1.7976931348623157e308, 5e-324 })]
public void QueryDouble(string column, object[] expected)
{
DoQuery("reals", column, expected, reader => reader.GetDouble(0));
}
[Theory]
[InlineData("SmallDecimal", new object[] { null, "0", "-999.99", "-0.01", "999.99", "0.01" })]
[InlineData("MediumDecimal", new object[] { null, "0", "-999999999999.99999999", "-0.00000001", "999999999999.99999999", "0.00000001" })]
// value exceeds the range of a decimal and cannot be deserialized
// [InlineData("BigDecimal", new object[] { null, "0", "-99999999999999999999.999999999999999999999999999999", "-0.000000000000000000000000000001", "99999999999999999999.999999999999999999999999999999", "0.000000000000000000000000000001" })]
public void QueryDecimal(string column, object[] expected)
{
for (int i = 0; i < expected.Length; i++)
if (expected[i] != null)
expected[i] = decimal.Parse((string) expected[i], CultureInfo.InvariantCulture);
DoQuery("reals", column, expected, reader => reader.GetDecimal(0));
}
[Theory]
[InlineData("utf8", new[] { null, "", "ASCII", "Ũńıċōđĕ", c_251ByteString })]
[InlineData("utf8bin", new[] { null, "", "ASCII", "Ũńıċōđĕ", c_251ByteString })]
[InlineData("latin1", new[] { null, "", "ASCII", "Lãtïñ", c_251ByteString })]
[InlineData("latin1bin", new[] { null, "", "ASCII", "Lãtïñ", c_251ByteString })]
[InlineData("cp1251", new[] { null, "", "ASCII", "АБВГабвг", c_251ByteString })]
public void QueryString(string column, string[] expected)
{
DoQuery("strings", column, expected, reader => reader.GetString(0));
}
const string c_251ByteString = "This string has exactly 251 characters in it. The encoded length is stored as 0xFC 0xFB 0x00. 0xFB (i.e., 251) is the sentinel byte indicating \"this field is null\". Incorrectly interpreting the (decoded) length as the sentinel byte would corrupt data.";
[Theory]
[InlineData("guid", new object[] { null, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-c000-000000000046", "fd24a0e8-c3f2-4821-a456-35da2dc4bb8f", "6A0E0A40-6228-11D3-A996-0050041896C8" })]
[InlineData("guidbin", new object[] { null, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-c000-000000000046", "fd24a0e8-c3f2-4821-a456-35da2dc4bb8f", "6A0E0A40-6228-11D3-A996-0050041896C8" })]
public void QueryGuid(string column, object[] expected)
{
for (int i = 0; i < expected.Length; i++)
if (expected[i] != null)
expected[i] = Guid.Parse((string) expected[i]);
#if BASELINE
DoQuery<MySqlException>("strings", column, expected, reader => reader.GetGuid(0));
#else
DoQuery("strings", column, expected, reader => reader.GetGuid(0));
#endif
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void QueryBinaryGuid(bool oldGuids)
{
var csb = Constants.CreateConnectionStringBuilder();
csb.OldGuids = oldGuids;
csb.Database = "datatypes";
using (var connection = new MySqlConnection(csb.ConnectionString))
{
connection.Open();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = @"select guidbin from blobs order by rowid;";
using (var reader = cmd.ExecuteReader())
{
Assert.True(reader.Read());
Assert.Equal(DBNull.Value, reader.GetValue(0));
Assert.True(reader.Read());
if (oldGuids)
{
var expected = new Guid(0x33221100, 0x5544, 0x7766, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF);
Assert.Equal(expected, reader.GetValue(0));
Assert.Equal(expected, reader.GetGuid(0));
}
else
{
var expected = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
Assert.Equal(expected, GetBytes(reader));
Assert.Equal(expected, reader.GetValue(0));
}
Assert.False(reader.Read());
}
cmd.CommandText = @"select guidbin from strings order by rowid;";
using (var reader = cmd.ExecuteReader())
{
Assert.True(reader.Read());
Assert.Equal(DBNull.Value, reader.GetValue(0));
Assert.True(reader.Read());
if (oldGuids)
{
Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetValue(0));
Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetString(0));
}
else
{
Assert.Equal(Guid.Empty, reader.GetValue(0));
Assert.Equal(Guid.Empty, reader.GetGuid(0));
}
}
}
}
}
[Theory]
[InlineData("`Date`", new object[] { null, "1000 01 01", "9999 12 31", "0001 01 01", "2016 04 05" })]
[InlineData("`DateTime`", new object[] { null, "1000 01 01 0 0 0", "9999 12 31 23 59 59 999999", "0001 01 01 0 0 0", "2016 4 5 14 3 4 567890" })]
[InlineData("`Timestamp`", new object[] { null, "1970 01 01 0 0 1", "2038 1 18 3 14 7 999999", "0001 01 01 0 0 0", "2016 4 5 14 3 4 567890" })]
public void QueryDate(string column, object[] expected)
{
DoQuery("times", column, ConvertToDateTime(expected), reader => reader.GetDateTime(0));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void QueryZeroDateTime(bool convertZeroDateTime)
{
var csb = Constants.CreateConnectionStringBuilder();
csb.ConvertZeroDateTime = convertZeroDateTime;
csb.Database = "datatypes";
using (var connection = new MySqlConnection(csb.ConnectionString))
{
connection.Open();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = @"select `Date`, `DateTime`, `Timestamp` from times where `Date` = 0;";
using (var reader = cmd.ExecuteReader())
{
Assert.True(reader.Read());
if (convertZeroDateTime)
{
Assert.Equal(DateTime.MinValue, reader.GetDateTime(0));
Assert.Equal(DateTime.MinValue, reader.GetDateTime(1));
Assert.Equal(DateTime.MinValue, reader.GetDateTime(2));
}
else
{
#if BASELINE
Assert.Throws<MySql.Data.Types.MySqlConversionException>(() => reader.GetDateTime(0));
Assert.Throws<MySql.Data.Types.MySqlConversionException>(() => reader.GetDateTime(1));
Assert.Throws<MySql.Data.Types.MySqlConversionException>(() => reader.GetDateTime(2));
#else
Assert.Throws<InvalidCastException>(() => reader.GetDateTime(0));
Assert.Throws<InvalidCastException>(() => reader.GetDateTime(1));
Assert.Throws<InvalidCastException>(() => reader.GetDateTime(2));
#endif
}
}
}
}
}
[Theory]
[InlineData("`Time`", new object[] { null, "-838 -59 -59", "838 59 59", "0 0 0", "0 14 3 4 567890" })]
public void QueryTime(string column, object[] expected)
{
DoQuery<InvalidCastException>("times", column, ConvertToTimeSpan(expected), reader => reader.GetFieldValue<TimeSpan>(0));
}
[Theory]
[InlineData("`Year`", new object[] { null, 1901, 2155, 0, 2016 })]
public void QueryYear(string column, object[] expected)
{
DoQuery("times", column, expected, reader => reader.GetInt32(0));
}
[Theory]
[InlineData("Binary", 100)]
[InlineData("VarBinary", 0)]
[InlineData("TinyBlob", 0)]
[InlineData("Blob", 0)]
[InlineData("MediumBlob", 0)]
[InlineData("LongBlob", 0)]
public void QueryBlob(string column, int padLength)
{
var data = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
if (data.Length < padLength)
Array.Resize(ref data, padLength);
DoQuery<NullReferenceException>("blobs", "`" + column + "`", new object[] { null, data }, GetBytes);
}
[Theory]
[InlineData("TinyBlob", 255)]
[InlineData("Blob", 65535)]
#if false
// MySQL has a default max_allowed_packet size of 4MB; without changing the server configuration, it's impossible
// to send more than 4MB of data.
[InlineData("MediumBlob", 16777216)]
[InlineData("LargeBlob", 67108864)]
#endif
public void InsertLargeBlob(string column, int size)
{
var data = new byte[size];
for (int i = 0; i < data.Length; i++)
data[i] = (byte) (i % 256);
long lastInsertId;
using (var cmd = new MySqlCommand(Invariant($"insert into datatypes.blobs(`{column}`) values(?)"), m_database.Connection)
{
Parameters = { new MySqlParameter { Value = data } }
})
{
cmd.ExecuteNonQuery();
lastInsertId = cmd.LastInsertedId;
}
foreach (var queryResult in m_database.Connection.Query<byte[]>(Invariant($"select `{column}` from datatypes.blobs where rowid = {lastInsertId}")))
{
Assert.Equal(data, queryResult);
break;
}
m_database.Connection.Execute(Invariant($"delete from datatypes.blobs where rowid = {lastInsertId}"));
}
private static byte[] GetBytes(DbDataReader reader)
{
var size = reader.GetBytes(0, 0, null, 0, 0);
var result = new byte[size];
reader.GetBytes(0, 0, result, 0, result.Length);
return result;
}
private void DoQuery(string table, string column, object[] expected, Func<DbDataReader, object> getValue, object baselineCoercedNullValue = null)
{
DoQuery<GetValueWhenNullException>(table, column, expected, getValue, baselineCoercedNullValue);
}
// NOTE: baselineCoercedNullValue is to work around inconsistencies in mysql-connector-net; DBNull.Value will
// be coerced to 0 by some reader.GetX() methods, but not others.
private void DoQuery<TException>(string table, string column, object[] expected, Func<DbDataReader, object> getValue, object baselineCoercedNullValue = null)
where TException : Exception
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = Invariant($"select {column} from datatypes.{table} order by rowid");
using (var reader = cmd.ExecuteReader())
{
foreach (var value in expected)
{
Assert.True(reader.Read());
if (value == null)
{
Assert.Equal(DBNull.Value, reader.GetValue(0));
#if BASELINE
if (baselineCoercedNullValue != null)
Assert.Equal(baselineCoercedNullValue, getValue(reader));
else
Assert.Throws<TException>(() => getValue(reader));
#else
Assert.Throws<InvalidCastException>(() => getValue(reader));
#endif
}
else
{
Assert.Equal(value, reader.GetValue(0));
Assert.Equal(value, getValue(reader));
}
}
Assert.False(reader.Read());
Assert.False(reader.NextResult());
}
// don't perform exact queries for floating-point values; they may fail
// http://dev.mysql.com/doc/refman/5.7/en/problems-with-float.html
if (expected.Last() is float)
return;
cmd.CommandText = Invariant($"select rowid from datatypes.{table} where {column} = @value");
var p = cmd.CreateParameter();
p.ParameterName = "@value";
p.Value = expected.Last();
cmd.Parameters.Add(p);
var result = cmd.ExecuteScalar();
Assert.Equal(Array.IndexOf(expected, p.Value) + 1, result);
}
}
private static object[] ConvertToDateTime(object[] input)
{
var output = new object[input.Length];
for (int i = 0; i < input.Length; i++)
{
var value = SplitAndParse(input[i]);
if (value?.Length == 3)
output[i] = new DateTime(value[0], value[1], value[2]);
else if (value?.Length == 6)
output[i] = new DateTime(value[0], value[1], value[2], value[3], value[4], value[5]);
else if (value?.Length == 7)
output[i] = new DateTime(value[0], value[1], value[2], value[3], value[4], value[5], value[6] / 1000).AddTicks(value[6] % 1000 * 10);
}
return output;
}
private static object[] ConvertToTimeSpan(object[] input)
{
var output = new object[input.Length];
for (int i = 0; i < input.Length; i++)
{
var value = SplitAndParse(input[i]);
if (value?.Length == 3)
output[i] = new TimeSpan(value[0], value[1], value[2]);
else if (value?.Length == 5)
output[i] = new TimeSpan(value[0], value[1], value[2], value[3], value[4] / 1000) + TimeSpan.FromTicks(value[4] % 1000 * 10);
}
return output;
}
private static int[] SplitAndParse(object obj)
{
var value = obj as string;
if (value == null)
return null;
var split = value.Split();
var output = new int[split.Length];
for (int i = 0; i < split.Length; i++)
output[i] = int.Parse(split[i], CultureInfo.InvariantCulture);
return output;
}
readonly DataTypesFixture m_database;
}
}
|