text stringlengths 13 6.01M |
|---|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Session;
using Microsoft.PowerShell.EditorServices.Test.Shared;
using Microsoft.PowerShell.EditorServices.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.PowerShell.EditorServices.Test.Console
{
public class PowerShellContextTests : IDisposable
{
private PowerShellContext powerShellContext;
private AsyncQueue<SessionStateChangedEventArgs> stateChangeQueue;
private static readonly string s_debugTestFilePath =
TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared/Debugging/DebugTest.ps1");
public static readonly HostDetails TestHostDetails =
new HostDetails(
"PowerShell Editor Services Test Host",
"Test.PowerShellEditorServices",
new Version("1.0.0"));
// NOTE: These paths are arbitrarily chosen just to verify that the profile paths
// can be set to whatever they need to be for the given host.
public static readonly ProfilePaths TestProfilePaths =
new ProfilePaths(
TestHostDetails.ProfileId,
Path.GetFullPath(
TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared/Profile")),
Path.GetFullPath(
TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared")));
public PowerShellContextTests()
{
this.powerShellContext = PowerShellContextFactory.Create(Logging.NullLogger);
this.powerShellContext.SessionStateChanged += OnSessionStateChanged;
this.stateChangeQueue = new AsyncQueue<SessionStateChangedEventArgs>();
}
public void Dispose()
{
this.powerShellContext.Dispose();
this.powerShellContext = null;
}
[Fact]
public async Task CanExecutePSCommand()
{
PSCommand psCommand = new PSCommand();
psCommand.AddScript("$a = \"foo\"; $a");
var executeTask =
this.powerShellContext.ExecuteCommandAsync<string>(psCommand);
await this.AssertStateChange(PowerShellContextState.Running);
await this.AssertStateChange(PowerShellContextState.Ready);
var result = await executeTask;
Assert.Equal("foo", result.First());
}
[Fact]
public async Task CanQueueParallelRunspaceRequests()
{
// Concurrently initiate 4 requests in the session
Task taskOne = this.powerShellContext.ExecuteScriptStringAsync("$x = 100");
Task<RunspaceHandle> handleTask = this.powerShellContext.GetRunspaceHandleAsync();
Task taskTwo = this.powerShellContext.ExecuteScriptStringAsync("$x += 200");
Task taskThree = this.powerShellContext.ExecuteScriptStringAsync("$x = $x / 100");
PSCommand psCommand = new PSCommand();
psCommand.AddScript("$x");
Task<IEnumerable<int>> resultTask = this.powerShellContext.ExecuteCommandAsync<int>(psCommand);
// Wait for the requested runspace handle and then dispose it
RunspaceHandle handle = await handleTask;
handle.Dispose();
// Wait for all of the executes to complete
await Task.WhenAll(taskOne, taskTwo, taskThree, resultTask);
// At this point, the remaining command executions should execute and complete
int result = resultTask.Result.FirstOrDefault();
// 100 + 200 = 300, then divided by 100 is 3. We are ensuring that
// the commands were executed in the sequence they were called.
Assert.Equal(3, result);
}
[Fact]
public async Task CanAbortExecution()
{
var executeTask =
Task.Run(
async () =>
{
var unusedTask = this.powerShellContext.ExecuteScriptWithArgsAsync(s_debugTestFilePath);
await Task.Delay(50);
this.powerShellContext.AbortExecution();
});
await this.AssertStateChange(PowerShellContextState.Running);
await this.AssertStateChange(PowerShellContextState.Aborting);
await this.AssertStateChange(PowerShellContextState.Ready);
await executeTask;
}
[Fact]
public async Task CanResolveAndLoadProfilesForHostId()
{
string[] expectedProfilePaths =
new string[]
{
TestProfilePaths.AllUsersAllHosts,
TestProfilePaths.AllUsersCurrentHost,
TestProfilePaths.CurrentUserAllHosts,
TestProfilePaths.CurrentUserCurrentHost
};
// Load the profiles for the test host name
await this.powerShellContext.LoadHostProfilesAsync();
// Ensure that all the paths are set in the correct variables
// and that the current user's host profile got loaded
PSCommand psCommand = new PSCommand();
psCommand.AddScript(
"\"$($profile.AllUsersAllHosts) " +
"$($profile.AllUsersCurrentHost) " +
"$($profile.CurrentUserAllHosts) " +
"$($profile.CurrentUserCurrentHost) " +
"$(Assert-ProfileLoaded)\"");
var result =
await this.powerShellContext.ExecuteCommandAsync<string>(
psCommand);
string expectedString =
string.Format(
"{0} True",
string.Join(
" ",
expectedProfilePaths));
Assert.Equal(expectedString, result.FirstOrDefault(), true);
}
#region Helper Methods
private async Task AssertStateChange(PowerShellContextState expectedState)
{
SessionStateChangedEventArgs newState =
await this.stateChangeQueue.DequeueAsync();
Assert.Equal(expectedState, newState.NewSessionState);
}
private void OnSessionStateChanged(object sender, SessionStateChangedEventArgs e)
{
this.stateChangeQueue.EnqueueAsync(e).Wait();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Pesadores : Personas
{
[Key]
public int IdPesador { get; set; }
public Pesadores()
{
IdPesador = 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotNetLinearAlgebra
{
/// <summary>
/// Matrix object of type double
/// </summary>
public class Matrix
{
protected readonly int _m;
protected readonly int _n;
protected double[][] _matrixArr;
/// <summary>
/// Ctor for a matrix object
/// </summary>
/// <param name="m">Number of rows</param>
/// <param name="n">Number of columns</param>
public Matrix(int m, int n)
{
_m = m;
_n = n;
_matrixArr = new double[m][];
for(int i = 0; i < m; i++)
{
_matrixArr[i] = new double[n];
}
}
/// <summary>
/// Get or set the value at the i-th and j-th index.
/// </summary>
/// <param name="i">Zero-based index</param>
/// <param name="j">Zero-based index</param>
/// <returns></returns>
public double this[int i, int j]
{
get
{
return _matrixArr[i][j];
}
set
{
_matrixArr[i][j] = value;
}
}
/// <summary>
/// Return the dimensions of this matrix
/// </summary>
public int[] Dim
{
get { return new int[] { _m, _n }; }
}
/// <summary>
/// Compares the dimensions of Matrix a and Matrix b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool IsSameDim(Matrix a, Matrix b)
{
if(a.Dim[0] == b.Dim[0] && a.Dim[1] == b.Dim[1])
{
return true;
}
return false;
}
/// <summary>
/// Casts and copies a 2D array by value into a Matrix object
/// </summary>
/// <param name="arr"></param>
public static implicit operator Matrix(double[,] arr)
{
int numRows = arr.GetLength(0);
int numColumns = arr.GetLength(1);
Matrix returnMat = new Matrix(numRows, numColumns);
for(int i = 0; i < numRows; i++)
{
for(int j = 0; j < numColumns; j++)
{
returnMat._matrixArr[i][j] = arr[i, j];
}
}
return returnMat;
}
#region Array math functions
/// <summary>
/// The function used to add two arrays
/// </summary>
public static Func<double[][], double[][], double[][]> Sum;
/// <summary>
/// The function used to subtract two arrays
/// </summary>
public static Func<double[][], double[][], double[][]> Subtract;
/// <summary>
/// The function used to multiply an array by a double
/// </summary>
public static Func<double, double[][], double[][]> ScalarMultiply;
/// <summary>
/// The function used to dot multiply two arrays
/// </summary>
public static Func<double[][], double[][], double[][]> DotMultiply;
/// <summary>
/// The function used to element-wise multiply two arrays
/// </summary>
public static Func<double[][], double[][], double[][]> HadamardProduct;
#endregion
public static void SetMathFuncToDefault()
{
Sum = DefaultSum;
Subtract = DefaultSubtract;
ScalarMultiply = DefaultScalarMultiply;
DotMultiply = DefaultDotMultiply;
HadamardProduct = DefaultHadamard;
}
/// <summary>
/// Default Matrix sum function
/// </summary>
/// <param name="matrix1"></param>
/// <param name="matrix2"></param>
/// <returns></returns>
protected static double[][] DefaultSum(double[][] matrix1, double[][] matrix2)
{
int numRows = matrix1.Length;
int numCol = matrix1[0].Length;
double[][] Calc = new double[numRows][];
for (int i = 0; i < numRows; i++)
{
Calc[i] = new double[numCol];
for (int j = 0; j < numCol; j++)
{
Calc[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return Calc;
}
/// <summary>
/// Returns the sum of Matrix a and Matrix b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Matrix operator +(Matrix a, Matrix b)
{
if (Matrix.IsSameDim(a, b))
{
Matrix result = new Matrix(a._m, a._n);
result._matrixArr = Matrix.Sum(a._matrixArr, b._matrixArr);
return result;
}
else
{
throw new ArgumentException();
}
}
/// <summary>
/// Default Matrix subtraction function
/// </summary>
/// <param name="matrix1"></param>
/// <param name="matrix2"></param>
/// <returns></returns>
protected static double[][] DefaultSubtract(double[][] matrix1, double[][] matrix2)
{
int numRows = matrix1.Length;
int numCol = matrix1[0].Length;
double[][] Calc = new double[numRows][];
for (int i = 0; i < numRows; i++)
{
Calc[i] = new double[numCol];
for (int j = 0; j < numCol; j++)
{
Calc[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return Calc;
}
/// <summary>
/// Returns the difference of Matrix a and Matrix b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Matrix operator -(Matrix a, Matrix b)
{
if (Matrix.IsSameDim(a, b))
{
Matrix result = new Matrix(a._m, a._n);
result._matrixArr = Matrix.Subtract(a._matrixArr, b._matrixArr);
return result;
}
else
{
throw new ArgumentException();
}
}
/// <summary>
/// Default scalar matrix mulitply function
/// </summary>
/// <param name="k"></param>
/// <param name="matrix1"></param>
/// <returns></returns>
protected static double[][] DefaultScalarMultiply(double k, double[][] matrix1)
{
int numRows = matrix1.Length;
int numCol = matrix1[0].Length;
double[][] Calc = new double[numRows][];
for (int i = 0; i < numRows; i++)
{
Calc[i] = new double[numCol];
for (int j = 0; j < numCol; j++)
{
Calc[i][j] = matrix1[i][j] * k;
}
}
return Calc;
}
/// <summary>
/// Returns the scalar multiple of Matrix a
/// </summary>
/// <param name="k">Scalar multiple</param>
/// <param name="a">Matrix</param>
/// <returns></returns>
public static Matrix operator *(double k, Matrix a)
{
Matrix result = new Matrix(a._m, a._n);
result._matrixArr = Matrix.ScalarMultiply(k, a._matrixArr);
return result;
}
/// <summary>
/// Returns the scalar multiple of Matrix a
/// </summary>
/// <param name="k">Scalar multiple</param>
/// <param name="a">Matrix</param>
/// <returns></returns>
public static Matrix operator *(Matrix a, double k)
{
return k * a;
}
/// <summary>
/// Returns the Matrix a divided by k
/// </summary>
/// <param name="k">Scalar divisor</param>
/// <param name="a">Matrix</param>
/// <returns></returns>
public static Matrix operator /(Matrix a, double k)
{
return (1 / k) * a;
}
/// <summary>
/// Default Matrix element-wise multiply function
/// </summary>
/// <param name="matrix1"></param>
/// <param name="matrix2"></param>
/// <returns></returns>
protected static double[][] DefaultHadamard(double[][] matrix1, double[][] matrix2)
{
int numRows = matrix1.Length;
int numCol = matrix1[0].Length;
double[][] Calc = new double[numRows][];
for (int i = 0; i < numRows; i++)
{
Calc[i] = new double[numCol];
for (int j = 0; j < numCol; j++)
{
Calc[i][j] = matrix1[i][j] * matrix2[i][j];
}
}
return Calc;
}
/// <summary>
/// Returns the Hadamard product of Matrix a and Matrix b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Matrix operator ^(Matrix a, Matrix b)
{
if (Matrix.IsSameDim(a, b))
{
Matrix result = new Matrix(a._m, a._n);
result._matrixArr = Matrix.DefaultHadamard(a._matrixArr, b._matrixArr);
return result;
}
else
{
throw new ArgumentException();
}
}
/// <summary>
/// Default Matrix dot multiply function
/// </summary>
/// <param name="matrix1"></param>
/// <param name="matrix2"></param>
/// <returns></returns>
protected static double[][] DefaultDotMultiply(double[][] matrix1, double[][] matrix2)
{
int numRows = matrix1.Length;
int numCol = matrix2[0].Length;
int numCol1 = matrix1[0].Length;
double[][] Calc = new double[numRows][];
for (int i = 0; i < numRows; i++)
{
Calc[i] = new double[numCol];
for (int j = 0; j < numCol; j++)
{
for(int k = 0; k < numCol1; k++)
{
Calc[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return Calc;
}
/// <summary>
/// Returns the dot product of Matrix a and Matrix b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Matrix operator *(Matrix a, Matrix b)
{
if (a.Dim[1] == b.Dim[0])
{
Matrix result = new Matrix(a._m, b._n);
result._matrixArr = Matrix.DotMultiply(a._matrixArr, b._matrixArr);
return result;
}
else
{
throw new ArgumentException();
}
}
/// <summary>
/// Returns the negative multiple of Matrix a
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public static Matrix operator -(Matrix a)
{
Matrix result = new Matrix(a._m, a._n);
result._matrixArr = Matrix.ScalarMultiply(-1, a._matrixArr);
return result;
}
}
}
|
using System.Net.Mail;
using System.Net;
using System.Text;
namespace ShCore.Utility
{
/// <summary>
/// Mailer
/// </summary>
public class ShMailer
{
#region Properties
private SmtpClient smtp = new SmtpClient();
public SmtpClient Smtp
{
set { this.smtp = value; }
get { return this.smtp; }
}
private MailMessage mail = new MailMessage();
public MailMessage Mail
{
set { this.mail = value; }
get { return this.mail; }
}
private string emailFrom = "linkit.vn@gmail.com";
public string EmailFrom
{
set { this.emailFrom = value; }
get { return this.emailFrom; }
}
private string passwordEmailFrom = "sonpcdct";
public string PasswordEmailFrom
{
set { this.passwordEmailFrom = value; }
get { return this.passwordEmailFrom; }
}
private string sendBy = "Mạng xã hội tin học LinkIT";
public string SendBy
{
set { this.sendBy = value; }
get { return this.sendBy; }
}
#endregion
/// <summary>
/// Constructor
/// </summary>
public ShMailer()
{
this.Smtp.EnableSsl = true;
this.Smtp.Host = "smtp.gmail.com";
this.Smtp.Credentials = new NetworkCredential(emailFrom, passwordEmailFrom);
mail.From = new MailAddress(emailFrom, sendBy);
mail.BodyEncoding = mail.SubjectEncoding = Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
}
/// <summary>
/// Gửi mail
/// </summary>
/// <returns></returns>
public bool Send()
{
try
{
smtp.Send(mail);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Thực hiện gửi mail
/// </summary>
/// <param name="title"></param>
/// <param name="content"></param>
/// <param name="to"></param>
/// <returns></returns>
public static bool SendMail(string title, string content,params string[] to)
{
var shmailer = new ShMailer();
for (var i = 0; i < to.Length;i++ )
shmailer.Mail.To.Add(to[i]);
shmailer.Mail.Subject = title;
shmailer.Mail.Body = content;
return shmailer.Send();
}
}
}
|
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace ScripterTestCmd
{
public class TreeNode : ITreeNode
{
public Guid Id { get; set; }
public string Parent { get; set; }
public string Name { get; set; }
public string Path => $"{Parent}/{Name}".Trim('/');
public bool IsFolder { get; set; }
public string Extension { get; set; }
public JToken Content { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public ITreeNode[] Children { get; set; }
}
public static class TreeNodeExtensions
{
public static ITreeNode GetNodeByPath(this ITreeNode treeNode, string path)
{
var splitted = path.Split('/');
var current = treeNode;
foreach (var s in splitted)
{
current = current.Children.FirstOrDefault(n => n.Name == s);
if (current == null)
{
return null;
}
}
return current;
}
}
}
|
using System;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.Web.Templates.Payment;
namespace NopSolutions.NopCommerce.Web.Administration.Payment.Assist
{
public partial class ConfigurePaymentMethod : BaseNopAdministrationUserControl, IConfigurePaymentMethodModule
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var setting = SettingManager.GetSettingByName("PaymentMethod.Assist.OkUrl");
if (setting == null)
{
SettingManager.AddSetting("PaymentMethod.Assist.OkUrl", string.Format("{0}{1}", Request.Url.GetLeftPart(UriPartial.Authority), "\\Assist.aspx?status=succeeded&orderId={0}"), string.Empty);
SettingManager.AddSetting("PaymentMethod.Assist.NoUrl", string.Format("{0}{1}", Request.Url.GetLeftPart(UriPartial.Authority), "\\Assist.aspx?status=failed&orderId={0}"), string.Empty);
SettingManager.AddSetting("PaymentMethod.Assist.TestMode", "true", string.Empty);
SettingManager.AddSetting("PaymentMethod.Assist.PaymentUrl", "https://test.paysec.by/pay/order.cfm", string.Empty);
SettingManager.AddSetting("PaymentMethod.Assist.ServiceFee", "5", string.Empty);
}
BindData();
}
}
private void BindData()
{
tbOKUrl.Text = SettingManager.GetSettingValue("PaymentMethod.Assist.OkUrl");
tbNoUrl.Text = SettingManager.GetSettingValue("PaymentMethod.Assist.NoUrl");
tbTestMode.Text = SettingManager.GetSettingValue("PaymentMethod.Assist.TestMode");
tbUrl.Text = SettingManager.GetSettingValue("PaymentMethod.Assist.PaymentUrl");
tbServiceFee.Text = SettingManager.GetSettingValue("PaymentMethod.Assist.ServiceFee");
}
public void Save()
{
SettingManager.SetParam("PaymentMethod.Assist.OkUrl", tbOKUrl.Text);
SettingManager.SetParam("PaymentMethod.Assist.NoUrl", tbNoUrl.Text);
SettingManager.SetParam("PaymentMethod.Assist.TestMode", tbTestMode.Text);
SettingManager.SetParam("PaymentMethod.Assist.PaymentUrl", tbUrl.Text);
SettingManager.SetParam("PaymentMethod.Assist.ServiceFee", tbServiceFee.Text);
}
}
} |
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// Defines Destiny.HistoricalStats.Definitions.UnitType
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum DestinyHistoricalStatsDefinitionsUnitType
{
/// <summary>
///
/// </summary>
[EnumMember(Value = "0")]
None,
/// <summary>
/// Indicates the statistic is a simple count of something.
/// </summary>
[EnumMember(Value = "1")]
Count,
/// <summary>
/// Indicates the statistic is a per game average.
/// </summary>
[EnumMember(Value = "2")]
PerGame,
/// <summary>
/// Indicates the number of seconds
/// </summary>
[EnumMember(Value = "3")]
Seconds,
/// <summary>
/// Indicates the number of points earned
/// </summary>
[EnumMember(Value = "4")]
Points,
/// <summary>
/// Values represents a team ID
/// </summary>
[EnumMember(Value = "5")]
Team,
/// <summary>
/// Values represents a distance (units to-be-determined)
/// </summary>
[EnumMember(Value = "6")]
Distance,
/// <summary>
/// Ratio represented as a whole value from 0 to 100.
/// </summary>
[EnumMember(Value = "7")]
Percent,
/// <summary>
/// Ratio of something, shown with decimal places
/// </summary>
[EnumMember(Value = "8")]
Ratio,
/// <summary>
/// True or false
/// </summary>
[EnumMember(Value = "9")]
Boolean,
/// <summary>
/// The stat is actually a weapon type.
/// </summary>
[EnumMember(Value = "10")]
WeaponType,
/// <summary>
/// Indicates victory, defeat, or something in between.
/// </summary>
[EnumMember(Value = "11")]
Standing,
/// <summary>
/// Number of milliseconds some event spanned. For example, race time, or lap time.
/// </summary>
[EnumMember(Value = "12")]
Milliseconds
}
}
|
namespace TipsAndTricksLibrary.Extensions
{
using System;
using System.Collections.Generic;
public static class ArrayExtensions
{
public static int? UpperBound<TSource>(this IReadOnlyList<TSource> source, TSource value, IComparer<TSource> itemsComparer = null,
int? startIndex = null, int? endIndex = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (source.Count == 0)
throw new ArgumentException(nameof(source));
var first = startIndex ?? 0;
if (first < 0 || first >= source.Count)
throw new ArgumentException(nameof(startIndex));
var last = (endIndex ?? source.Count - 1) + 1;
if (first > last || last > source.Count)
throw new ArgumentException(nameof(endIndex));
var comparer = itemsComparer ?? Comparer<TSource>.Default;
var count = last - first;
while (count > 0)
{
var current = first;
var step = count/2;
current += step;
if (comparer.Compare(value, source[current]) >= 0)
{
first = current + 1;
count -= step + 1;
}
else
count = step;
}
return first == last ? (int?) null : first;
}
public static int? UpperBound<TSource>(this IReadOnlyList<TSource> source, TSource value, Comparison<TSource> comparison,
int? startIndex = null, int? endIndex = null)
{
if(comparison == null)
throw new ArgumentNullException(nameof(comparison));
return UpperBound(source, value, Comparer<TSource>.Create(comparison), startIndex, endIndex);
}
public static int? LowerBound<TSource>(this IReadOnlyList<TSource> source, TSource value, IComparer<TSource> itemsComparer = null,
int? startIndex = null, int? endIndex = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (source.Count == 0)
throw new ArgumentException(nameof(source));
var first = startIndex ?? 0;
if (first < 0 || first >= source.Count)
throw new ArgumentException(nameof(startIndex));
var last = (endIndex ?? source.Count - 1) + 1;
if (first > last || last > source.Count)
throw new ArgumentException(nameof(endIndex));
var comparer = itemsComparer ?? Comparer<TSource>.Default;
var count = last - first;
while (count > 0)
{
var current = first;
var step = count / 2;
current += step;
if (comparer.Compare(value, source[current]) > 0)
{
first = current + 1;
count -= step + 1;
}
else
count = step;
}
return first == last ? (int?)null : first;
}
public static int? LowerBound<TSource>(this IReadOnlyList<TSource> source, TSource value, Comparison<TSource> comparison,
int? startIndex = null, int? endIndex = null)
{
if (comparison == null)
throw new ArgumentNullException(nameof(comparison));
return LowerBound(source, value, Comparer<TSource>.Create(comparison), startIndex, endIndex);
}
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.SqlServer.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Migrations
{
public class SqlServerMigrationsSqlGeneratorTest : MigrationsSqlGeneratorTestBase
{
[ConditionalFact]
public void CreateIndexOperation_unique_online()
{
Generate(
new CreateIndexOperation
{
Name = "IX_People_Name",
Table = "People",
Schema = "dbo",
Columns = new[] { "FirstName", "LastName" },
IsUnique = true,
[SqlServerAnnotationNames.CreatedOnline] = true
});
AssertSql(
@"CREATE UNIQUE INDEX [IX_People_Name] ON [dbo].[People] ([FirstName], [LastName]) WHERE [FirstName] IS NOT NULL AND [LastName] IS NOT NULL WITH (ONLINE = ON);
");
}
[ConditionalFact]
public virtual void AddColumnOperation_identity_legacy()
{
Generate(
new AddColumnOperation
{
Table = "People",
Name = "Id",
ClrType = typeof(int),
ColumnType = "int",
DefaultValue = 0,
IsNullable = false,
[SqlServerAnnotationNames.ValueGenerationStrategy] =
SqlServerValueGenerationStrategy.IdentityColumn
});
AssertSql(
@"ALTER TABLE [People] ADD [Id] int NOT NULL IDENTITY;
");
}
public override void AddColumnOperation_without_column_type()
{
base.AddColumnOperation_without_column_type();
AssertSql(
@"ALTER TABLE [People] ADD [Alias] nvarchar(max) NOT NULL;
");
}
public override void AddColumnOperation_with_unicode_no_model()
{
base.AddColumnOperation_with_unicode_no_model();
AssertSql(
@"ALTER TABLE [Person] ADD [Name] varchar(max) NULL;
");
}
public override void AddColumnOperation_with_fixed_length_no_model()
{
base.AddColumnOperation_with_fixed_length_no_model();
AssertSql(
@"ALTER TABLE [Person] ADD [Name] char(100) NULL;
");
}
public override void AddColumnOperation_with_maxLength_no_model()
{
base.AddColumnOperation_with_maxLength_no_model();
AssertSql(
@"ALTER TABLE [Person] ADD [Name] nvarchar(30) NULL;
");
}
public override void AddColumnOperation_with_maxLength_overridden()
{
base.AddColumnOperation_with_maxLength_overridden();
AssertSql(
@"ALTER TABLE [Person] ADD [Name] nvarchar(32) NULL;
");
}
public override void AddColumnOperation_with_precision_and_scale_overridden()
{
base.AddColumnOperation_with_precision_and_scale_overridden();
AssertSql(
@"ALTER TABLE [Person] ADD [Pi] decimal(15,10) NOT NULL;
");
}
public override void AddColumnOperation_with_precision_and_scale_no_model()
{
base.AddColumnOperation_with_precision_and_scale_no_model();
AssertSql(
@"ALTER TABLE [Person] ADD [Pi] decimal(20,7) NOT NULL;
");
}
public override void AddColumnOperation_with_unicode_overridden()
{
base.AddColumnOperation_with_unicode_overridden();
AssertSql(
@"ALTER TABLE [Person] ADD [Name] nvarchar(max) NULL;
");
}
[ConditionalFact]
public virtual void AddColumnOperation_with_rowversion_overridden()
{
Generate(
modelBuilder => modelBuilder.Entity<Person>().Property<byte[]>("RowVersion"),
new AddColumnOperation
{
Table = "Person",
Name = "RowVersion",
ClrType = typeof(byte[]),
IsRowVersion = true,
IsNullable = true
});
AssertSql(
@"ALTER TABLE [Person] ADD [RowVersion] rowversion NULL;
");
}
[ConditionalFact]
public virtual void AddColumnOperation_with_rowversion_no_model()
{
Generate(
new AddColumnOperation
{
Table = "Person",
Name = "RowVersion",
ClrType = typeof(byte[]),
IsRowVersion = true,
IsNullable = true
});
AssertSql(
@"ALTER TABLE [Person] ADD [RowVersion] rowversion NULL;
");
}
public override void AlterColumnOperation_without_column_type()
{
base.AlterColumnOperation_without_column_type();
AssertSql(
@"DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[People]') AND [c].[name] = N'LuckyNumber');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [People] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [People] ALTER COLUMN [LuckyNumber] int NOT NULL;
");
}
public override void AddForeignKeyOperation_without_principal_columns()
{
base.AddForeignKeyOperation_without_principal_columns();
AssertSql(
@"ALTER TABLE [People] ADD FOREIGN KEY ([SpouseId]) REFERENCES [People];
");
}
[ConditionalFact]
public virtual void AlterColumnOperation_with_identity_legacy()
{
Generate(
new AlterColumnOperation
{
Table = "People",
Name = "Id",
ClrType = typeof(int),
[SqlServerAnnotationNames.ValueGenerationStrategy] =
SqlServerValueGenerationStrategy.IdentityColumn
});
AssertSql(
@"DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[People]') AND [c].[name] = N'Id');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [People] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [People] ALTER COLUMN [Id] int NOT NULL;
");
}
[ConditionalFact]
public virtual void AlterColumnOperation_with_index_no_oldColumn()
{
Generate(
modelBuilder => modelBuilder
.HasAnnotation(CoreAnnotationNames.ProductVersion, "1.0.0-rtm")
.Entity<Person>(
x =>
{
x.Property<string>("Name").HasMaxLength(30);
x.HasIndex("Name");
}),
new AlterColumnOperation
{
Table = "Person",
Name = "Name",
ClrType = typeof(string),
MaxLength = 30,
IsNullable = true,
OldColumn = new AddColumnOperation()
});
AssertSql(
@"DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Person]') AND [c].[name] = N'Name');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Person] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Person] ALTER COLUMN [Name] nvarchar(30) NULL;
");
}
[ConditionalFact]
public virtual void AlterColumnOperation_with_added_index()
{
Generate(
modelBuilder => modelBuilder
.HasAnnotation(CoreAnnotationNames.ProductVersion, "1.1.0")
.Entity<Person>(
x =>
{
x.Property<string>("Name").HasMaxLength(30);
x.HasIndex("Name");
}),
new AlterColumnOperation
{
Table = "Person",
Name = "Name",
ClrType = typeof(string),
MaxLength = 30,
IsNullable = true,
OldColumn = new AddColumnOperation { ClrType = typeof(string), IsNullable = true }
},
new CreateIndexOperation
{
Name = "IX_Person_Name",
Table = "Person",
Columns = new[] { "Name" }
});
AssertSql(
@"DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Person]') AND [c].[name] = N'Name');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Person] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Person] ALTER COLUMN [Name] nvarchar(30) NULL;
GO
CREATE INDEX [IX_Person_Name] ON [Person] ([Name]);
");
}
[ConditionalFact]
public virtual void AlterColumnOperation_with_added_index_no_oldType()
{
Generate(
modelBuilder => modelBuilder
.HasAnnotation(CoreAnnotationNames.ProductVersion, "2.1.0")
.Entity<Person>(
x =>
{
x.Property<string>("Name");
x.HasIndex("Name");
}),
new AlterColumnOperation
{
Table = "Person",
Name = "Name",
ClrType = typeof(string),
IsNullable = true,
OldColumn = new AddColumnOperation { ClrType = typeof(string), IsNullable = true }
},
new CreateIndexOperation
{
Name = "IX_Person_Name",
Table = "Person",
Columns = new[] { "Name" }
});
AssertSql(
@"DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Person]') AND [c].[name] = N'Name');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Person] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Person] ALTER COLUMN [Name] nvarchar(450) NULL;
GO
CREATE INDEX [IX_Person_Name] ON [Person] ([Name]);
");
}
[ConditionalFact]
public virtual void AlterColumnOperation_identity_legacy()
{
Generate(
modelBuilder => modelBuilder.HasAnnotation(CoreAnnotationNames.ProductVersion, "1.1.0"),
new AlterColumnOperation
{
Table = "Person",
Name = "Id",
ClrType = typeof(long),
[SqlServerAnnotationNames.ValueGenerationStrategy] = SqlServerValueGenerationStrategy.IdentityColumn,
OldColumn = new AddColumnOperation
{
ClrType = typeof(int),
[SqlServerAnnotationNames.ValueGenerationStrategy] = SqlServerValueGenerationStrategy.IdentityColumn
}
});
AssertSql(
@"DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Person]') AND [c].[name] = N'Id');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Person] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Person] ALTER COLUMN [Id] bigint NOT NULL;
");
}
[ConditionalFact]
public virtual void AlterColumnOperation_add_identity_legacy()
{
var ex = Assert.Throws<InvalidOperationException>(
() => Generate(
modelBuilder => modelBuilder.HasAnnotation(CoreAnnotationNames.ProductVersion, "1.1.0"),
new AlterColumnOperation
{
Table = "Person",
Name = "Id",
ClrType = typeof(int),
[SqlServerAnnotationNames.ValueGenerationStrategy] = SqlServerValueGenerationStrategy.IdentityColumn,
OldColumn = new AddColumnOperation { ClrType = typeof(int) }
}));
Assert.Equal(SqlServerStrings.AlterIdentityColumn, ex.Message);
}
[ConditionalFact]
public virtual void AlterColumnOperation_remove_identity_legacy()
{
var ex = Assert.Throws<InvalidOperationException>(
() => Generate(
modelBuilder => modelBuilder.HasAnnotation(CoreAnnotationNames.ProductVersion, "1.1.0"),
new AlterColumnOperation
{
Table = "Person",
Name = "Id",
ClrType = typeof(int),
OldColumn = new AddColumnOperation
{
ClrType = typeof(int),
[SqlServerAnnotationNames.ValueGenerationStrategy] = SqlServerValueGenerationStrategy.IdentityColumn
}
}));
Assert.Equal(SqlServerStrings.AlterIdentityColumn, ex.Message);
}
[ConditionalFact]
public virtual void CreateDatabaseOperation()
{
Generate(
new SqlServerCreateDatabaseOperation { Name = "Northwind" });
AssertSql(
@"CREATE DATABASE [Northwind];
GO
IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [Northwind] SET READ_COMMITTED_SNAPSHOT ON;
END;
");
}
[ConditionalFact]
public virtual void CreateDatabaseOperation_with_filename()
{
Generate(
new SqlServerCreateDatabaseOperation { Name = "Northwind", FileName = "Narf.mdf" });
var expectedFile = Path.GetFullPath("Narf.mdf");
var expectedLog = Path.GetFullPath("Narf_log.ldf");
AssertSql(
$@"CREATE DATABASE [Northwind]
ON (NAME = N'Narf', FILENAME = N'{expectedFile}')
LOG ON (NAME = N'Narf_log', FILENAME = N'{expectedLog}');
GO
IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [Northwind] SET READ_COMMITTED_SNAPSHOT ON;
END;
");
}
[ConditionalFact]
public virtual void CreateDatabaseOperation_with_filename_and_datadirectory()
{
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
Generate(
new SqlServerCreateDatabaseOperation { Name = "Northwind", FileName = "|DataDirectory|Narf.mdf" });
var expectedFile = Path.Combine(baseDirectory, "Narf.mdf");
var expectedLog = Path.Combine(baseDirectory, "Narf_log.ldf");
AssertSql(
$@"CREATE DATABASE [Northwind]
ON (NAME = N'Narf', FILENAME = N'{expectedFile}')
LOG ON (NAME = N'Narf_log', FILENAME = N'{expectedLog}');
GO
IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [Northwind] SET READ_COMMITTED_SNAPSHOT ON;
END;
");
}
[ConditionalFact]
public virtual void CreateDatabaseOperation_with_filename_and_custom_datadirectory()
{
var dataDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory);
Generate(
new SqlServerCreateDatabaseOperation { Name = "Northwind", FileName = "|DataDirectory|Narf.mdf" });
AppDomain.CurrentDomain.SetData("DataDirectory", null);
var expectedFile = Path.Combine(dataDirectory, "Narf.mdf");
var expectedLog = Path.Combine(dataDirectory, "Narf_log.ldf");
AssertSql(
$@"CREATE DATABASE [Northwind]
ON (NAME = N'Narf', FILENAME = N'{expectedFile}')
LOG ON (NAME = N'Narf_log', FILENAME = N'{expectedLog}');
GO
IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [Northwind] SET READ_COMMITTED_SNAPSHOT ON;
END;
");
}
[ConditionalFact]
public virtual void CreateDatabaseOperation_with_collation()
{
Generate(
new SqlServerCreateDatabaseOperation { Name = "Northwind", Collation = "German_PhoneBook_CI_AS" });
AssertSql(
@"CREATE DATABASE [Northwind]
COLLATE German_PhoneBook_CI_AS;
GO
IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [Northwind] SET READ_COMMITTED_SNAPSHOT ON;
END;
");
}
[ConditionalFact]
public virtual void AlterDatabaseOperation_collation()
{
Generate(
new AlterDatabaseOperation { Collation = "German_PhoneBook_CI_AS" });
Assert.Contains(
"COLLATE German_PhoneBook_CI_AS",
Sql);
}
[ConditionalFact]
public virtual void AlterDatabaseOperation_collation_to_default()
{
Generate(
new AlterDatabaseOperation
{
Collation = null,
OldDatabase =
{
Collation = "SQL_Latin1_General_CP1_CI_AS"
}
});
AssertSql(
@"BEGIN
DECLARE @db_name nvarchar(max) = DB_NAME();
DECLARE @defaultCollation nvarchar(max) = CAST(SERVERPROPERTY('Collation') AS nvarchar(max));
EXEC(N'ALTER DATABASE [' + @db_name + '] COLLATE ' + @defaultCollation + N';');
END
");
}
[ConditionalFact]
public virtual void AlterDatabaseOperation_memory_optimized()
{
Generate(
new AlterDatabaseOperation { [SqlServerAnnotationNames.MemoryOptimized] = true });
Assert.Contains(
"CONTAINS MEMORY_OPTIMIZED_DATA;",
Sql);
}
[ConditionalFact]
public virtual void DropDatabaseOperation()
{
Generate(
new SqlServerDropDatabaseOperation { Name = "Northwind" });
AssertSql(
@"IF SERVERPROPERTY('EngineEdition') <> 5
BEGIN
ALTER DATABASE [Northwind] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
END;
GO
DROP DATABASE [Northwind];
");
}
[ConditionalFact]
public virtual void DropIndexOperations_throws_when_no_table()
{
var migrationBuilder = new MigrationBuilder("SqlServer");
migrationBuilder.DropIndex(
name: "IX_Name");
var ex = Assert.Throws<InvalidOperationException>(
() => Generate(migrationBuilder.Operations.ToArray()));
Assert.Equal(SqlServerStrings.IndexTableRequired, ex.Message);
}
[ConditionalFact]
public virtual void MoveSequenceOperation_legacy()
{
Generate(
new RenameSequenceOperation
{
Name = "EntityFrameworkHiLoSequence",
Schema = "dbo",
NewSchema = "my"
});
AssertSql(
@"ALTER SCHEMA [my] TRANSFER [dbo].[EntityFrameworkHiLoSequence];
");
}
[ConditionalFact]
public virtual void MoveTableOperation_legacy()
{
Generate(
new RenameTableOperation
{
Name = "People",
Schema = "dbo",
NewSchema = "hr"
});
AssertSql(
@"ALTER SCHEMA [hr] TRANSFER [dbo].[People];
");
}
[ConditionalFact]
public virtual void RenameIndexOperations_throws_when_no_table()
{
var migrationBuilder = new MigrationBuilder("SqlServer");
migrationBuilder.RenameIndex(
name: "IX_OldIndex",
newName: "IX_NewIndex");
var ex = Assert.Throws<InvalidOperationException>(
() => Generate(migrationBuilder.Operations.ToArray()));
Assert.Equal(SqlServerStrings.IndexTableRequired, ex.Message);
}
[ConditionalFact]
public virtual void RenameSequenceOperation_legacy()
{
Generate(
new RenameSequenceOperation
{
Name = "EntityFrameworkHiLoSequence",
Schema = "dbo",
NewName = "MySequence"
});
AssertSql(
@"EXEC sp_rename N'[dbo].[EntityFrameworkHiLoSequence]', N'MySequence';
");
}
[ConditionalFact]
public override void RenameTableOperation_legacy()
{
base.RenameTableOperation_legacy();
AssertSql(
@"EXEC sp_rename N'[dbo].[People]', N'Person';
");
}
public override void RenameTableOperation()
{
base.RenameTableOperation();
AssertSql(
@"EXEC sp_rename N'[dbo].[People]', N'Person';
");
}
[ConditionalFact]
public virtual void SqlOperation_handles_backslash()
{
Generate(
new SqlOperation { Sql = @"-- Multiline \" + EOL + "comment" });
AssertSql(
@"-- Multiline comment
");
}
[ConditionalFact]
public virtual void SqlOperation_ignores_sequential_gos()
{
Generate(
new SqlOperation { Sql = "-- Ready set" + EOL + "GO" + EOL + "GO" });
AssertSql(
@"-- Ready set
");
}
[ConditionalFact]
public virtual void SqlOperation_handles_go()
{
Generate(
new SqlOperation { Sql = "-- I" + EOL + "go" + EOL + "-- Too" });
AssertSql(
@"-- I
GO
-- Too
");
}
[ConditionalFact]
public virtual void SqlOperation_handles_go_with_count()
{
Generate(
new SqlOperation { Sql = "-- I" + EOL + "GO 2" });
AssertSql(
@"-- I
GO
-- I
");
}
[ConditionalFact]
public virtual void SqlOperation_ignores_non_go()
{
Generate(
new SqlOperation { Sql = "-- I GO 2" });
AssertSql(
@"-- I GO 2
");
}
public override void SqlOperation()
{
base.SqlOperation();
AssertSql(
@"-- I <3 DDL
");
}
public override void InsertDataOperation_all_args_spatial()
{
base.InsertDataOperation_all_args_spatial();
AssertSql(
@"IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id', N'Full Name', N'Geometry') AND [object_id] = OBJECT_ID(N'[dbo].[People]'))
SET IDENTITY_INSERT [dbo].[People] ON;
INSERT INTO [dbo].[People] ([Id], [Full Name], [Geometry])
VALUES (0, NULL, NULL),
(1, 'Daenerys Targaryen', NULL),
(2, 'John Snow', NULL),
(3, 'Arya Stark', NULL),
(4, 'Harry Strickland', NULL),
(5, 'The Imp', NULL),
(6, 'The Kingslayer', NULL),
(7, 'Aemon Targaryen', geography::Parse('GEOMETRYCOLLECTION (LINESTRING (1.1 2.2 NULL, 2.2 2.2 NULL, 2.2 1.1 NULL, 7.1 7.2 NULL), LINESTRING (7.1 7.2 NULL, 20.2 20.2 NULL, 20.2 1.1 NULL, 70.1 70.2 NULL), MULTIPOINT ((1.1 2.2 NULL), (2.2 2.2 NULL), (2.2 1.1 NULL)), POLYGON ((1.1 2.2 NULL, 2.2 2.2 NULL, 2.2 1.1 NULL, 1.1 2.2 NULL)), POLYGON ((10.1 20.2 NULL, 20.2 20.2 NULL, 20.2 10.1 NULL, 10.1 20.2 NULL)), POINT (1.1 2.2 3.3), MULTILINESTRING ((1.1 2.2 NULL, 2.2 2.2 NULL, 2.2 1.1 NULL, 7.1 7.2 NULL), (7.1 7.2 NULL, 20.2 20.2 NULL, 20.2 1.1 NULL, 70.1 70.2 NULL)), MULTIPOLYGON (((10.1 20.2 NULL, 20.2 20.2 NULL, 20.2 10.1 NULL, 10.1 20.2 NULL)), ((1.1 2.2 NULL, 2.2 2.2 NULL, 2.2 1.1 NULL, 1.1 2.2 NULL))))'));
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id', N'Full Name', N'Geometry') AND [object_id] = OBJECT_ID(N'[dbo].[People]'))
SET IDENTITY_INSERT [dbo].[People] OFF;
");
}
// The test data we're using is geographic but is represented in NTS as a GeometryCollection
protected override string GetGeometryCollectionStoreType()
=> "geography";
public override void InsertDataOperation_required_args()
{
base.InsertDataOperation_required_args();
AssertSql(
@"IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'First Name') AND [object_id] = OBJECT_ID(N'[People]'))
SET IDENTITY_INSERT [People] ON;
INSERT INTO [People] ([First Name])
VALUES (N'John');
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'First Name') AND [object_id] = OBJECT_ID(N'[People]'))
SET IDENTITY_INSERT [People] OFF;
");
}
public override void InsertDataOperation_required_args_composite()
{
base.InsertDataOperation_required_args_composite();
AssertSql(
@"IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'First Name', N'Last Name') AND [object_id] = OBJECT_ID(N'[People]'))
SET IDENTITY_INSERT [People] ON;
INSERT INTO [People] ([First Name], [Last Name])
VALUES (N'John', N'Snow');
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'First Name', N'Last Name') AND [object_id] = OBJECT_ID(N'[People]'))
SET IDENTITY_INSERT [People] OFF;
");
}
public override void InsertDataOperation_required_args_multiple_rows()
{
base.InsertDataOperation_required_args_multiple_rows();
AssertSql(
@"IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'First Name') AND [object_id] = OBJECT_ID(N'[People]'))
SET IDENTITY_INSERT [People] ON;
INSERT INTO [People] ([First Name])
VALUES (N'John'),
(N'Daenerys');
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'First Name') AND [object_id] = OBJECT_ID(N'[People]'))
SET IDENTITY_INSERT [People] OFF;
");
}
public override void InsertDataOperation_throws_for_unsupported_column_types()
{
base.InsertDataOperation_throws_for_unsupported_column_types();
}
public override void DeleteDataOperation_all_args()
{
base.DeleteDataOperation_all_args();
AssertSql(
@"DELETE FROM [People]
WHERE [First Name] = N'Hodor';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'Daenerys';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'John';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'Arya';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'Harry';
SELECT @@ROWCOUNT;
");
}
public override void DeleteDataOperation_all_args_composite()
{
base.DeleteDataOperation_all_args_composite();
AssertSql(
@"DELETE FROM [People]
WHERE [First Name] = N'Hodor' AND [Last Name] IS NULL;
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'Daenerys' AND [Last Name] = N'Targaryen';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'John' AND [Last Name] = N'Snow';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'Arya' AND [Last Name] = N'Stark';
SELECT @@ROWCOUNT;
DELETE FROM [People]
WHERE [First Name] = N'Harry' AND [Last Name] = N'Strickland';
SELECT @@ROWCOUNT;
");
}
public override void DeleteDataOperation_required_args()
{
base.DeleteDataOperation_required_args();
AssertSql(
@"DELETE FROM [People]
WHERE [Last Name] = N'Snow';
SELECT @@ROWCOUNT;
");
}
public override void DeleteDataOperation_required_args_composite()
{
base.DeleteDataOperation_required_args_composite();
AssertSql(
@"DELETE FROM [People]
WHERE [First Name] = N'John' AND [Last Name] = N'Snow';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_all_args()
{
base.UpdateDataOperation_all_args();
AssertSql(
@"UPDATE [People] SET [Birthplace] = N'Winterfell', [House Allegiance] = N'Stark', [Culture] = N'Northmen'
WHERE [First Name] = N'Hodor';
SELECT @@ROWCOUNT;
UPDATE [People] SET [Birthplace] = N'Dragonstone', [House Allegiance] = N'Targaryen', [Culture] = N'Valyrian'
WHERE [First Name] = N'Daenerys';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_all_args_composite()
{
base.UpdateDataOperation_all_args_composite();
AssertSql(
@"UPDATE [People] SET [House Allegiance] = N'Stark'
WHERE [First Name] = N'Hodor' AND [Last Name] IS NULL;
SELECT @@ROWCOUNT;
UPDATE [People] SET [House Allegiance] = N'Targaryen'
WHERE [First Name] = N'Daenerys' AND [Last Name] = N'Targaryen';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_all_args_composite_multi()
{
base.UpdateDataOperation_all_args_composite_multi();
AssertSql(
@"UPDATE [People] SET [Birthplace] = N'Winterfell', [House Allegiance] = N'Stark', [Culture] = N'Northmen'
WHERE [First Name] = N'Hodor' AND [Last Name] IS NULL;
SELECT @@ROWCOUNT;
UPDATE [People] SET [Birthplace] = N'Dragonstone', [House Allegiance] = N'Targaryen', [Culture] = N'Valyrian'
WHERE [First Name] = N'Daenerys' AND [Last Name] = N'Targaryen';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_all_args_multi()
{
base.UpdateDataOperation_all_args_multi();
AssertSql(
@"UPDATE [People] SET [Birthplace] = N'Dragonstone', [House Allegiance] = N'Targaryen', [Culture] = N'Valyrian'
WHERE [First Name] = N'Daenerys';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_required_args()
{
base.UpdateDataOperation_required_args();
AssertSql(
@"UPDATE [People] SET [House Allegiance] = N'Targaryen'
WHERE [First Name] = N'Daenerys';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_required_args_composite()
{
base.UpdateDataOperation_required_args_composite();
AssertSql(
@"UPDATE [People] SET [House Allegiance] = N'Targaryen'
WHERE [First Name] = N'Daenerys' AND [Last Name] = N'Targaryen';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_required_args_composite_multi()
{
base.UpdateDataOperation_required_args_composite_multi();
AssertSql(
@"UPDATE [People] SET [Birthplace] = N'Dragonstone', [House Allegiance] = N'Targaryen', [Culture] = N'Valyrian'
WHERE [First Name] = N'Daenerys' AND [Last Name] = N'Targaryen';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_required_args_multi()
{
base.UpdateDataOperation_required_args_multi();
AssertSql(
@"UPDATE [People] SET [Birthplace] = N'Dragonstone', [House Allegiance] = N'Targaryen', [Culture] = N'Valyrian'
WHERE [First Name] = N'Daenerys';
SELECT @@ROWCOUNT;
");
}
public override void UpdateDataOperation_required_args_multiple_rows()
{
base.UpdateDataOperation_required_args_multiple_rows();
AssertSql(
@"UPDATE [People] SET [House Allegiance] = N'Stark'
WHERE [First Name] = N'Hodor';
SELECT @@ROWCOUNT;
UPDATE [People] SET [House Allegiance] = N'Targaryen'
WHERE [First Name] = N'Daenerys';
SELECT @@ROWCOUNT;
");
}
public override void DefaultValue_with_line_breaks(bool isUnicode)
{
base.DefaultValue_with_line_breaks(isUnicode);
var storeType = isUnicode ? "nvarchar(max)" : "varchar(max)";
var unicodePrefix = isUnicode ? "N" : string.Empty;
var expectedSql = @$"CREATE TABLE [dbo].[TestLineBreaks] (
[TestDefaultValue] {storeType} NOT NULL DEFAULT CONCAT({unicodePrefix}CHAR(13), {unicodePrefix}CHAR(10), {unicodePrefix}'Various Line', {unicodePrefix}CHAR(13), {unicodePrefix}'Breaks', {unicodePrefix}CHAR(10))
);
";
AssertSql(expectedSql);
}
[ConditionalFact]
public virtual void AddColumn_generates_exec_when_computed_and_idempotent()
{
Generate(
modelBuilder => { },
migrationBuilder => migrationBuilder.AddColumn<int>(
name: "Column2",
table: "Table1",
computedColumnSql: "[Column1] + 1"),
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@"EXEC(N'ALTER TABLE [Table1] ADD [Column2] AS [Column1] + 1');
");
}
[ConditionalFact]
public virtual void AddCheckConstraint_generates_exec_when_idempotent()
{
Generate(
modelBuilder => { },
migrationBuilder => migrationBuilder.AddCheckConstraint(
name: "CK_Table1",
table: "Table1",
"[Column1] BETWEEN 0 AND 100"),
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@"EXEC(N'ALTER TABLE [Table1] ADD CONSTRAINT [CK_Table1] CHECK ([Column1] BETWEEN 0 AND 100)');
");
}
[ConditionalFact]
public virtual void CreateIndex_generates_exec_when_filter_and_idempotent()
{
Generate(
modelBuilder => { },
migrationBuilder => migrationBuilder.CreateIndex(
name: "IX_Table1_Column1",
table: "Table1",
column: "Column1",
filter: "[Column1] IS NOT NULL"),
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@"EXEC(N'CREATE INDEX [IX_Table1_Column1] ON [Table1] ([Column1]) WHERE [Column1] IS NOT NULL');
");
}
[ConditionalFact]
public virtual void CreateIndex_generates_exec_when_legacy_filter_and_idempotent()
{
Generate(
modelBuilder =>
{
modelBuilder
.HasAnnotation(CoreAnnotationNames.ProductVersion, "1.1.0")
.Entity("Table1").Property<int?>("Column1");
},
migrationBuilder => migrationBuilder.CreateIndex(
name: "IX_Table1_Column1",
table: "Table1",
column: "Column1",
unique: true),
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@"EXEC(N'CREATE UNIQUE INDEX [IX_Table1_Column1] ON [Table1] ([Column1]) WHERE [Column1] IS NOT NULL');
");
}
[ConditionalFact]
public virtual void DeleteData_generates_exec_when_idempotent()
{
Generate(
modelBuilder => { },
migrationBuilder => migrationBuilder
.DeleteData(
table: "Table1",
keyColumn: "Id",
keyColumnType: "int",
keyValue: 1),
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@$"EXEC(N'DELETE FROM [Table1]
WHERE [Id] = 1;
SELECT @@ROWCOUNT');
");
}
[ConditionalFact]
public virtual void InsertData_generates_exec_when_idempotent()
{
Generate(
modelBuilder => { },
migrationBuilder => migrationBuilder
.InsertData(
table: "Table1",
column: "Id",
columnType: "int",
value: 1),
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@$"IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id') AND [object_id] = OBJECT_ID(N'[Table1]'))
SET IDENTITY_INSERT [Table1] ON;
EXEC(N'INSERT INTO [Table1] ([Id])
VALUES (1)');
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id') AND [object_id] = OBJECT_ID(N'[Table1]'))
SET IDENTITY_INSERT [Table1] OFF;
");
}
[ConditionalFact]
public virtual void UpdateData_generates_exec_when_idempotent()
{
Generate(
modelBuilder => { },
migrationBuilder =>
{
var operation = migrationBuilder
.UpdateData(
table: "Table1",
keyColumnTypes: new[] { "int" },
keyColumns: new[] { "Id" },
keyValues: new object[] { 1 },
columns: new[] { "Column1" },
columnTypes: new[] { "int" },
values: new object[] { 2 });
},
MigrationsSqlGenerationOptions.Idempotent);
AssertSql(
@$"EXEC(N'UPDATE [Table1] SET [Column1] = 2
WHERE [Id] = 1;
SELECT @@ROWCOUNT');
");
}
public SqlServerMigrationsSqlGeneratorTest()
: base(
SqlServerTestHelpers.Instance,
new ServiceCollection().AddEntityFrameworkSqlServerNetTopologySuite(),
SqlServerTestHelpers.Instance.AddProviderOptions(
((IRelationalDbContextOptionsBuilderInfrastructure)
new SqlServerDbContextOptionsBuilder(new DbContextOptionsBuilder()).UseNetTopologySuite())
.OptionsBuilder).Options)
{
}
}
}
|
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts
{
record LspAttributes(
SyntaxAttributeData? GenerateTypedDataAttribute,
bool GenerateTypedData,
SyntaxAttributeData? GenerateContainerAttribute,
bool GenerateContainer,
SyntaxAttributeData? CapabilityAttribute,
SyntaxSymbol? Capability,
SyntaxAttributeData? ResolverAttribute,
SyntaxSymbol? Resolver,
SyntaxAttributeData? RegistrationOptionsKeyAttribute,
string? RegistrationOptionsKey,
SyntaxAttributeData? RegistrationOptionsAttribute,
SyntaxSymbol? RegistrationOptions,
bool CanBeResolved,
bool CanHaveData
)
{
public static LspAttributes? Parse(
Compilation compilation,
TypeDeclarationSyntax syntax,
SemanticModel model,
INamedTypeSymbol symbol)
{
var prefix = "OmniSharp.Extensions.LanguageServer.Protocol.Generation";
var attributes = new LspAttributes(null, false, null, false, null, null,null, null, null, null, null, null, false, false);
attributes = attributes with
{
CanBeResolved = syntax.BaseList?.Types.Any(z => z.Type.GetSyntaxName()?.Contains("ICanBeResolved") == true) == true || symbol.AllInterfaces.Any(z => z.ToDisplayString().Contains("ICanBeResolved")),
CanHaveData = syntax.BaseList?.Types.Any(z => z.Type.GetSyntaxName()?.Contains("ICanHaveData") == true) == true || symbol.AllInterfaces.Any(z => z.ToDisplayString().Contains("ICanHaveData")),
};
{
var attributeSymbol = compilation.GetTypeByMetadataName($"{prefix}.GenerateTypedDataAttribute");
if (symbol.GetAttribute(attributeSymbol) is { } data && data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax)
{
attributes = attributes with {
GenerateTypedData = true,
GenerateTypedDataAttribute = new SyntaxAttributeData(attributeSyntax, data)
};
}
}
{
var attributeSymbol = compilation.GetTypeByMetadataName($"{prefix}.GenerateContainerAttribute");
if (symbol.GetAttribute(attributeSymbol) is { } data && data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax)
{
attributes = attributes with {
GenerateContainer = true,
GenerateContainerAttribute = new SyntaxAttributeData(attributeSyntax, data)
};
}
}
{
var attributeSymbol = compilation.GetTypeByMetadataName($"{prefix}.RegistrationOptionsKeyAttribute");
if (symbol.GetAttribute(attributeSymbol) is { ConstructorArguments: { Length: >=1 } arguments } data
&& arguments[0].Kind is TypedConstantKind.Primitive && arguments[0].Value is string value
&& data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax)
{
attributes = attributes with {
RegistrationOptionsKeyAttribute = new SyntaxAttributeData(attributeSyntax, data),
RegistrationOptionsKey = value
};
}
}
{
var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, compilation.GetTypeByMetadataName($"{prefix}.CapabilityAttribute"));
attributes = attributes with {
CapabilityAttribute = syntaxAttributeData,
Capability = syntaxSymbol
};
}
{
var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, compilation.GetTypeByMetadataName($"{prefix}.ResolverAttribute"));
attributes = attributes with {
ResolverAttribute = syntaxAttributeData,
Resolver = syntaxSymbol
};
}
{
var (syntaxAttributeData, syntaxSymbol) = ExtractAttributeTypeData(symbol, compilation.GetTypeByMetadataName($"{prefix}.RegistrationOptionsAttribute"));
attributes = attributes with {
RegistrationOptionsAttribute = syntaxAttributeData,
RegistrationOptions = syntaxSymbol
};
}
return attributes;
static (SyntaxAttributeData? SyntaxAttributeData, SyntaxSymbol? SyntaxSymbol) ExtractAttributeTypeData(INamedTypeSymbol symbol, INamedTypeSymbol? attributeSymbol)
{
if (symbol.GetAttribute(attributeSymbol) is { ConstructorArguments: { Length: >=1 } arguments } data
&& arguments[0].Kind is TypedConstantKind.Type && arguments[0].Value is INamedTypeSymbol value
&& data.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax attributeSyntax
&& attributeSyntax is { ArgumentList: { Arguments: { Count: 1 } syntaxArguments } }
&& syntaxArguments[0].Expression is TypeOfExpressionSyntax typeOfExpressionSyntax)
{
return ( new SyntaxAttributeData(attributeSyntax, data), new SyntaxSymbol(typeOfExpressionSyntax.Type, value) );
}
return (null, null);
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using ServicesLibrary.Interfaces;
using ServicesLibrary.Models;
using TiendeoAPI.Core.Interfaces;
using TiendeoAPI.Helpers;
using TiendeoAPI.Models;
namespace TiendeoAPI.Core.StoreCore
{
public class StoreCore : IStoreCore
{
private readonly ILocalService _localService;
private readonly IBusinessService _businessService;
private readonly ICityService _cityService;
public StoreCore(ILocalService localService, IBusinessService businessService, ICityService cityService)
{
this._localService = localService;
this._businessService = businessService;
this._cityService = cityService;
}
public List<StoreModel> GetStoresOrderByRank()
{
return this.GetStores().OrderBy(x => x.Rank).ToList();
}
private List<StoreModel> GetStores()
{
List<StoreModel> resultStores = new List<StoreModel>();
var storesDtos = this._localService.GetAllStores();
storesDtos.ForEach(store =>
{
var storeModel = Mapper.Map<StoreModel>(store);
var businessDto = this._businessService.GetBusinessById(store.BusinessId);
var cityDto = this._cityService.GetCityById(store.CityId);
storeModel.Business = (businessDto != null) ? Mapper.Map<BusinessModel>(businessDto) : null;
storeModel.City = (cityDto != null) ? Mapper.Map<CityModel>(cityDto) : null;
resultStores.Add(storeModel);
});
return resultStores;
}
public List<StoreModel> GetXStoresFromCityOrderByRank(string name,int number)
{
var city = this._cityService.GetCityByName(name);
if(city != null)
{
return this.GetStores().Where(store => store.City.Name == name).Take(number).OrderBy(x => x.Rank).ToList();
}
else
{
return null;
}
}
public StoreDistanceModel GetNearestStoreFromCoords(Coord userCoord)
{
var storesDtos = this._localService.GetAllStores();
StoreDistanceModel distanceModel = new StoreDistanceModel();
storesDtos.ForEach(store =>
{
var distance = this.GetDistanceToStore(userCoord, store);
if (distanceModel.Store == null || distanceModel.Distance > distance)
{
this.SetStoreDistanceModelFromStoreDto(store, distanceModel);
distanceModel.Distance = distance;
}
});
return distanceModel;
}
public List<StoreDistanceModel> GetXNearestStoresFromCoords(Coord userCoord, int number)
{
var storesDtos = this._localService.GetAllStores();
List<StoreDistanceModel> distanceModels = new List<StoreDistanceModel>();
storesDtos.ForEach(store =>
{
StoreDistanceModel storeDistanceModel = new StoreDistanceModel();
var distance = this.GetDistanceToStore(userCoord, store);
this.SetStoreDistanceModelFromStoreDto(store, storeDistanceModel);
storeDistanceModel.Distance = distance;
distanceModels.Add(storeDistanceModel);
});
return distanceModels.OrderBy(s => s.Distance).Take(number).ToList();
}
private double GetDistanceToStore(Coord userCoord, StoreDto store)
{
Coord storeCoord = new Coord { Lat = store.Lat, Lon = store.Lon };
return DistanceCalculate.CalculateDistanceBetween(userCoord, storeCoord);
}
private void SetStoreDistanceModelFromStoreDto(StoreDto store, StoreDistanceModel distanceModel)
{
var storeModel = Mapper.Map<StoreModel>(store);
var businessDto = this._businessService.GetBusinessById(store.BusinessId);
var cityDto= this._cityService.GetCityById(store.CityId);
storeModel.Business = (businessDto != null) ? Mapper.Map<BusinessModel>(businessDto) : null;
storeModel.City = (cityDto != null) ? Mapper.Map<CityModel>(cityDto) : null;
distanceModel.Store = storeModel;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Darek_kancelaria.Models
{
public class Termcs
{
public int Id { get; set; }
[Required]
[Display(Name = "Nazwa wydarzenia")]
public string Name { get; set; }
[Required]
[Display(Name="Termin wydarzenia")]
public DateTime Term { get; set; }
public virtual CaseModel CaseModel { get; set; }
}
} |
using System;
namespace Lfs.Desktop.Wpf.Services
{
public class ErrorService
{
public static void TreatException(Exception ex)
{
string msg = "";
do
{
msg += $"{ex.Message};\n";
ex = ex?.InnerException;
}
while (ex != null);
var error = new ErrorWindow(msg);
error.Show();
}
}
}
|
using System;
using System.Windows.Forms;
using Relocation.Data;
using Relocation.Base;
using Relocation.Com;
using Relocation.Com.Tools;
using Relocation.Base.UI;
using System.Linq;
namespace Relocation
{
public partial class LoginWindow : BaseForm
{
public User User
{
get;
private set;
}
public LoginWindow()
: base()
{
Initialize();
}
public LoginWindow(Session s)
: base(s)
{
Initialize();
}
private void Initialize()
{
InitializeComponent();
this.username.Tag = new ControlTag(User.GetPropName(t => t.name), new ValidatorInfo(true));
this.password.Tag = new ControlTag(User.GetPropName(t => t.password), new ValidatorInfo(true));
}
/// <summary>
/// 重写父类的事件(防止关闭窗体时提示数据未保存)
/// </summary>
protected override void FieldTextChangeEvent(object sender, EventArgs e)
{
}
//登录
private void submit_Click(object sender, EventArgs e)
{
try
{
if (!this.ValidatorAllControls())
return;
this.User = Session.DataModel.getUserByNameAndPassword(username.Text, password.Text);
if (User == null)
{
this.errLabel.Text = "您输入的用户名/密码错误";
return;
}
this.DialogResult = DialogResult.OK;
this.Close();
} catch (Exception ex)
{
Log.Error(ex);
MyMessagebox.Error("连接数据库失败!");
}
}
//重置
private void reset_Click(object sender, EventArgs e)
{
username.Text = "";
password.Text = "";
errLabel.Text = "";
}
private void username_TextChanged(object sender, EventArgs e)
{
this.password.Text = "";
this.errLabel.Text = "";
}
}
}
|
using System.ComponentModel.DataAnnotations;
using XMLApiProject.Services.Models.PaymentService.Entities;
using XMLApiProject.Services.Models.PaymentService.XML.RequestService.Responses;
namespace XMLApiProject.Services.Models.PaymentService.XML.RequestService.Request
{
public class MultiUseTokenRequestMessage: RequestMessageBase
{
#region Properties
public string MerchantCode { get; set; }
public string MerchantAccountCode { get; set; }
[Required]
[StringLength(16)]
public string PaymentAccountNumber { get; set; }
[StringLength(7)]
public string ExpirationDate { get; set; }
public string MSRKey { get; set; }
public string SecureFormat { get; set; }
public uint? BDKSlot { get; set; }
public string Track1 { get; set; }
public string Track2 { get; set; }
public string Track3 { get; set; }
public string EncryptionId { get; set; }
[StringLength(40)]
public string DeviceMake { get; set; }
[StringLength(40)]
public string DeviceModel { get; set; }
[StringLength(40)]
public string DeviceSerial { get; set; }
[StringLength(50)]
public string DeviceFirmware { get; set; }
[StringLength(10)]
public string RegistrationKey { get; set; }
[StringLength(36)]
public string AppHostMachineId { get; set; }
[StringLength(6)]
public string IntegrationMethod { get; set; }
public string OriginatingTechnologySource { get; set; }
[Required]
public string SoftwareVendor { get; set; }
public string SecurityTechnology { get; set; }
#endregion
#region Constructor
public MultiUseTokenRequestMessage()
{
}
public MultiUseTokenRequestMessage(string paymentAccountNumber, string expirationDate, string mSRKey, string secureFormat, uint bDKSlot, string track1,
string track2, string track3, string encryptionId, string deviceMake, string deviceModel, string deviceSerial,
string deviceFirmware, string registrationKey, string appHostMachineId, string integrationMethod, string originatingTechnologySource,
string softwareVendor, string securityTechnology)
{
PaymentAccountNumber = paymentAccountNumber;
ExpirationDate = expirationDate;
MSRKey = mSRKey;
SecureFormat = secureFormat;
BDKSlot = bDKSlot;
Track1 = track1;
Track2 = track2;
Track3 = track3;
EncryptionId = encryptionId;
DeviceMake = deviceMake;
DeviceModel = deviceModel;
DeviceSerial = deviceSerial;
DeviceFirmware = deviceFirmware;
RegistrationKey = registrationKey;
AppHostMachineId = appHostMachineId;
IntegrationMethod = integrationMethod;
OriginatingTechnologySource = originatingTechnologySource;
SoftwareVendor = softwareVendor;
SecurityTechnology = securityTechnology;
}
public MultiUseTokenRequestMessage(IGetTokenRequest request)
{
{
PaymentAccountNumber = request.PaymentAccountNumber;
ExpirationDate = request.ExpirationDate.ToString("MMyy");
MSRKey = request.MSRKey;
SecureFormat = request.SecureFormat;
BDKSlot = request.BDKSlot;
Track1 = request.Track1;
Track2 = request.Track2;
Track3 = request.Track3;
EncryptionId = request.EncryptionId;
DeviceMake = request.DeviceMake;
DeviceModel = request.DeviceModel;
DeviceSerial = request.DeviceSerial;
DeviceFirmware = request.DeviceFirmware;
RegistrationKey = request.RegistrationKey;
AppHostMachineId = request.AppHostMachineId;
IntegrationMethod = request.IntegrationMethod;
OriginatingTechnologySource = request.OriginatingTechnologySource;
SoftwareVendor = request.SoftwareVendor;
SecurityTechnology = request.SecurityTechnology;
MerchantCode = request.MerchantCode;
MerchantAccountCode = request.MerchantAccountCode;
}
}
#endregion
public override string GetResponseRootName()
{
return nameof(GetToken);
}
public override RawRequestMessageString ToXmlRequestString()
{
return ToXmlRequestString<MultiUseTokenRequestMessage>();
}
public bool ShouldSerializeBDKSlot()
{
return BDKSlot.HasValue;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace DropoutCoder.Core {
public static class TypeHelper {
public static readonly IEnumerable<Type> BuiltInTypes = new[] {
GetType<bool>(),
GetType<byte>(),
GetType<sbyte>(),
GetType<char>(),
GetType<decimal>(),
GetType<double>(),
GetType<float>(),
GetType<int>(),
GetType<uint>(),
GetType<long>(),
GetType<ulong>(),
GetType<object>(),
GetType<short>(),
GetType<string>()
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Type GetType<T>() {
return typeof(T);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TypeInfo GetTypeInfo<T>() {
return GetType<T>().GetTypeInfo();
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using W3ChampionsStatisticService.CommonValueObjects;
using W3ChampionsStatisticService.Ladder;
namespace W3ChampionsStatisticService.Ports
{
public interface IRankRepository
{
Task<List<Rank>> LoadPlayersOfLeague(int leagueId, int season, GateWay gateWay, GameMode gameMode);
Task<List<Rank>> SearchPlayerOfLeague(string searchFor, int season, GateWay gateWay, GameMode gameMode);
Task<List<Rank>> LoadPlayerOfLeague(string searchFor, int season);
Task<List<Rank>> LoadPlayersOfCountry(string countryCode, int season, GateWay gateWay, GameMode gameMode);
Task<List<LeagueConstellation>> LoadLeagueConstellation(int? season = null);
Task InsertRanks(List<Rank> events);
Task InsertLeagues(List<LeagueConstellation> leagueConstellations);
Task UpsertSeason(Season season);
Task<List<Season>> LoadSeasons();
Task<List<Rank>> LoadRanksForPlayers(List<string> list, int season);
Task<List<PlayerInfoForProxy>> SearchAllPlayersForProxy(string tagSearch);
}
} |
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Security;
using System.Windows.Forms;
namespace Luminous
{
public class DatabaseManager
{
#region Private Variables
private string _userName;
private SecureString _passWord;
private string _ip;
private string _dataBase;
#endregion
#region Constructor / Destroy void
public DatabaseManager(string userName, SecureString password, string ip, string dataBase)
{
_userName = userName;
_passWord = password;
_ip = ip;
_dataBase = dataBase;
this.TestConnection();
}
public void Destroy()
{
_userName = null;
_passWord = null;
_ip = null;
_dataBase = null;
}
#endregion
#region Public Variables
public string Username
{
get => _userName;
set => _userName = value;
}
public SecureString Password
{
get => null;
set => _passWord = value;
}
public string IPAddress
{
get => _ip;
set => _ip = value;
}
public string DatabaseName
{
get => _dataBase;
set => _dataBase = value;
}
#endregion
#region Methods
public void TestConnection()
{
MySqlConnection conn = new MySqlConnection("Persist Security Info=False;server=" + _ip + ";database=" + _dataBase + ";userid=" + _userName + ";password=" + SecureStringManager.ToUnsecureString(_passWord) + "");
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT 1+1", conn);
cmd.ExecuteScalar();
}
catch (Exception e)
{
MessageBox.Show(
$"Luminous has encountered an error when connecting to the MySQL Server and as a result, the program has crashed. The exception is as follows:\n {e}", "Luminous");
Environment.Exit(0);
}
finally
{
conn.Close();
}
}
public void ExecuteNonQuery(string Query)
{
MySqlConnection conn = new MySqlConnection("Persist Security Info=False;server=" + _ip + ";database=" + _dataBase + ";userid=" + _userName + ";password=" + SecureStringManager.ToUnsecureString(_passWord) + "");
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteScalar();
}
catch (Exception e)
{
MessageBox.Show(
$"Luminous has encountered an error when executing a non-query to the specified MySQL Server and as a result, the program has crashed. The exception is as follows:\n {e}",
"Luminous");
Environment.Exit(1);
}
finally
{
conn.Close();
}
}
public DataTable ExecuteQuery(string Query)
{
var conn = new MySqlConnection("Persist Security Info=False;server=" + _ip + ";database=" + _dataBase + ";userid=" + _userName + ";password=" + SecureStringManager.ToUnsecureString(_passWord) + "");
var dt = new DataTable();
try
{
conn.Open();
var cmd = new MySqlCommand(Query, conn);
dt.Load(cmd.ExecuteReader());
}
catch (Exception e)
{
MessageBox.Show(
$"Luminous has encountered an error when executing a query to the specified MySQL Server and as a result, the program has crashed. The exception is as follows:\n {e}",
"Luminous");
Environment.Exit(1);
}
finally
{
conn.Close();
}
return dt;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thoughtworks_BattleShip.Interface;
namespace Thoughtworks_Battleship
{
public class Player : IPlayer
{
private IBattleField battleField;
private Queue<IMissile> missiles;
public Player(string name)
{
this.Name = name;
this.missiles = new Queue<IMissile>();
}
public string Name { get; }
public void SetBattleField(int width, int height)
{
this.battleField = new BattleField(width, height);
}
public void AddShipToFleet(IShip ship, string position)
{
this.battleField.AddShip(ship, position);
}
public void AddMissile(IMissile missile)
{
this.missiles.Enqueue(missile);
}
public IMissile GetMissile()
{
if (this.missiles.Count > 0)
return this.missiles.Dequeue();
else
return null;
}
public bool MissileReceived(IMissile missile)
{
return this.battleField.MissileReceived(missile);
}
public bool HasAmmuntion()
{
return this.missiles.Count > 0 ? true : false;
}
public bool HasStrength()
{
return this.battleField.TotalStrength > 0 ? true : false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace QuestionPaperGenerator.Models
{
[Table("WorksheetDetails")]
public class QuestionPattern
{
public int Id { get; set; }
[Required]
public int Frequency { get; set; }
[Required]
public int Marks { get; set; }
[ForeignKey("Template")]
public virtual int Template_Id { get; set; }
public virtual Template Template { get; set; }
[ForeignKey("Worksheet")]
public virtual int Worksheet_Id { get; set; }
public virtual Worksheet Worksheet { get; set; }
}
} |
using PaymentUI.ViewModels;
using Xamarin.Forms;
namespace PaymentUI.Views
{
public partial class CreditCardPage : ContentPage
{
public CreditCardPage()
{
InitializeComponent();
this.BindingContext = new CreditCardPageViewModel();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Business.DTO;
using Business.Rules;
using Database.Repositories;
namespace Business.Services
{
public class RouteService
{
private IRouteRepository _routeRepository;
public RouteService(string path)
{
_routeRepository = new RouteRepository(path);
}
public RouteService(IRouteRepository routeRepository)
{
_routeRepository = routeRepository;
}
public List<RouteDTO> GetAll()
{
var routes = _routeRepository.GetAll();
var routesDTO = routes.Select(RouteDTO.Convert).ToList();
return routesDTO;
}
public string GetShortest(string origin, string destin)
{
var routes = _routeRepository.GetAll();
var routesDTO = routes.Select(RouteDTO.Convert).ToList();
var result = ShortestRoute.GetRoute(origin, destin, routesDTO);
return result;
}
}
}
|
using System;
using Caliburn.Micro;
namespace Frontend.Core.Common
{
public abstract class ViewModelBase : PropertyChangedBase, IDisposable
{
private bool isDisposed;
protected ViewModelBase(IEventAggregator eventAggregator)
{
EventAggregator = eventAggregator;
//HACK: This needs rethinking, but when vms gets resolved from a view (Say, a contentcontrol binding to a vm),
//the Load method obviously won't get called.
//this.Load(null);
}
protected IEventAggregator EventAggregator { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Load(object parameter)
{
OnLoading(parameter);
OnLoad(parameter);
OnLoaded(parameter);
}
public void Unload()
{
OnUnloading();
OnUnload();
OnUnloaded();
}
protected virtual void Dispose(bool isDisposing)
{
if (isDisposing && !isDisposed)
{
Unload();
isDisposed = true;
}
}
protected virtual void OnLoading(object parameter)
{
}
protected virtual void OnLoad(object parameter)
{
}
protected virtual void OnLoaded(object parameter)
{
}
protected virtual void OnUnloading()
{
}
protected virtual void OnUnload()
{
}
protected virtual void OnUnloaded()
{
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using PBingenering.SQL;
using PBingenering.Model;
namespace PBingenering
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosed += Form1_FormClosed;
textBox1.KeyDown += Form1_KeyDown;
textBox2.KeyDown += Form1_KeyDown;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(null, null);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
SqlManager.CloseConnection();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Close();
SqlManager.CloseConnection();
}
private void button1_Click(object sender, EventArgs e)
{
User user = SqlManager.CheckLogin(textBox1.Text.Trim(), textBox2.Text.Trim());
if(user != null)
{
Form2 fm = new Form2(user);
Hide();
if (fm.ShowDialog() == DialogResult.Cancel)//окно формы 2 было закрыто на крестик вверхнем правом углу
{
Close();
fm.Hide();
}
}
else
{
MessageBox.Show("Логин или пароль не верны");
}
#region Старое говно
/*
//string commandString = "Select login,password,Roles.ROL from Personal inner join roles on personal.rol = roles.id where login= '" + textBox1.Text.Trim() + "' and password= '" + textBox2.Text.Trim() + "'";
string commandString = $"Select login,password,Roles.ROL from Personal inner join roles on personal.rol = roles.id where login= '{textBox1.Text.Trim()}' and password= '{textBox2.Text.Trim()}'";
SqlDataAdapter sda = new SqlDataAdapter(commandString, connection);
DataTable dtb1 = new DataTable();
DataGridView dgv1 = new DataGridView();
dgv1.DataSource = sda;
sda.Fill(dtb1);
if (dtb1.Rows.Count == 1)
{
Form2 fm = new Form2(dtb1.Rows[0][0].ToString(), dtb1.Rows[0][2].ToString());
Hide();
if(fm.ShowDialog() == DialogResult.Cancel)//окно формы 2 было закрыто на крестик вверхнем правом углу
{
Close();
}
}
else
{
MessageBox.Show("Что то пошло не так");
}*/
#endregion
}
}
}
|
namespace PDB.Models;
public class Direction
{
public int DeltaX { get; }
public int DeltaY { get; }
private Direction(int deltaX, int deltaY)
{
DeltaX = deltaX;
DeltaY = deltaY;
}
public static readonly Direction NorthWest = new Direction(-1, 1);
public static readonly Direction North = new Direction(0, 1);
public static readonly Direction NorthEast = new Direction(1, 1);
public static readonly Direction East = new Direction(1, 0);
public static readonly Direction SouthEast = new Direction(1, -1);
public static readonly Direction South = new Direction(0, -1);
public static readonly Direction SouthWest = new Direction(-1, -1);
public static readonly Direction West = new Direction(-1, 0);
public static readonly IList<Direction> AllDirections = new List<Direction>()
{
NorthWest, North, NorthEast, East, South, SouthEast, SouthWest, West
};
} |
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class SurfaceCreator : MonoBehaviour {
[Range(1, 200)] public int resolution = 10;
[Range(256, 1024)] public int textureResolution = 512;
[Range(1, 20)] public int frequency = 1;
[Range(0f, 1f)] public float strength = 1f;
[Range(1, 8)] public int octaves = 1;
[Range(1f, 4f)] public float lacunarity = 2f;
[Range(0f, 1f)] public float persistence = 0.5f;
[Range(1, 3)] public int dimensions = 3;
public NoiseMethodType type;
public Gradient coloring;
public Vector3 offset;
public Vector3 rotation;
public bool coloringForStrength;
public bool damping;
[Range(0.15f, 1f)] public float dampingIntensity = 0.5f;
public bool showNormals;
private Vector3[] vertices;
private Vector3[] normals;
private Mesh mesh;
private Texture2D texture;
private void OnEnable () {
if (mesh == null) {
mesh = new Mesh();
mesh.name = "Surface Mesh";
GetComponent<MeshFilter>().mesh = mesh;
}
Refresh();
}
public void Refresh () {
CreateGrid();
CreateTexture();
Quaternion q = Quaternion.Euler(rotation);
Quaternion qInv = Quaternion.Inverse(q);
Vector3 point00 = q * new Vector3(-0.5f,-0.5f) + offset;
Vector3 point10 = q * new Vector3( 0.5f,-0.5f) + offset;
Vector3 point01 = q * new Vector3(-0.5f, 0.5f) + offset;
Vector3 point11 = q * new Vector3( 0.5f, 0.5f) + offset;
NoiseMethod method = Noise.noiseMethods[(int)type][dimensions - 1];
float stepSize = 1f / resolution;
float amplitude = damping ? (strength / frequency) * (1f / dampingIntensity) : strength;
for (int v = 0, y = 0; y <= resolution; y++) {
Vector3 point0 = Vector3.Lerp(point00, point01, y * stepSize);
Vector3 point1 = Vector3.Lerp(point10, point11, y * stepSize);
for (int x = 0; x <= resolution; x++, v++) {
Vector3 point = Vector3.Lerp(point0, point1, x * stepSize);
NoiseSample sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence);
sample *= 0.5f;
sample *= amplitude;
vertices[v].y = sample.value;
}
}
mesh.vertices = vertices;
mesh.RecalculateNormals();
float textureStepSize = 1f / textureResolution;
for (int v = 0, y = 0; y <= textureResolution; y++) {
Vector3 point0 = Vector3.Lerp(point00, point01, y * textureStepSize);
Vector3 point1 = Vector3.Lerp(point10, point11, y * textureStepSize);
for (int x = 0; x <= textureResolution; x++, v++) {
Vector3 point = Vector3.Lerp(point0, point1, x * textureStepSize);
NoiseSample sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence);
sample = type == NoiseMethodType.Value ? (sample - 0.5f) : (sample * 0.5f);
if (coloringForStrength)
texture.SetPixel(x, y, coloring.Evaluate(sample.value + 0.5f));
else
texture.SetPixel(x, y, coloring.Evaluate((sample.value * amplitude) + 0.5f));
}
}
texture.Apply();
}
private void CreateGrid() {
vertices = new Vector3[(resolution + 1) * (resolution + 1)];
Vector2[] uv = new Vector2[vertices.Length];
int[] triangles = new int[resolution * resolution * 6];
float stepSize = 1f / resolution;
for (int v = 0, z = 0; z <= resolution; z++)
for (int x = 0; x <= resolution; x++, v++) {
vertices[v] = new Vector3(x * stepSize - 0.5f, 0f, z * stepSize - 0.5f);
uv[v] = new Vector2(x * stepSize, z * stepSize);
}
for (int t = 0, v = 0, y = 0; y < resolution; y++, v++)
for (int x = 0; x < resolution; x++, v++, t += 6) {
triangles[t] = v;
triangles[t + 1] = v + resolution + 1;
triangles[t + 2] = v + 1;
triangles[t + 3] = v + 1;
triangles[t + 4] = v + resolution + 1;
triangles[t + 5] = v + resolution + 2;
}
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
}
private void CreateTexture() {
texture = new Texture2D(textureResolution, textureResolution, TextureFormat.RGB24, true);
texture.name = "Procedural Texture";
texture.wrapMode = TextureWrapMode.Clamp;
texture.filterMode = FilterMode.Trilinear;
texture.anisoLevel = 9;
Material material = GetComponent<MeshRenderer>().sharedMaterial;
/* This is the property name for the base texture in the HDRP/Lit shader */
material.SetTexture("_BaseColorMap", texture);
GetComponent<MeshRenderer>().sharedMaterial = material;
}
private float GetXDerivative (int x, int z) {
int rowOffset = z * (resolution + 1);
float left, right, scale;
if (x > 0) {
left = vertices[rowOffset + x - 1].y;
if (x < resolution) {
right = vertices[rowOffset + x + 1].y;
scale = 0.5f * resolution;
} else {
right = vertices[rowOffset + x].y;
scale = resolution;
}
}
else {
left = vertices[rowOffset + x].y;
right = vertices[rowOffset + x + 1].y;
scale = resolution;
}
return (right - left) * scale;
}
private float GetZDerivative (int x, int z) {
int rowLength = resolution + 1;
float back, forward, scale;
if (z > 0) {
back = vertices[(z - 1) * rowLength + x].y;
if (z < resolution) {
forward = vertices[(z + 1) * rowLength + x].y;
scale = 0.5f * resolution;
} else {
forward = vertices[z * rowLength + x].y;
scale = resolution;
}
} else {
back = vertices[z * rowLength + x].y;
forward = vertices[(z + 1) * rowLength + x].y;
scale = resolution;
}
return (forward - back) * scale;
}
} |
using System;
using System.Collections.Generic;
using Paralect.Schematra.Exceptions;
namespace Paralect.Schematra
{
public abstract class Type
{
/// <summary>
/// Type context this type belongs to
/// </summary>
protected readonly TypeContext _typeContext;
/// <summary>
/// Short name of type (without namespace prefix)
/// </summary>
protected String _name;
/// <summary>
/// Namespace of this type
/// </summary>
protected String _namespace;
/// <summary>
/// Full name of type with namespace
/// </summary>
protected String _fullName;
/// <summary>
/// List of aliasses
/// </summary>
protected List<String> _aliases = new List<String>();
/// <summary>
/// List of aliasses
/// </summary>
protected List<String> _usings = new List<String>();
/// <summary>
/// Short name of type (without namespace prefix)
/// </summary>
public String Name
{
get { return _name; }
}
/// <summary>
/// Namespace of this type
/// </summary>
public string Namespace
{
get { return _namespace; }
}
/// <summary>
/// Full name of type with namespace
/// </summary>
public String FullName
{
get { return _fullName; }
}
/// <summary>
/// List of aliasses
/// </summary>
public ICollection<string> Aliases
{
get { return _aliases.AsReadOnly(); }
}
/// <summary>
/// Type context this type belongs to
/// </summary>
public TypeContext TypeContext
{
get { return _typeContext; }
}
/// <summary>
/// Initialization
/// </summary>
protected Type(TypeContext typeContext)
{
_typeContext = typeContext;
}
public abstract void Build();
/// <summary>
/// Define name by name and @namespace
/// </summary>
protected void SetNameInternal(String name, String @namespace)
{
_name = name;
_namespace = @namespace;
_fullName = Utils.ConcatNamespaces(@namespace, name);
}
/// <summary>
/// Define name by full name
/// </summary>
protected void SetNameInternal(String fullName)
{
_fullName = fullName;
// Extract name
var index = _fullName.LastIndexOf('.');
_name = index != -1 ? fullName.Substring(index + 1) : _fullName;
_namespace = index != -1 ? fullName.Substring(0, index) : String.Empty;
}
/// <summary>
/// Add alias
/// </summary>
protected void AddAliasInternal(String alias)
{
if (_aliases.Contains(alias))
throw new DuplicateTypeAliasException("Alias {0} already defined for type {1}", alias, _fullName);
_aliases.Add(alias);
}
/// <summary>
/// Add usings internal
/// </summary>
protected void SetUsingsInternal(List<String> usings)
{
_usings = usings;
}
/// <summary>
/// Copy this type infor to another type instance
/// </summary>
/// <param name="to"></param>
protected void CopyInternal(Type to)
{
to._name = _name;
to._fullName = _fullName;
to._namespace = _namespace;
foreach (var aliase in _aliases)
{
to.AddAliasInternal(aliase);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NewsPortal.Models;
using NewsPortalLogic;
namespace NewsPortal.Controllers
{
public class HomeController : Controller
{
private NewsManager _news;
public HomeController(NewsManager newsManager)
{
_news = newsManager;
}
public IActionResult Index(int? id)
{
var view = _news.GetAll();
return View(view);
}
public IActionResult About()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ControlValveMaintenance.Models.Lookups;
namespace ControlValveMaintenance.Models
{
public class SiteMaintenance : INotifyPropertyChanged
{
#region Variables
// CLASS VARIABLES
private int siteMaintID;
private int siteID;
private int maintType;
private int airVacChkStatus;
private int relChkStatus;
private int pressureGuageChkStatus;
private int transChkStatus;
private int alarmsChkStatus;
private int vaultClnStatus;
private int lightHeatChkStatus;
private int sumpChkStatus;
private int ladderStatus;
private int accessHatchStatus;
private DateTime scheduledDate;
private DateTime? completedDate;
private string completedBy;
private int elev;
private string baseMapName;
private string addy;
private string comments;
private string approvedBy;
private DateTime? approvalDate;
private string reviewedBy;
private DateTime? reviewedDate;
private int siteNo;
#endregion
#region Properties
// CLASS PROPERTIES
public int SiteMaintID
{
get
{
return siteMaintID;
}
set
{
SetField(ref siteMaintID, value, "SiteMaintID");
}
}
public int SiteID
{
get
{
return siteID;
}
set
{
SetField(ref siteID, value, "SiteID");
}
}
public string MaintType
{
get
{
return MaintTypeID.Instance.getType(maintType);
}
set
{
SetField(ref maintType, Convert.ToInt16(value), "MaintType");
}
}
public string AirVacChkStatus
{
get
{
return StatusCodes.Instance.getStatus(airVacChkStatus);
}
set
{
SetField(ref airVacChkStatus, Convert.ToInt16(value), "AirVacChkStatus");
}
}
public string RelChkStatus
{
get
{
return StatusCodes.Instance.getStatus(relChkStatus);
}
set
{
SetField(ref relChkStatus, Convert.ToInt16(value), "RelChkStatus");
}
}
public string PressureGuageChkStatus
{
get
{
return StatusCodes.Instance.getStatus(pressureGuageChkStatus);
}
set
{
SetField(ref pressureGuageChkStatus, Convert.ToInt16(value), "PressureGuageChkStatus");
}
}
public string TransChkStatus
{
get
{
return StatusCodes.Instance.getStatus(transChkStatus);
}
set
{
SetField(ref transChkStatus, Convert.ToInt16(value), "TransChkStatus");
}
}
public string AlarmsChkStatus
{
get
{
return StatusCodes.Instance.getStatus(alarmsChkStatus);
}
set
{
SetField(ref alarmsChkStatus, Convert.ToInt16(value), "AlarmsChkStatus");
}
}
public string VaultClnStatus
{
get
{
return StatusCodes.Instance.getStatus(vaultClnStatus);
}
set
{
SetField(ref vaultClnStatus, Convert.ToInt16(value), "VaultClnStatus");
}
}
public string LightHeatChkStatus
{
get
{
return StatusCodes.Instance.getStatus(lightHeatChkStatus);
}
set
{
SetField(ref lightHeatChkStatus, Convert.ToInt16(value), "LightHeatChkStatus");
}
}
public string SumpChkStatus
{
get
{
return StatusCodes.Instance.getStatus(sumpChkStatus);
}
set
{
SetField(ref sumpChkStatus, Convert.ToInt16(value), "SumpChkStatus");
}
}
public string AccessHatchStatus
{
get
{
return StatusCodes.Instance.getStatus(accessHatchStatus);
}
set
{
SetField(ref accessHatchStatus, Convert.ToInt16(value), "AccessHatchStatus");
}
}
public string LadderStatus
{
get
{
return StatusCodes.Instance.getStatus(ladderStatus);
}
set
{
SetField(ref ladderStatus, Convert.ToInt16(value), "LadderStatus");
}
}
public DateTime ScheduledDate
{
get
{
return scheduledDate;
}
set
{
SetField(ref scheduledDate, value, "ScheduledDate");
}
}
public DateTime? CompletedDate
{
get
{
if (completedDate == DateTime.MinValue) return null;
return completedDate;
}
set
{
SetField(ref completedDate, value, "CompletedDate");
}
}
public string CompletedBy
{
get
{
return completedBy;
}
set
{
SetField(ref completedBy, value, "CompletedBy");
}
}
public int Elevation
{
get
{
return elev;
}
set
{
SetField(ref elev, value, "Elevation");
}
}
public string BaseMap
{
get
{
return baseMapName;
}
set
{
SetField(ref baseMapName, value, "BaseMap");
}
}
public string Address
{
get
{
return addy;
}
set
{
SetField(ref addy, value, "Address");
}
}
public string FieldComments
{
get
{
return comments;
}
set
{
SetField(ref comments, value, "FieldComments");
}
}
public string ApprovedBy
{
get
{
return approvedBy;
}
set
{
SetField(ref approvedBy, value, "ApprovedBy");
}
}
public DateTime? ApprovalDate
{
get
{
if (approvalDate == DateTime.MinValue) return null;
return approvalDate;
}
set
{
SetField(ref approvalDate, value, "ApprovalDate");
}
}
public string ReviewedBy
{
get
{
return reviewedBy;
}
set
{
SetField(ref reviewedBy, value, "ReviewedBy");
}
}
public DateTime? ReviewedDate
{
get
{
if (reviewedDate == DateTime.MinValue) return null;
return reviewedDate;
}
set
{
SetField(ref reviewedDate, value, "ReviewedDate");
}
}
public int SiteNo
{
get
{
return siteNo;
}
set
{
SetField(ref siteNo, value, "SiteNo");
}
}
#endregion
/// <summary>
/// DEFAULT CONSTRUCTOR
/// </summary>
public SiteMaintenance()
{
}
private bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
#region Property Changed
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
|
using PrincessApollo.Controls;
using UnityEngine;
using UnityEngine.UI;
using static System.Convert;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] Vector3 velocity;
[Space(20)]
[SerializeField] float movementSpeedMultiplier = 10;
float dashRange = 1f, dashSwitch = 1, dashVelocity;
public float savedDir = 1, jumpForce = 200;
Rigidbody2D rb;
BoxCollider2D v_coll;
Animator a_anim;
private enum State
{
Normal,
Dashing,
Crouching,
}
public enum KeySets // Ändra inte namnen, dessa är samma namn som används i kontrollfilen // F
{
PlayerOne,
PlayerTwo,
}
[SerializeField]
private KeySets controlSet;
[SerializeField]
private State activeState;
//TEMP??
public Text tt;
public Slider sl;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
v_coll = GetComponent<BoxCollider2D>();
a_anim = GetComponent<Animator>();
}
public void resetVelocity()
{
velocity = Vector3.zero;
}
void Update()
{
#region ???
if (velocity.x != 0)
{
savedDir = velocity.x / Mathf.Abs(velocity.x);
}
if(savedDir <= 0)
{
GetComponent<SpriteRenderer>().flipX = true;
}
else
{
GetComponent<SpriteRenderer>().flipX = false;
}
if(velocity.x == 0)
{
if(activeState != State.Crouching)
{
tt.text = " STATE = IDLE";
}
if (activeState == State.Normal)
{
a_anim.SetTrigger("Idle");
}
}
#endregion
rb.velocity = new Vector2(velocity.x + dashVelocity * savedDir, rb.velocity.y);
switch (activeState)
{
case State.Normal:
//TEMP??
sl.value += Time.deltaTime;
//
if (velocity.x != 0)
{
tt.text = " STATE = NORMAL";
a_anim.SetTrigger("Walking");
}
velocity.x = (ToInt32(Input.GetKey(Controls.Scheme.GetCodeFromKey($"{controlSet}-Right"))) - ToInt32(Input.GetKey(Controls.Scheme.GetCodeFromKey($"{controlSet}-Left")))) * movementSpeedMultiplier;
dashVelocity = 0;
if (Input.GetKey(Controls.Scheme.GetCodeFromKey($"{controlSet}-Forward")) || Input.GetKeyDown(KeyCode.Space) && rb.velocity.y >= 0)
{
rb.AddForce(jumpForce * transform.up);
}
#region transitions
if (Input.GetKeyDown(Controls.Scheme.GetCodeFromKey($"{controlSet}-Dash")) && sl.value > 1)
{
dashSwitch = dashRange;
a_anim.SetBool("isDashing", true);
activeState = State.Dashing;
sl.value--;
}
if (Input.GetKeyDown(Controls.Scheme.GetCodeFromKey($"{controlSet}-Back")) && rb.velocity.y == 0 && rb.velocity.y >= 0)
{
//activeState = State.Crouching;
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
activeState = State.Crouching;
}
break;
case State.Dashing:
tt.text = "STATE = DASHING";
newDashTImer -= Time.deltaTime;
if(newDashTImer <= 0)
{
dashVelocity = 60;
dashSwitch -= Time.deltaTime * 3.5f;
}
else
{
resetVelocity();
dashVelocity = 0;
}
if(dashSwitch <= 0)
{
newDashTImer = .7f;
dashSwitch = 1;
a_anim.SetBool("isDashing", false);
activeState = State.Normal;
}
break;
case State.Crouching:
tt.text = "STATE = CROUCING";
a_anim.SetBool("Crouching", true);
resetVelocity();
if (Input.GetKeyUp(KeyCode.LeftControl))
{
activeState = State.Normal;
a_anim.SetBool("Crouching", false);
}
break;
#endregion
}
}
float newDashTImer = .7f;
} |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Univariate
{
using System;
using Accord.Math;
using Accord.Statistics.Distributions;
using Accord.Statistics.Distributions.Fitting;
using Accord.Statistics.Distributions.Multivariate;
using AForge;
/// <summary>
/// Normal (Gaussian) distribution.
/// </summary>
///
/// <remarks>
/// <para>
/// In probability theory, the normal (or Gaussian) distribution is a very
/// commonly occurring continuous probability distribution—a function that
/// tells the probability that any real observation will fall between any two
/// real limits or real numbers, as the curve approaches zero on either side.
/// Normal distributions are extremely important in statistics and are often
/// used in the natural and social sciences for real-valued random variables
/// whose distributions are not known.</para>
/// <para>
/// The normal distribution is immensely useful because of the central limit
/// theorem, which states that, under mild conditions, the mean of many random
/// variables independently drawn from the same distribution is distributed
/// approximately normally, irrespective of the form of the original distribution:
/// physical quantities that are expected to be the sum of many independent processes
/// (such as measurement errors) often have a distribution very close to the normal.
/// Moreover, many results and methods (such as propagation of uncertainty and least
/// squares parameter fitting) can be derived analytically in explicit form when the
/// relevant variables are normally distributed.</para>
/// <para>
/// The Gaussian distribution is sometimes informally called the bell curve. However,
/// many other distributions are bell-shaped (such as Cauchy's, Student's, and logistic).
/// The terms Gaussian function and Gaussian bell curve are also ambiguous because they
/// sometimes refer to multiples of the normal distribution that cannot be directly
/// interpreted in terms of probabilities.</para>
///
/// <para>
/// The Gaussian is the most widely used distribution for continuous
/// variables. In the case of a single variable, it is governed by
/// two parameters, the mean and the variance.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="https://en.wikipedia.org/wiki/Normal_distribution">
/// Wikipedia, The Free Encyclopedia. Normal distribution. Available on:
/// https://en.wikipedia.org/wiki/Normal_distribution </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <para>
/// This examples shows how to create a Normal distribution,
/// compute some of its properties and generate a number of
/// random samples from it.</para>
///
/// <code>
/// // Create a normal distribution with mean 2 and sigma 3
/// var normal = new NormalDistribution(mean: 2, stdDev: 3);
///
/// // In a normal distribution, the median and
/// // the mode coincide with the mean, so
///
/// double mean = normal.Mean; // 2
/// double mode = normal.Mode; // 2
/// double median = normal.Median; // 2
///
/// // The variance is the square of the standard deviation
/// double variance = normal.Variance; // 3² = 9
///
/// // Let's check what is the cumulative probability of
/// // a value less than 3 occurring in this distribution:
/// double cdf = normal.DistributionFunction(3); // 0.63055
///
/// // Finally, let's generate 1000 samples from this distribution
/// // and check if they have the specified mean and standard devs
///
/// double[] samples = normal.Generate(1000);
///
/// double sampleMean = samples.Mean(); // 1.92
/// double sampleDev = samples.StandardDeviation(); // 3.00
/// </code>
///
/// <para>
/// This example further demonstrates how to compute
/// derived measures from a Normal distribution: </para>
///
/// <code>
/// var normal = new NormalDistribution(mean: 4, stdDev: 4.2);
///
/// double mean = normal.Mean; // 4.0
/// double median = normal.Median; // 4.0
/// double mode = normal.Mode; // 4.0
/// double var = normal.Variance; // 17.64
///
/// double cdf = normal.DistributionFunction(x: 1.4); // 0.26794249453351904
/// double pdf = normal.ProbabilityDensityFunction(x: 1.4); // 0.078423391448155175
/// double lpdf = normal.LogProbabilityDensityFunction(x: 1.4); // -2.5456330358182586
///
/// double ccdf = normal.ComplementaryDistributionFunction(x: 1.4); // 0.732057505466481
/// double icdf = normal.InverseDistributionFunction(p: cdf); // 1.4
///
/// double hf = normal.HazardFunction(x: 1.4); // 0.10712736480747137
/// double chf = normal.CumulativeHazardFunction(x: 1.4); // 0.31189620872601354
///
/// string str = normal.ToString(CultureInfo.InvariantCulture); // N(x; μ = 4, σ² = 17.64)
/// </code>
/// </example>
///
/// <seealso cref="Accord.Statistics.Distributions.Univariate.SkewNormalDistribution"/>
/// <seealso cref="Accord.Statistics.Distributions.Multivariate.MultivariateNormalDistribution"/>
///
/// <seealso cref="Accord.Statistics.Testing.ZTest"/>
/// <seealso cref="Accord.Statistics.Testing.TTest"/>
///
[Serializable]
public class NormalDistribution : UnivariateContinuousDistribution,
IFittableDistribution<double, NormalOptions>,
ISampleableDistribution<double>, IFormattable
{
// Distribution parameters
private double mean = 0; // mean μ
private double stdDev = 1; // standard deviation σ
// Distribution measures
private double? entropy;
// Derived measures
private double variance = 1; // σ²
private double lnconstant; // log(1/sqrt(2*pi*variance))
private bool immutable;
// 97.5 percentile of standard normal distribution
private const double p95 = 1.95996398454005423552;
/// <summary>
/// Constructs a Normal (Gaussian) distribution
/// with zero mean and unit standard deviation.
/// </summary>
///
public NormalDistribution()
{
initialize(mean, stdDev, stdDev * stdDev);
}
/// <summary>
/// Constructs a Normal (Gaussian) distribution
/// with given mean and unit standard deviation.
/// </summary>
///
/// <param name="mean">The distribution's mean value μ (mu).</param>
///
public NormalDistribution([Real] double mean)
{
initialize(mean, stdDev, stdDev * stdDev);
}
/// <summary>
/// Constructs a Normal (Gaussian) distribution
/// with given mean and standard deviation.
/// </summary>
///
/// <param name="mean">The distribution's mean value μ (mu).</param>
/// <param name="stdDev">The distribution's standard deviation σ (sigma).</param>
///
public NormalDistribution([Real] double mean, [Positive] double stdDev)
{
if (stdDev <= 0)
{
throw new ArgumentOutOfRangeException("stdDev",
"Standard deviation must be positive.");
}
initialize(mean, stdDev, stdDev * stdDev);
}
/// <summary>
/// Gets the Mean value μ (mu) for this Normal distribution.
/// </summary>
///
public override double Mean
{
get { return mean; }
}
/// <summary>
/// Gets the median for this distribution.
/// </summary>
///
/// <remarks>
/// The normal distribution's median value
/// equals its <see cref="Mean"/> value μ.
/// </remarks>
///
/// <value>
/// The distribution's median value.
/// </value>
///
public override double Median
{
get
{
System.Diagnostics.Debug.Assert(mean.IsRelativelyEqual(base.Median, 1e-10));
return mean;
}
}
/// <summary>
/// Gets the Variance σ² (sigma-squared), which is the square
/// of the standard deviation σ for this Normal distribution.
/// </summary>
///
public override double Variance
{
get { return variance; }
}
/// <summary>
/// Gets the Standard Deviation σ (sigma), which is the
/// square root of the variance for this Normal distribution.
/// </summary>
///
public override double StandardDeviation
{
get { return stdDev; }
}
/// <summary>
/// Gets the mode for this distribution.
/// </summary>
///
/// <remarks>
/// The normal distribution's mode value
/// equals its <see cref="Mean"/> value μ.
/// </remarks>
///
/// <value>
/// The distribution's mode value.
/// </value>
///
public override double Mode
{
get { return mean; }
}
/// <summary>
/// Gets the skewness for this distribution. In
/// the Normal distribution, this is always 0.
/// </summary>
///
public double Skewness
{
get { return 0; }
}
/// <summary>
/// Gets the excess kurtosis for this distribution.
/// In the Normal distribution, this is always 0.
/// </summary>
///
public double Kurtosis
{
get { return 0; }
}
/// <summary>
/// Gets the support interval for this distribution.
/// </summary>
///
/// <value>
/// A <see cref="DoubleRange" /> containing
/// the support interval for this distribution.
/// </value>
///
public override DoubleRange Support
{
get { return new DoubleRange(Double.NegativeInfinity, Double.PositiveInfinity); }
}
/// <summary>
/// Gets the Entropy for this Normal distribution.
/// </summary>
///
public override double Entropy
{
get
{
if (!entropy.HasValue)
entropy = 0.5 * (Math.Log(2.0 * Math.PI * variance) + 1);
return entropy.Value;
}
}
/// <summary>
/// Gets the cumulative distribution function (cdf) for
/// the this Normal distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">
/// A single point in the distribution range.</param>
///
/// <remarks>
/// <para>
/// The Cumulative Distribution Function (CDF) describes the cumulative
/// probability that a given value or any value smaller than it will occur.</para>
/// <para>
/// The calculation is computed through the relationship to the error function
/// as <see cref="Accord.Math.Special.Erfc">erfc</see>(-z/sqrt(2)) / 2.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description>
/// Weisstein, Eric W. "Normal Distribution." From MathWorld--A Wolfram Web Resource.
/// Available on: http://mathworld.wolfram.com/NormalDistribution.html </description></item>
/// <item><description><a href="http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function">
/// Wikipedia, The Free Encyclopedia. Normal distribution. Available on:
/// http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// See <see cref="NormalDistribution"/>.
/// </example>
///
public override double DistributionFunction(double x)
{
return Normal.Function((x - mean) / stdDev);
}
/// <summary>
/// Gets the complementary cumulative distribution function
/// (ccdf) for this distribution evaluated at point <c>x</c>.
/// This function is also known as the Survival function.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
public override double ComplementaryDistributionFunction(double x)
{
return Normal.Complemented((x - mean) / stdDev);
}
/// <summary>
/// Gets the inverse of the cumulative distribution function (icdf) for
/// this distribution evaluated at probability <c>p</c>. This function
/// is also known as the Quantile function.
/// </summary>
///
/// <remarks>
/// <para>
/// The Inverse Cumulative Distribution Function (ICDF) specifies, for
/// a given probability, the value which the random variable will be at,
/// or below, with that probability.</para>
/// <para>
/// The Normal distribution's ICDF is defined in terms of the
/// <see cref="Normal.Inverse">standard normal inverse cumulative
/// distribution function I</see> as <c>ICDF(p) = μ + σ * I(p)</c>.
/// </para>
/// </remarks>
///
/// <example>
/// See <see cref="NormalDistribution"/>.
/// </example>
///
public override double InverseDistributionFunction(double p)
{
double inv = Normal.Inverse(p);
double icdf = mean + stdDev * inv;
#if DEBUG
double baseValue = base.InverseDistributionFunction(p);
double r1 = DistributionFunction(baseValue);
double r2 = DistributionFunction(icdf);
bool close = r1.IsRelativelyEqual(r2, 1e-6);
if (!close)
{
throw new Exception();
}
#endif
return icdf;
}
/// <summary>
/// Gets the probability density function (pdf) for
/// the Normal distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range. For a
/// univariate distribution, this should be a single
/// double value. For a multivariate distribution,
/// this should be a double array.</param>
///
/// <returns>
/// The probability of <c>x</c> occurring
/// in the current distribution.
/// </returns>
///
/// <remarks>
/// <para>
/// The Probability Density Function (PDF) describes the
/// probability that a given value <c>x</c> will occur.</para>
/// <para>
/// The Normal distribution's PDF is defined as
/// <c>PDF(x) = c * exp((x - μ / σ)²/2)</c>.</para>
/// </remarks>
///
/// <example>
/// See <see cref="NormalDistribution"/>.
/// </example>
///
public override double ProbabilityDensityFunction(double x)
{
double z = (x - mean) / stdDev;
double lnp = lnconstant - z * z * 0.5;
return Math.Exp(lnp);
}
/// <summary>
/// Gets the probability density function (pdf) for
/// the Normal distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range. For a
/// univariate distribution, this should be a single
/// double value. For a multivariate distribution,
/// this should be a double array.</param>
///
/// <returns>
/// The probability of <c>x</c> occurring
/// in the current distribution.
/// </returns>
///
/// <remarks>
/// The Probability Density Function (PDF) describes the
/// probability that a given value <c>x</c> will occur.
/// </remarks>
///
/// <example>
/// See <see cref="NormalDistribution"/>.
/// </example>
///
public override double LogProbabilityDensityFunction(double x)
{
double z = (x - mean) / stdDev;
double lnp = lnconstant - z * z * 0.5;
return lnp;
}
/// <summary>
/// Gets the Z-Score for a given value.
/// </summary>
///
public double ZScore(double x)
{
return (x - mean) / stdDev;
}
/// <summary>
/// Gets the Standard Gaussian Distribution, with zero mean and unit variance.
/// </summary>
///
public static NormalDistribution Standard { get { return standard; } }
private static readonly NormalDistribution standard = new NormalDistribution() { immutable = true };
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting, such
/// as regularization constants and additional parameters.</param>
///
public override void Fit(double[] observations, double[] weights, IFittingOptions options)
{
NormalOptions normalOptions = options as NormalOptions;
if (options != null && normalOptions == null)
throw new ArgumentException("The specified options' type is invalid.", "options");
Fit(observations, weights, normalOptions);
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting, such
/// as regularization constants and additional parameters.</param>
///
public void Fit(double[] observations, double[] weights, NormalOptions options)
{
if (immutable)
throw new InvalidOperationException("NormalDistribution.Standard is immutable.");
double mu, var;
if (weights != null)
{
#if DEBUG
for (int i = 0; i < weights.Length; i++)
if (Double.IsNaN(weights[i]) || Double.IsInfinity(weights[i]))
throw new ArgumentException("Invalid numbers in the weight vector.", "weights");
#endif
// Compute weighted mean
mu = Measures.WeightedMean(observations, weights);
// Compute weighted variance
var = Measures.WeightedVariance(observations, weights, mu);
}
else
{
// Compute weighted mean
mu = Measures.Mean(observations);
// Compute weighted variance
var = Measures.Variance(observations, mu);
}
if (options != null)
{
// Parse optional estimation options
double regularization = options.Regularization;
if (var == 0 || Double.IsNaN(var) || Double.IsInfinity(var))
var = regularization;
}
if (Double.IsNaN(var) || var <= 0)
{
throw new ArgumentException("Variance is zero. Try specifying "
+ "a regularization constant in the fitting options.");
}
initialize(mu, Math.Sqrt(var), var);
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
///
public override object Clone()
{
return new NormalDistribution(mean, stdDev);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
///
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
///
public override string ToString(string format, IFormatProvider formatProvider)
{
return String.Format(formatProvider, "N(x; μ = {0}, σ² = {1})",
mean.ToString(format, formatProvider),
variance.ToString(format, formatProvider));
}
private void initialize(double mu, double dev, double var)
{
this.mean = mu;
this.stdDev = dev;
this.variance = var;
// Compute derived values
this.lnconstant = -Math.Log(Constants.Sqrt2PI * dev);
}
/// <summary>
/// Estimates a new Normal distribution from a given set of observations.
/// </summary>
///
public static NormalDistribution Estimate(double[] observations)
{
return Estimate(observations, null, null);
}
/// <summary>
/// Estimates a new Normal distribution from a given set of observations.
/// </summary>
///
public static NormalDistribution Estimate(double[] observations, NormalOptions options)
{
return Estimate(observations, null, options);
}
/// <summary>
/// Estimates a new Normal distribution from a given set of observations.
/// </summary>
///
public static NormalDistribution Estimate(double[] observations, double[] weights, NormalOptions options)
{
NormalDistribution n = new NormalDistribution();
n.Fit(observations, weights, options);
return n;
}
/// <summary>
/// Converts this univariate distribution into a
/// 1-dimensional multivariate distribution.
/// </summary>
///
public MultivariateNormalDistribution ToMultivariateDistribution()
{
return new MultivariateNormalDistribution(
new double[] { mean }, new double[,] { { variance } });
}
/// <summary>
/// Generates a random vector of observations from the current distribution.
/// </summary>
///
/// <param name="samples">The number of samples to generate.</param>
///
/// <returns>A random vector of observations drawn from this distribution.</returns>
///
public override double[] Generate(int samples)
{
double[] r = new double[samples];
var g = new Accord.Math.Random.GaussianGenerator(
(float)mean, (float)stdDev, Accord.Math.Random.Generator.Random.Next());
for (int i = 0; i < r.Length; i++)
r[i] = g.Next();
return r;
}
/// <summary>
/// Generates a random vector of observations from the current distribution.
/// </summary>
///
/// <returns>A random vector of observations drawn from this distribution.</returns>
///
public override double Generate()
{
var g = new Accord.Math.Random.GaussianGenerator(
(float)mean, (float)stdDev, Accord.Math.Random.Generator.Random.Next());
return g.Next();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
namespace Dao.Mercadeo
{
public class CampaniaColorProductoDao : GenericDao<crmCampaniaColorProducto>, ICampaniaColorProductoDao
{
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
namespace NopSolutions.NopCommerce.DataAccess.Media
{
/// <summary>
/// Acts as a base class for deriving custom picture provider
/// </summary>
[DBProviderSectionName("nopDataProviders/PictureProvider")]
public abstract partial class DBPictureProvider : BaseDBProvider
{
#region Methods
/// <summary>
/// Gets a picture
/// </summary>
/// <param name="PictureID">Picture identifier</param>
/// <returns>Picture</returns>
public abstract DBPicture GetPictureByID(int PictureID);
/// <summary>
/// Deletes a picture
/// </summary>
/// <param name="PictureID">Picture identifier</param>
public abstract void DeletePicture(int PictureID);
/// <summary>
/// Inserts a picture
/// </summary>
/// <param name="PictureBinary">The picture binary</param>
/// <param name="Extension">The picture extension</param>
/// <param name="IsNew">A value indicating whether the picture is new</param>
/// <returns>Picture</returns>
public abstract DBPicture InsertPicture(byte[] PictureBinary, string Extension, bool IsNew);
/// <summary>
/// Updates the picture
/// </summary>
/// <param name="PictureID">The picture identifier</param>
/// <param name="PictureBinary">The picture binary</param>
/// <param name="Extension">The picture extension</param>
/// <param name="IsNew">A value indicating whether the picture is new</param>
/// <returns>Picture</returns>
public abstract DBPicture UpdatePicture(int PictureID, byte[] PictureBinary, string Extension, bool IsNew);
#endregion
}
}
|
using MusicPlayer.Core.Models;
using MusicPlayer.UserControls;
namespace MusicPlayer.ViewModels.Interfaces
{
public interface IPlaylistsViewModel
{
Playlist CurrentPlaylist { get; set; }
string CurrentPlaylistName { get; set; }
SongsControl SongsControl { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Liquorly.Models;
using Liquorly.ViewModels;
namespace Liquorly.Controllers
{
public class CustomersController : Controller
{
// GET: Customer
public ActionResult Index()
{
IEnumerable<Customer> customerList = GetCustomers();
return View(customerList);
}
public ActionResult Details(int id)
{
var customer = GetCustomers().SingleOrDefault(c => c.Id==id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
private static IEnumerable<Customer> GetCustomers()
{
return new List<Customer>()
{
new Customer() {Id=1, Name = "MetalHead" },
new Customer() {Id =2, Name = "Hiipy"}
};
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YourProject_winForms
{
public partial class ServiceDetailsScreen : Form
{
#region MyLogger
// declaration of logger
private static readonly log4net.ILog myLog4N = log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion
#region Constructors
public ServiceDetailsScreen()
{
myLog4N.Debug("LN27: Initializing Service Details Form components.."); //logs message
InitializeComponent();
DoubleBuffered = true;
}
#endregion
#region Form Events
private void ServiceDetailsScreen_Load(object sender, EventArgs e)
{
myLog4N.Debug("LN38: Populating Service Grid.."); //logs message
PopulateGrid(); // populate grid
}
private void ServiceDetailsScreen_Paint(object sender, PaintEventArgs e)
{
myLog4N.Debug("LN44: Painting Service Screen.."); //logs message
// read the new Property settings of the ColorTheme
this.BackColor = Properties.Settings.Default.ColorTheme;
}
#endregion
#region Control events
// this takes us to the add new service screen
private void btnAddNewService_Click(object sender, EventArgs e)
{
AddNewService frm = new AddNewService();
if (frm.ShowDialog() == DialogResult.OK)
myLog4N.Debug("LN57: Ok Selected.." + MousePosition.ToString()); //logs message
myLog4N.Debug("LN58: Populating Service Grid.."); //logs message
PopulateGrid();
}
// this takes us to the edit service screen
private void EditServiceButton_Click(object sender, EventArgs e)
{
myLog4N.Debug("LN66: Edit Service Button Clicked.."); //logs message
if (dgvServices.CurrentCell == null) return;
myLog4N.Debug("LN69: Null Service Cell Selected.."); //logs message
long PKID = long.Parse(dgvServices[0, dgvServices.CurrentCell.RowIndex].Value.ToString());
EditService frm = new EditService(PKID);
if (frm.ShowDialog() == DialogResult.OK)
myLog4N.Debug("LN75: Edit Service Clicked, Populating Service Grid.."); //logs message
PopulateGrid();
}
// this loads the clicked cells tool information in the update tool screen
private void dgvServices_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvServices.CurrentCell == null) return;
myLog4N.Debug("LN83: Null Service Cell Selected.."); //logs message
long PKID = long.Parse(dgvServices[0, dgvServices.CurrentCell.RowIndex].Value.ToString());
EditService frm = new EditService(PKID);
if (frm.ShowDialog() == DialogResult.OK)
myLog4N.Debug("LN89: Ok Selected, Populating Product Grid.."); //logs message
PopulateGrid();
}
// this button will close this window
private void HomeButton_Click(object sender, EventArgs e)
{
myLog4N.Debug("LN96: Home Button Clicked.."); //logs button clicked message
CollectGarbage(); //calls for garbage collection
Close(); //closes the window
}
/// <summary>
/// Will delete the selected service record from the database.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDelete_Click(object sender, EventArgs e)
{
myLog4N.Debug("LN109: Delete Service Button Clicked.."); //logs button clicked message
try
{
if (MessageBox.Show("Are you sure you want to delete the selected service record?", "Service",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
myLog4N.Debug("LN116: Yes Option Selected.."); //logs button clicked message
long PKID = long.Parse(dgvServices[0, dgvServices.CurrentCell.RowIndex].Value.ToString());
//Use the DeleteRecord method
ProjectModel.DLL.ProjectContext.DeleteRecord("Service", "ServiceId", PKID.ToString());
myLog4N.Debug("LN122: Service Deleted, Populating Service Grid.."); //logs button clicked message
PopulateGrid();
}
}
catch (Exception ex)
{
MessageBox.Show("LN 127: Error Deleting Service Record ");
}
}
#endregion
#region Helper Methods
/// <summary>
/// Method used for populating data to our data grid view.
/// </summary>
private void PopulateGrid()
{
ProjectModel.DLL.ProjectContext.ConnectionString = Properties.Settings.Default.ConnectionString;
DataTable dtbServices = new DataTable();
dtbServices = ProjectModel.DLL.ProjectContext.GetDataTable("Service");
dgvServices.DataSource = dtbServices;
//added for removing columns from data table
dtbServices.Columns.Remove("ContactName");
dtbServices.Columns.Remove("ContactEmail");
dtbServices.Columns.Remove("Location");
dtbServices.Columns.Remove("ReceiptIMG");
dtbServices.Columns.Remove("Amount");
dtbServices.Columns.Remove("Comments");
myLog4N.Debug("Populating Grid...");
}
#endregion
#region Cleaner Methods
/// <summary>
/// This method will call for garbage collection.
/// </summary>
private void CollectGarbage()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
#endregion
#region FileHandling
#region Export To CSV File
/// <summary>
/// Export tools to CSV File
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ExportToolReport_Click(object sender, EventArgs e)
{
try
{
// create file save structure
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Report.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
// Message to user to acknowledge data is being prepared.
MessageBox.Show("Preparing data for export please wait...");
if (File.Exists(filename))
{
try
{
// delete file to save file with existing name.
File.Delete(filename);
}
catch (IOException ioCsvException)
{
// display export data error.
MessageBox.Show("ERROR writing data to disk." + ioCsvException.Message);
myLog4N.Debug(ioCsvException.StackTrace);
}
}
// count the columns in the data grid view(DGV).
int columnCount = dgvServices.ColumnCount;
// Store Column Names in string.
string columnNames = "";
// Collect data from DGV rows and store in Array.
string[] export = new string[dgvServices.RowCount + 1];
// Control structure For:
// Number of columns starting at the first index position.
// Count total number of columns in DGV and, Add.
for (int i = 0; i < columnCount; i++)
{
// Store column names to string - Add comma between column names.
columnNames += dgvServices.Columns[i].Name.ToString() + ",";
}
export[0] += columnNames;
for (int i = 1; (i - 1) < dgvServices.RowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
try
{
////////////////////////////////////////////////////////////////////
/// FIX Null Reference Exception.
/// DataGridView - set AllowUserToAddRows to False.
/// DataGridView - set AllowUserToDeleteRows to False.
///////////////////////////////////////////////////////////////////
// Add data rows.
export[i] += dgvServices.Rows[i - 1].Cells[j].Value.ToString() + ",";
myLog4N.Debug(dgvServices.Rows[i - 1].Cells[j].Value.ToString());
/////////////////////////////////////////////////////////////////////////////
/// EXAMPLE - FOR 2nd Null Ref Exception.
/// Use a '?' symbol to allow null values on export.
/// **Value?.ToString()**
///
/// // Add '?' at the end of Value to allow null values.
/// export[i] += dgvTools.Rows[i - 1].Cells[j].Value?.ToString() + ",";
/////////////////////////////////////////////////////////////////////////////
}
catch (IOException csvWriteException)
{
// display error to user.
MessageBox.Show("ERROR Null Reference found in data." + csvWriteException.Message);
myLog4N.Debug(csvWriteException.StackTrace);
}
}
}
// Export data from DGV to CSV file.
System.IO.File.WriteAllLines(sfd.FileName, export, System.Text.Encoding.UTF8);
// display prompts to the user about the files progress.
MessageBox.Show("CSV file generated successfully.");
myLog4N.Debug("CSV file generated successfully.");
}
}
catch (IOException CSVFailException)
{ // display catch message to user
MessageBox.Show("ERROR writing data CSV." + CSVFailException.Message);
myLog4N.Debug(CSVFailException.StackTrace);
}
}
#endregion
#endregion
private void printFile()
{
try
{
//instantiate print dialog
PrintDialog PD = new PrintDialog();
PD.ShowDialog();
//instantiate print document
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "Service_Receipt";
PD.Document = printDoc;
PD.AllowSelection = true;
PD.AllowSomePages = true;
//Call ShowDialog and print document
if (PD.ShowDialog() == DialogResult.OK) printDoc.Print();
}
catch (IOException IOE)
{
// display export data error.
MessageBox.Show("ERROR Printing File." + IOE.Message);
myLog4N.Debug("ERROR Printing File. " + IOE.StackTrace);
}
}
private void btnServiceList_Click(object sender, EventArgs e)
{
SearchServices frm = new SearchServices();
frm.ShowDialog();
}
// private void btnExportService_Click1(object sender, EventArgs e)
// {
// try
// {
// // create file save structure
// string filename = "";
// SaveFileDialog sfd = new SaveFileDialog();
// sfd.Filter = "CSV (*.csv)|*.csv";
// sfd.FileName = "Report.csv";
// if (sfd.ShowDialog() == DialogResult.OK)
// {
// // Message to user to acknowledge data is being prepared.
// MessageBox.Show("Preparing data for export please wait...");
// if (File.Exists(filename))
// {
// try
// {
// // delete file to save file with existing name.
// File.Delete(filename);
// }
// catch (IOException ioCsvException)
// {
// // display export data error.
// MessageBox.Show("ERROR writing data to disk." + ioCsvException.Message);
// myLog4N.Debug(ioCsvException.StackTrace);
// }
// }
// // count the columns in the data grid view(DGV).
// int columnCount = dgvServices.ColumnCount;
// // Store Column Names in string.
// string columnNames = "";
// // Collect data from DGV rows and store in Array.
// string[] export = new string[dgvServices.RowCount + 1];
// // Control structure For:
// // Number of columns starting at the first index position.
// // Count total number of columns in DGV and, Add.
// for (int i = 0; i < columnCount; i++)
// {
// // Store column names to string - Add comma between column names.
// columnNames += dgvServices.Columns[i].Name.ToString() + ",";
// }
// export[0] += columnNames;
// for (int i = 1; (i - 1) < dgvServices.RowCount; i++)
// {
// for (int j = 0; j < columnCount; j++)
// {
// try
// {
// ////////////////////////////////////////////////////////////////////
// /// FIX Null Reference Exception.
// /// DataGridView - set AllowUserToAddRows to False.
// /// DataGridView - set AllowUserToDeleteRows to False.
// ///////////////////////////////////////////////////////////////////
// // Add data rows.
// export[i] += dgvServices.Rows[i - 1].Cells[j].Value.ToString() + ",";
// myLog4N.Debug(dgvServices.Rows[i - 1].Cells[j].Value.ToString());
// /////////////////////////////////////////////////////////////////////////////
// /// EXAMPLE - FOR 2nd Null Ref Exception.
// /// Use a '?' symbol to allow null values on export.
// /// **Value?.ToString()**
// ///
// /// // Add '?' at the end of Value to allow null values.
// /// export[i] += dgvTools.Rows[i - 1].Cells[j].Value?.ToString() + ",";
// /////////////////////////////////////////////////////////////////////////////
// }
// catch (IOException csvWriteException)
// {
// // display error to user.
// MessageBox.Show("ERROR Null Reference found in data." + csvWriteException.Message);
// myLog4N.Debug(csvWriteException.StackTrace);
// }
// }
// }
// // Export data from DGV to CSV file.
// System.IO.File.WriteAllLines(sfd.FileName, export, System.Text.Encoding.UTF8);
// // display prompts to the user about the files progress.
// MessageBox.Show("CSV file generated successfully.");
// myLog4N.Debug("CSV file generated successfully.");
// }
// }
// catch (IOException CSVFailException)
// { // display catch message to user
// MessageBox.Show("ERROR writing data CSV." + CSVFailException.Message);
// myLog4N.Debug(CSVFailException.StackTrace);
// }
// }
}
}
|
namespace ConsoleWebServer.Application.Controllers
{
using System;
using System.Linq;
using Framework;
using Framework.ActionResults;
using Framework.ActionResults.ContentActions;
public class ApiController : Controller
{
private const string RefererStringFormat = "Referer";
private const string InvalidRefererStringFormat = "Invalid referer!";
private const string DateAvailableForStringFormat = "Data available for ";
private const string DateStringFormat = "yyyy-MM-dd";
public ApiController(HttpRequest request)
: base(request)
{
}
public IActionResult ReturnMe(string param)
{
return this.Json(new { param });
}
public IActionResult GetDateWithCors(string domainName)
{
var requestReferer = string.Empty;
if (this.Request.Headers.ContainsKey(RefererStringFormat))
{
requestReferer = this.Request.Headers[RefererStringFormat].FirstOrDefault();
}
if (string.IsNullOrWhiteSpace(requestReferer) || !requestReferer.Contains(domainName))
{
throw new ArgumentException(InvalidRefererStringFormat);
}
return new WithCors(domainName, new JsonActionResult(this.Request, new { date = DateTime.Now.ToString(DateStringFormat), moreInfo = DateAvailableForStringFormat + domainName }));
}
}
}
|
using AutoMapper;
using iCopy.SERVICES.IServices;
using iCopy.Web.Controllers;
using iCopy.Web.Helper;
using iCopy.Web.Resources;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace iCopy.Web.Areas.Location.Controllers
{
[Area(Strings.Area.Location), Authorize(Roles = Strings.Roles.Administrator)]
public class CountryController : BaseDataTableCRUDController<Model.Request.Country, Model.Request.Country, Model.Response.Country, Model.Request.CountrySearch, int>
{
public CountryController(ICRUDService<Model.Request.Country, Model.Request.Country, Model.Response.Country, Model.Request.CountrySearch, int> crudService,
SharedResource _localizer, IMapper mapper) : base(crudService, _localizer, mapper)
{
}
}
} |
using Newtonsoft.Json;
namespace CalcEnterpriseClient.Models
{
public class SessionTalk
{
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
[JsonProperty(PropertyName = "duration")]
public int Duration { get; set; }
[JsonProperty(PropertyName = "speakers")]
public string[] Speakers { get; set; }
}
} |
using System.IO;
using System.Linq;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AngularExe.Controllers
{
public class EventController : ApiController
{
[HttpGet]
public JToken Get(string id = null)
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("/");
return JObject.Parse(File.ReadAllText(
$"{path}app\\data\\event\\{id}.json"));
}
public JToken GetLastId()
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("/") + "app\\data\\event";
var mostRecentId = Directory.GetFiles(path, "*.json")
.Select(x => Path.GetFileName(x)?.TrimEnd(".json".ToCharArray()))
.OrderByDescending(i => i?.Length).ThenByDescending(c => c).FirstOrDefault();
return JObject.Parse(mostRecentId != null ? $"{{\"id\":{mostRecentId }}}" : "{\"id\":0}");
}
[HttpPost]
public void Post(string id, JObject eventData)
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("/");
File.WriteAllText(
$"{path}app\\data\\event\\{id}.json",
eventData.ToString(Formatting.None));
}
public JToken GetAll()
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("/") + "app\\data\\event";
var content = string.Empty;
foreach (var file in Directory.GetFiles(path))
{
content += File.ReadAllText(file) + ",";
}
return JArray.Parse($"[{content.Substring(0, content.Length - 1)}]");
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
namespace GitlabManager.Services.Database.Model
{
/// <summary>
/// Database model for ef-core for the Accounts-Table
/// </summary>
[Table("Accounts")]
public class DbAccount
{
/// <summary>
/// Internal account id
/// </summary>
public int Id { get; set; }
/// <summary>
/// Name of connection
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Description of the account
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gitlab URL
/// </summary>
public string HostUrl { get; set; }
/// <summary>
/// Private token for user
/// </summary>
public string AuthenticationToken { get; set; }
/// <summary>
/// UNIX Timestamp when account was updated the last time
/// </summary>
public long LastProjectUpdateAt { get; set; }
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.UI.Modules
{
public interface IProfileModule
{
bool DisplayModule { get; }
int ProfileUserId { get; }
}
}
|
#region using
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Gemini.Properties;
#endregion
namespace Gemini
{
static class Program
{
#region Definitions
private static bool IsNowRsync = false;
private static TimeSpan WaitTimeSpan = TimeSpan.FromSeconds(1);
private static ProcessStartInfo rsyncProcessStartInfo = new ProcessStartInfo();
private static TimeSpan IntervalTimeSpan = TimeSpan.FromSeconds(Settings.Default.IntervalSeconds);
#endregion
#region Main
/// <summary>
/// Main EntryPoint
/// </summary>
static void Main()
{
#region CreateRsyncProcessStartInfo
rsyncProcessStartInfo.FileName = Settings.Default.RsyncPath;
rsyncProcessStartInfo.Arguments = CreateRsyncArgs();
rsyncProcessStartInfo.CreateNoWindow = true;
rsyncProcessStartInfo.UseShellExecute = false;
rsyncProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
#endregion
#region Console
Console.WriteLine($"watching:{Settings.Default.LocalPath}");
#endregion
#region IntervalMode
if (Settings.Default.IntervalSeconds > 0)
{
Task.Run(() =>
{
while (true)
{
Thread.Sleep(IntervalTimeSpan);
if (Settings.Default.NotifyMode)
{
Console.WriteLine("rsync by interval");
}
Rsync(false);
}
});
}
#endregion
#region Watch
using (var fileSystemWatcher = new FileSystemWatcher(Settings.Default.LocalPath))
{
fileSystemWatcher.EnableRaisingEvents = true;
fileSystemWatcher.Created += (o, e) =>
{
if (Settings.Default.NotifyMode)
{
Console.WriteLine($"rsync by created: {e.FullPath}");
}
Rsync();
};
fileSystemWatcher.Deleted += (o, e) =>
{
if (Settings.Default.NotifyMode)
{
Console.WriteLine($"rsync by deleted: {e.FullPath}");
}
Rsync();
};
fileSystemWatcher.Changed += (o, e) =>
{
if (Settings.Default.NotifyMode)
{
Console.WriteLine($"rsync by changed: {e.FullPath}");
}
Rsync();
};
fileSystemWatcher.Renamed += (o, e) =>
{
if (Settings.Default.NotifyMode)
{
Console.WriteLine($"rsync by renamed: {e.OldFullPath} -> {e.FullPath}");
}
Rsync();
};
while (true)
{
fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All);
}
}
#endregion
}
#endregion
#region CreateRsyncArgs
private static string CreateRsyncArgs()
{
return $"-e \"ssh -p {Settings.Default.SSHPort} -i {Settings.Default.KeyFilePath}\" --delete {string.Join(" ", Settings.Default.ExcludeInclude.Cast<string>())} {(Settings.Default.CompressMode ? "-az" : " - a")} {Settings.Default.LocalPath.ConvertToLinuxPath()} {Settings.Default.RemoteUser}@{Settings.Default.RemoteHost}:{Settings.Default.RemotePath}";
}
#endregion
#region ConvertToLinuxPath
private static string ConvertToLinuxPath(this string path)
{
return Regex.Replace(path, @"^(?<drive>[A-Za-z]):\\", "/${drive}/").Replace(@"\", "/");
}
#endregion
#region RSync
private static void Rsync(bool wait = true)
{
#region Check
if (IsNowRsync)
{
if (!wait)
{
return;
}
#region Wait
while (true)
{
Thread.Sleep(WaitTimeSpan);
if (!IsNowRsync)
{
break;
}
}
#endregion
}
#endregion
#region Rsync
IsNowRsync = true;
try
{
var rsyncProcess = Process.Start(rsyncProcessStartInfo);
rsyncProcess.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
IsNowRsync = false;
}
#endregion
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Flyweight
{
class FlyweightFactory
{
Dictionary<int, Image> images = new Dictionary<int, Image>();
static Random shuffle = new Random();
private Image GetImage(int key)
{
Image image;
switch (key)
{
case 1:
image = Image.FromFile(@"C:\Users\izba_cr95\source\repos\Flyweight\Flyweight\images\Fotolia_85723666_XS.jpg");
images.Add(key, image);
return image;
case 2:
image = Image.FromFile(@"C:\Users\izba_cr95\source\repos\Flyweight\Flyweight\images\Mops.jpg");
images.Add(key, image);
return image;
case 3:
image = Image.FromFile(@"C:\Users\izba_cr95\source\repos\Flyweight\Flyweight\images\mops_53201193_XS.jpg");
images.Add(key, image);
return image;
case 4:
image = Image.FromFile(@"C:\Users\izba_cr95\source\repos\Flyweight\Flyweight\images\Psy rasy Mops.jpg");
images.Add(key, image);
return image;
}
return null;
}
public void loadFromList(PictureBox picture)
{
int id = shuffle.Next(1, 5);
if (images.ContainsKey(id))
{
picture.BackgroundImage = images[id];
}
else
{
picture.BackgroundImage = GetImage(id);
}
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System.Linq;
namespace Jieshai.Web
{
/// <summary>
/// 授权过滤
/// </summary>
public class AuthorizationFilter : IAuthorizationFilter
{
public AuthorizationFilter()
{
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <remarks>用于统一过滤登录用户的状态是否有效,如果无效,拒绝请求</remarks>
public void OnAuthorization(AuthorizationFilterContext context)
{
var httpCtx = context.HttpContext;
//跳过的请求
if (SkipRequest(httpCtx.Request.Path))
{
return;
}
var hasToken = httpCtx.Request.Cookies.TryGetValue("token", out string token);
if (hasToken)
{
var existToken = Jieshai.Core.JieshaiManager.Instace.UserManager.ExistToken(token);
if (existToken)
{
return;
}
}
var ulr = new UserLoginResult(-1)
{
Message = "请重新登录"
};
context.Result = new JsonResult(ulr);
}
/// <summary>
/// 是否跳过请求url,比如登录请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private bool SkipRequest(string url)
{
List<string> skipUrls = new List<string>()
{
"/login"
};
url = url.ToLowerInvariant();
return skipUrls.Any(p => url.IndexOf(p)==0);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using FluentAssertions;
using Xunit;
namespace Microsoft.CodeAnalysis.Sarif.Visitors
{
public class RunMergingVisitorTests
{
[Fact]
public void RunMergingVisitor_RemapsNestedFilesProperly()
{
// This run has a single result that points to a doubly nested file.
var baselineRun = new Run
{
Tool = new Tool { Driver = new ToolComponent { Name = "Test Tool" } },
Artifacts = new List<Artifact>
{
new Artifact{ Location = new ArtifactLocation{ Index = 0 }, Contents = new ArtifactContent { Text = "1" } },
new Artifact{ Location = new ArtifactLocation{ Index = 1 }, Contents = new ArtifactContent { Text = "1.2" }, ParentIndex = 0 },
new Artifact{ Location = new ArtifactLocation{ Index = 2 }, Contents = new ArtifactContent { Text = "1.2.3." }, ParentIndex = 1 }
},
Results = new List<Result>
{
new Result
{
Locations = new List<Location>
{
new Location
{
PhysicalLocation = new PhysicalLocation
{
ArtifactLocation = new ArtifactLocation
{
Index = 2
}
}
}
}
}
}
};
// This run has a single result pointing to a single file location.
var currentRun = new Run
{
Tool = new Tool { Driver = new ToolComponent { Name = "Test Tool" } },
Artifacts = new List<Artifact>
{
new Artifact{ Location = new ArtifactLocation{ Index = 0 }, Contents = new ArtifactContent { Text = "New" } },
new Artifact{ Location = new ArtifactLocation{ Index = 1 }, Contents = new ArtifactContent { Text = "Child of new" }, ParentIndex = 0 },
},
Results = new List<Result>
{
new Result
{
Locations = new List<Location>
{
new Location
{
PhysicalLocation = new PhysicalLocation
{
ArtifactLocation = new ArtifactLocation
{
Index = 0
}
}
}
}
}
}
};
// Use the RunMergingVisitor to merge two runs
var visitor = new RunMergingVisitor();
Run mergedRun = currentRun.DeepClone();
Run baselineRunCopy = baselineRun.DeepClone();
visitor.VisitRun(mergedRun);
visitor.VisitRun(baselineRunCopy);
visitor.PopulateWithMerged(mergedRun);
// Confirm that Artifacts (including indirectly referenced ones) were all copied to the destination Run
mergedRun.Artifacts.Count.Should().Be(baselineRun.Artifacts.Count + currentRun.Artifacts.Count);
// Confirm that Artifacts have consistent indices in the merged Run
for (int i = 0; i < mergedRun.Artifacts.Count; i++)
{
mergedRun.Artifacts[i].Location.Index.Should().Be(i);
}
// Verify each merged Run Result ArtifactIndex points to an Artifact with the same
// text as the corresponding original Result
VerifyArtifactMatches(mergedRun, currentRun, 0);
VerifyArtifactMatches(mergedRun, baselineRun, currentRun.Results.Count);
// Verify that the parent index chain for the nested artifacts was updated properly
// Recall that visitor placed the artifacts from the baseline run at the end of the
// merged run's artifacts array, and that in this test case, the artifacts in the
// baseline run were arranged with the most nested artifact at the end.
Artifact artifact = mergedRun.Artifacts[mergedRun.Artifacts.Count - 1];
artifact.ParentIndex.Should().Be(3);
artifact = mergedRun.Artifacts[artifact.ParentIndex];
artifact.ParentIndex.Should().Be(2);
artifact = mergedRun.Artifacts[artifact.ParentIndex];
artifact.ParentIndex.Should().Be(-1);
}
private void VerifyArtifactMatches(Run mergedRun, Run sourceRun, int firstResultIndex)
{
for (int i = 0; i < sourceRun.Results.Count; ++i)
{
int previousArtifactIndex = sourceRun.Results[i].Locations[0].PhysicalLocation.ArtifactLocation.Index;
Artifact previousArtifact = sourceRun.Artifacts[previousArtifactIndex];
int newArtifactIndex = mergedRun.Results[firstResultIndex].Locations[0].PhysicalLocation.ArtifactLocation.Index;
Artifact newArtifact = mergedRun.Artifacts[newArtifactIndex];
newArtifact.Contents.Text.Should().Be(previousArtifact.Contents.Text);
firstResultIndex++;
}
}
[Fact]
public void RunMergingVisitor_RemapsLogicalLocations()
{
var baselineRun = new Run
{
Tool = new Tool { Driver = new ToolComponent { Name = "Test Tool" } },
LogicalLocations = new List<LogicalLocation>
{
new LogicalLocation
{
Index = 0,
ParentIndex = -1,
Kind = LogicalLocationKind.Namespace,
Name = "N1",
FullyQualifiedName = "N1"
},
new LogicalLocation
{
Index = 1,
ParentIndex = 0,
Kind = LogicalLocationKind.Type,
Name = "T1",
FullyQualifiedName = "N1.T1"
},
new LogicalLocation
{
Index = 2,
ParentIndex = 1,
Kind = LogicalLocationKind.Member,
Name = "M1",
FullyQualifiedName = "N1.T1.M1"
},
},
Results = new List<Result>
{
new Result
{
Locations = new List<Location>
{
new Location
{
LogicalLocation = new LogicalLocation
{
Index = 2
}
}
}
},
// This result implicates a logical location that has already been encountered.
// The visitor should count it only once.
new Result
{
Locations = new List<Location>
{
new Location
{
LogicalLocation = new LogicalLocation
{
Index = 1
}
}
}
}
}
};
// This run has a single result that points to a different logical location.
var currentRun = new Run
{
Tool = new Tool { Driver = new ToolComponent { Name = "Test Tool" } },
LogicalLocations = new List<LogicalLocation>
{
new LogicalLocation
{
Index = 0,
ParentIndex = -1,
Kind = LogicalLocationKind.Namespace,
Name = "N2",
FullyQualifiedName = "N2"
},
new LogicalLocation
{
Index = 1,
ParentIndex = 0,
Kind = LogicalLocationKind.Type,
Name = "T2",
FullyQualifiedName = "N2.T2"
}
},
Results = new List<Result>
{
new Result
{
Locations = new List<Location>
{
new Location
{
LogicalLocation = new LogicalLocation
{
Index = 1
}
}
}
}
}
};
Run mergedRun = currentRun.DeepClone();
Run baselineRunCopy = baselineRun.DeepClone();
// Merge Results from the Current and Baseline Run
var visitor = new RunMergingVisitor();
visitor.VisitRun(mergedRun);
visitor.VisitRun(baselineRunCopy);
visitor.PopulateWithMerged(mergedRun);
// Verify each Result points to a LogicalLocation with the same FullyQualifiedName as before
VerifyLogicalLocationMatches(mergedRun, currentRun, 0);
VerifyLogicalLocationMatches(mergedRun, baselineRun, currentRun.Results.Count);
// The logical locations in the merged run are the union of the logical locations from
// the baseline and current runs. In this test case, there are no logical locations in
// common between the two runs, so the number of logical locations in the merged run is
// just the sum of the baseline and current runs.
mergedRun.LogicalLocations.Count.Should().Be(baselineRun.LogicalLocations.Count + currentRun.LogicalLocations.Count);
}
private void VerifyLogicalLocationMatches(Run mergedRun, Run sourceRun, int firstResultIndex)
{
for (int i = 0; i < sourceRun.Results.Count; ++i)
{
int previousIndex = sourceRun.Results[i].Locations[0].LogicalLocation.Index;
LogicalLocation previousLocation = sourceRun.LogicalLocations[previousIndex];
int newIndex = mergedRun.Results[firstResultIndex].Locations[0].LogicalLocation.Index;
LogicalLocation newLocation = mergedRun.LogicalLocations[newIndex];
newLocation.FullyQualifiedName.Should().Be(previousLocation.FullyQualifiedName);
firstResultIndex++;
}
}
[Fact]
public void RunMergingVisitor_MapsRulesProperly()
{
var baselineRun = new Run
{
Tool = new Tool
{
Driver = new ToolComponent
{
Name = "Test Tool",
Rules = new List<ReportingDescriptor>()
{
new ReportingDescriptor() { Id = "Rule001" },
new ReportingDescriptor() { Id = "Rule002" },
}
},
},
Results = new List<Result>
{
new Result { RuleIndex = 1 },
new Result { RuleIndex = 0 },
new Result { RuleIndex = 1 }
}
};
var currentRun = new Run
{
Tool = new Tool
{
Driver = new ToolComponent
{
Name = "Test Tool",
Rules = new List<ReportingDescriptor>()
{
new ReportingDescriptor() { Id = "Rule001" },
new ReportingDescriptor() { Id = "Rule003" },
new ReportingDescriptor() { Id = "Rule004" },
}
},
},
Results = new List<Result>
{
new Result { RuleIndex = 0 },
new Result { RuleIndex = 1 },
new Result { RuleIndex = 1 }
}
};
// Use the RunMergingVisitor to merge two runs, via Run.MergeResultsFrom
Run mergedRun = currentRun.DeepClone();
Run baselineRunCopy = baselineRun.DeepClone();
mergedRun.MergeResultsFrom(baselineRunCopy);
// We should get RuleId001, 002, 003. Rule004 wasn't referenced. Rule001 was used in both Runs.
mergedRun.Tool.Driver.Rules.Count.Should().Be(3);
// Verify each merged Run Result ArtifactIndex points to an Artifact with the same
// text as the corresponding original Result
VerifyRuleMatches(mergedRun, currentRun, 0);
VerifyRuleMatches(mergedRun, baselineRun, currentRun.Results.Count);
}
private void VerifyRuleMatches(Run mergedRun, Run sourceRun, int firstResultIndex)
{
for (int i = 0; i < sourceRun.Results.Count; ++i)
{
Result previous = sourceRun.Results[i];
Result newResult = mergedRun.Results[firstResultIndex];
string expectedRuleId = previous.GetRule(sourceRun).Id;
newResult.RuleId.Should().Be(expectedRuleId);
newResult.GetRule(mergedRun).Id.Should().Be(expectedRuleId);
firstResultIndex++;
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Resources {
public Text availableGold;
public Text availableTime;
public Resources()
{
availableGold = GameObject.Find ("CurrentGold").GetComponent<Text>();
availableTime = GameObject.Find ("CurrentTime").GetComponent<Text>();
}
public void updateResources(int gold, int time)
{
availableGold.text = "Gold: " + gold.ToString();
availableTime.text = "Time: " + time.ToString();
}
/*void Update()
{
int time = 0;
int gold = 0;
time++;
gold++;
textGold.text = "wtf"+gold.ToString();
}*/
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace Bililive_dm
{
/// <summary>
/// DanmakuTextControl.xaml 的互動邏輯
/// </summary>
public partial class DanmakuTextControl : UserControl
{
/// <summary>
/// 使用的字體
/// </summary>
public static FontFamily TextFontFamily = new FontFamily();
private readonly int _addtime;
public DanmakuTextControl(int addtime = 0, bool warning = false)
{
_addtime = addtime;
InitializeComponent();
Text.FontFamily = TextFontFamily;
UserName.FontFamily = TextFontFamily;
sp.FontFamily = TextFontFamily;
if (warning) LayoutRoot.Background = Brushes.Red;
var sb = (Storyboard)Resources["Storyboard1"];
Storyboard.SetTarget(sb.Children[2], this);
(sb.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[1].KeyTime =
KeyTime.FromTimeSpan(new TimeSpan(Convert.ToInt64(Store.MainOverlayEffect1 * TimeSpan.TicksPerSecond)));
(sb.Children[1] as DoubleAnimationUsingKeyFrames).KeyFrames[1].KeyTime =
KeyTime.FromTimeSpan(new TimeSpan(Convert.ToInt64(Store.MainOverlayEffect1 * TimeSpan.TicksPerSecond)));
(sb.Children[1] as DoubleAnimationUsingKeyFrames).KeyFrames[2].KeyTime =
KeyTime.FromTimeSpan(
new TimeSpan(
Convert.ToInt64((Store.MainOverlayEffect2 + Store.MainOverlayEffect1) *
TimeSpan.TicksPerSecond)));
(sb.Children[2] as DoubleAnimationUsingKeyFrames).KeyFrames[0].KeyTime =
KeyTime.FromTimeSpan(
new TimeSpan(
Convert.ToInt64((Store.MainOverlayEffect3 + Store.MainOverlayEffect2 +
Store.MainOverlayEffect1 + _addtime) *
TimeSpan.TicksPerSecond)));
(sb.Children[2] as DoubleAnimationUsingKeyFrames).KeyFrames[1].KeyTime =
KeyTime.FromTimeSpan(
new TimeSpan(
Convert.ToInt64((Store.MainOverlayEffect4 + Store.MainOverlayEffect3 +
Store.MainOverlayEffect2 +
Store.MainOverlayEffect1 + _addtime) * TimeSpan.TicksPerSecond)));
Loaded += DanmakuTextControl_Loaded;
}
public void ChangeHeight()
{
TextBox.FontSize = Store.MainOverlayFontsize;
TextBox.Measure(new Size(Store.MainOverlayWidth, int.MaxValue));
var sb = (Storyboard)Resources["Storyboard1"];
var kf1 = sb.Children[0] as DoubleAnimationUsingKeyFrames;
kf1.KeyFrames[1].Value = TextBox.DesiredSize.Height;
}
private void DanmakuTextControl_Loaded(object sender, RoutedEventArgs e)
{
var sb = (Storyboard)Resources["Storyboard1"];
Storyboard.SetTarget(sb.Children[2], this);
(sb.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[1].KeyTime =
KeyTime.FromTimeSpan(new TimeSpan(Convert.ToInt64(Store.MainOverlayEffect1 * TimeSpan.TicksPerSecond)));
(sb.Children[1] as DoubleAnimationUsingKeyFrames).KeyFrames[1].KeyTime =
KeyTime.FromTimeSpan(new TimeSpan(Convert.ToInt64(Store.MainOverlayEffect1 * TimeSpan.TicksPerSecond)));
(sb.Children[1] as DoubleAnimationUsingKeyFrames).KeyFrames[2].KeyTime =
KeyTime.FromTimeSpan(
new TimeSpan(
Convert.ToInt64((Store.MainOverlayEffect2 + Store.MainOverlayEffect1) *
TimeSpan.TicksPerSecond)));
(sb.Children[2] as DoubleAnimationUsingKeyFrames).KeyFrames[0].KeyTime =
KeyTime.FromTimeSpan(
new TimeSpan(
Convert.ToInt64((Store.MainOverlayEffect3 + Store.MainOverlayEffect2 +
Store.MainOverlayEffect1 + _addtime) *
TimeSpan.TicksPerSecond)));
(sb.Children[2] as DoubleAnimationUsingKeyFrames).KeyFrames[1].KeyTime =
KeyTime.FromTimeSpan(
new TimeSpan(
Convert.ToInt64((Store.MainOverlayEffect4 + Store.MainOverlayEffect3 +
Store.MainOverlayEffect2 +
Store.MainOverlayEffect1 + _addtime) * TimeSpan.TicksPerSecond)));
Loaded -= DanmakuTextControl_Loaded;
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
namespace QFramework
{
public class UIScrollPageMark : MonoBehaviour
{
public UIScrollPage scrollPage;
public ToggleGroup toggleGroup;
public Toggle togglePrefab;
[Tooltip("页签中心位置")]
public UnityEngine.Vector2 centerPos;
[Tooltip("每个页签之间的间距")]
public UnityEngine.Vector2 interval;
public List<Toggle> toggleList = new List<Toggle>();
void Awake()
{
AdjustTogglePos();
scrollPage.AddPageChangeListener(OnScrollPageChanged);
}
public void OnScrollPageChanged(int pageCount, int currentPageIndex)
{
if (pageCount != toggleList.Count)
{
if (pageCount > toggleList.Count)
{
int cc = pageCount - toggleList.Count;
for (int i = 0; i < cc; i++)
{
toggleList.Add(CreateToggle(i));
}
}
else if (pageCount < toggleList.Count)
{
while (toggleList.Count > pageCount)
{
Toggle t = toggleList[toggleList.Count - 1];
toggleList.Remove(t);
DestroyImmediate(t.gameObject);
}
}
AdjustTogglePos();
}
toggleGroup.gameObject.SetActive(pageCount > 1);
if (currentPageIndex >= 0)
{
for (int i = 0; i < toggleList.Count; i++)
{
if (i == currentPageIndex) toggleList[i].isOn = true;
else toggleList[i].isOn = false;
}
}
}
Toggle CreateToggle(int i)
{
Toggle t = GameObject.Instantiate<Toggle>(togglePrefab);
t.gameObject.SetActive(true);
t.transform.SetParent(toggleGroup.transform);
t.transform.localScale = Vector3.one;
t.transform.localPosition = Vector3.zero;
return t;
}
void AdjustTogglePos()
{
UnityEngine.Vector2 startPos = centerPos - 0.5f * (toggleList.Count - 1) * interval;
for (int i = 0; i < toggleList.Count; i++)
{
toggleList[i].GetComponent<RectTransform>().anchoredPosition = startPos + i * interval;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Erwine.Leonard.T.ExtensionMethods.IEnumerableTypes
{
/// <summary>
/// Represents results from Take2 extension methods which inserts one collection into another
/// </summary>
/// <typeparam name="T">The type of objects to enumerate.</typeparam>
public class Take2InsertResult<T> : IEnumerable<T>
{
private Take2ParseResult<T> _take2;
private IEnumerable<T> _result = null;
private IEnumerable<T> _inserted;
/// <summary>
/// Collection which was parsed
/// </summary>
public IEnumerable<T> Source { get { return this._take2.Source; } }
/// <summary>
/// Elements which sequentially occur before the inserted elements.
/// </summary>
public IEnumerable<T> BeforeInserted { get { return this._take2.Select(e => e); } }
/// <summary>
/// Elements which have been inserted.
/// </summary>
public IEnumerable<T> Inserted
{
get
{
if (this._inserted == null)
this._inserted = new T[0];
return this._inserted;
}
}
/// <summary>
/// Items which sequentially occur after the inserted elements.
/// </summary>
public IEnumerable<T> AfterInserted { get { return this._take2.Remaining; } }
/// <summary>
/// Elements new Take2ResultCollection object.
/// </summary>
/// <param name="take2">Object which represents the collection being inserted into.</param>
/// <param name="inserted">Elements being inserted.</param>
public Take2InsertResult(Take2ParseResult<T> take2, IEnumerable<T> inserted)
{
this._take2 = take2;
this._inserted = inserted;
}
/// <summary>
/// Returns an enumerator that iterates through the result collection.
/// </summary>
/// <returns>A <see cref="System.Collections.Generic.IEnumerator<T>"/> that can be used to iterate through the result collection.</returns>
public IEnumerator<T> GetEnumerator()
{
if (this._result == null)
{
if (this.Inserted is T[] && (this.Inserted as T[]).Length == 0)
this._result = this._take2.Source;
else if (this._take2.Source is T[] && (this._take2.Source as T[]).Length == 0)
this._result = this.Inserted;
else
this._result = this._take2.Concat(this.Inserted).Concat(this._take2.Remaining);
}
return this._result.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the result collection.
/// </summary>
/// <returns>An <see cref="System.Collections.IEnumerator"/> object that can be used to iterate through the result collection.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// 攝影機跟隨
/// </summary>
public class CameraFollow : MonoBehaviour
{
public GameObject _gFollowTarget;
void Start()
{
_gFollowTarget = GameObject.FindGameObjectWithTag("Player");
}
void Update()
{
if (_gFollowTarget != null)
{
this.gameObject.transform.position = new Vector3(_gFollowTarget.transform.position.x, _gFollowTarget.transform.position.y, this.gameObject.transform.position.z);
}
}
} |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NGSTweaker
{
public partial class FormMain : Form
{
private Util Utils = new Util();
private string ExecPath;
private FormSettings _FormSettings;
private FormMods _FormMods;
public FormMain()
{
Utils.WriteLog("Starting NGS Tweaker...");
InitializeComponent();
}
private void UpdateButtons()
{
ExecPath = Utils.GetExecPath();
if (ExecPath != string.Empty)
{
LaunchButton.Enabled = true;
ModsButton.Enabled = true;
}
}
private void LaunchButton_Click(object sender, EventArgs e)
{
Utils.WriteLog("Launching PSO2");
LaunchButton.Enabled = false;
LaunchButton.Text = "Launching...";
ProcessStartInfo gameInfo = new ProcessStartInfo()
{
FileName = ExecPath,
UseShellExecute = false,
Arguments = "-reboot -optimize"
};
gameInfo.EnvironmentVariables["SteamAppId"] = "1056640";
Process gameProcess = new Process()
{
StartInfo = gameInfo
};
gameProcess.Start();
LaunchButton.Text = "Running...";
gameProcess.WaitForExit();
LaunchButton.Enabled = true;
LaunchButton.Text = "Launch";
}
private void SettingsButton_Click(object sender, EventArgs e)
{
if (_FormSettings == null)
{
_FormSettings = new FormSettings();
_FormSettings.FormClosed += (o, ea) => { UpdateButtons(); _FormSettings = null; };
}
else
{
_FormSettings.WindowState = FormWindowState.Normal;
}
_FormSettings.Show();
}
private void ModButton_Click(object sender, EventArgs e)
{
if (_FormMods == null)
{
_FormMods = new FormMods();
_FormMods.FormClosed += (o, ea) => _FormMods = null;
}
else
{
_FormMods.WindowState = FormWindowState.Normal;
}
_FormMods.Show();
}
private void FormMain_Load(object sender, EventArgs e)
{
ExecPath = Utils.GetExecPath();
if (ExecPath == string.Empty)
{
MessageBox.Show("Binary folder has not been set, please locate pso2.exe.", "NGS Tweaker Setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
Utils.SetBinPath();
ExecPath = Utils.GetExecPath();
UpdateButtons();
}
else
{
UpdateButtons();
}
LaunchButton.Focus();
}
private void ExitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
|
using be.belgium.eid;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using nmct.ba.cashlessproject.model.WPF;
using nmct.ba.cashlessproject.organisation.customerApp.ViewModel.General;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;
using Thinktecture.IdentityModel.Client;
namespace nmct.ba.cashlessproject.organisation.customerApp.ViewModel.CustomerApp
{
public class HomeVM : ObservableObject, IPage
{
#region Properties
public String Name
{
get { return "Home"; }
}
private Customer _eIDCustomer;
public Customer EIDCustomer
{
get
{
if (_eIDCustomer == null)
_eIDCustomer = new Customer();
return _eIDCustomer;
}
set
{
if (_eIDCustomer == null)
_eIDCustomer = new Customer();
_eIDCustomer = value;
OnPropertyChanged("EIDCustomer");
}
}
private Customer _currentCustomer;
public Customer CurrentCustomer
{
get { return _currentCustomer; }
set
{
_currentCustomer = value;
OnPropertyChanged("CurrentCustomer");
}
}
#endregion
#region Constructor
public HomeVM()
{
GetToken();
}
#endregion
#region Methods
/*
* Get token for authentication to the database.
*/
private void GetToken()
{
OAuth2Client client = new OAuth2Client(new Uri("http://localhost:49534/token"));
String username = ConfigurationManager.AppSettings["Login"].ToString();
String password = ConfigurationManager.AppSettings["Password"].ToString();
TokenResponse token = client.RequestResourceOwnerPasswordAsync(username, password).Result;
ApplicationVM appVM = App.Current.MainWindow.DataContext as ApplicationVM;
ApplicationVM.token = token;
}
/*
* Get eID data.
*/
private async void GetEIDData()
{
try
{
BEID_ReaderSet.initSDK(true);
BEID_ReaderSet readerSet = BEID_ReaderSet.instance();
BEID_ReaderContext reader = readerSet.getReader();
if (reader.isCardPresent())
{
BEID_EIDCard card = reader.getEIDCard();
BEID_EId doc = card.getID();
EIDCustomer = new Customer();
EIDCustomer.NationalNumber = doc.getNationalNumber();
String firstName = doc.getFirstName();
String surName = doc.getSurname();
EIDCustomer.CustomerName = firstName + " " + surName;
String street = doc.getStreet();
String zipCode = doc.getZipCode();
String municipality = doc.getMunicipality();
EIDCustomer.Address = street + ", " + zipCode + " " + municipality;
BEID_Picture tempPicture = card.getPicture();
EIDCustomer.Picture = tempPicture.getData().GetBytes();
await LoginSignupCustomer();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/*
* Login or signup the customer.
*/
private async Task LoginSignupCustomer()
{
Boolean isCustomer = await IsCustomerInDatabase();
if (!isCustomer)
await AddNewCustomerToDatabase();
ShowBalance();
}
/*
* Check if customer is already in database.
*/
private async Task<Boolean> IsCustomerInDatabase()
{
using(HttpClient client = new HttpClient())
{
String tempUrl = "http://localhost:49534/api/customer?nationalNumber=";
String url = String.Format("{0}{1}", tempUrl, EIDCustomer.NationalNumber);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
String json = await response.Content.ReadAsStringAsync();
CurrentCustomer = JsonConvert.DeserializeObject<Customer>(json);
return true;
}
else
return false;
}
}
/*
* Add new customer to the database.
*/
private async Task AddNewCustomerToDatabase()
{
using(HttpClient client = new HttpClient())
{
String json = JsonConvert.SerializeObject(EIDCustomer);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.PostAsync("http://localhost:49534/api/customer", new StringContent(json, Encoding.UTF8, "application/json"));
if(response.IsSuccessStatusCode)
{
await LoginNewUser();
}
}
}
/*
* Log in new user.
*/
private async Task LoginNewUser()
{
using (HttpClient client = new HttpClient())
{
String tempUrl = "http://localhost:49534/api/customer?nationalNumber=";
String url = String.Format("{0}{1}", tempUrl, EIDCustomer.NationalNumber);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
String json = await response.Content.ReadAsStringAsync();
CurrentCustomer = JsonConvert.DeserializeObject<Customer>(json);
}
}
}
/*
* Show balance screen.
*/
private void ShowBalance()
{
ApplicationVM appVM = App.Current.MainWindow.DataContext as ApplicationVM;
appVM.SelectedCustomerID = CurrentCustomer.ID;
appVM.Pages.RemoveAt(0);
appVM.Pages.Add(new BalanceVM());
appVM.CurrentPage = appVM.Pages[0];
}
#endregion
#region Actions
public ICommand ScanCardCommand
{
get { return new RelayCommand(GetEIDData); }
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosiveController : MonoBehaviour, IGetStung
{
#region Animation Variables
[SerializeField] Animator explosiveAnimator;
float warningClipTime;
float timeToImpact;
float animSpeed;
float distance;
HornetController hornet;
#endregion
#region Explosion Variables
[SerializeField] float explosionForce = 100f;
[SerializeField] float explosionUpForce = 40f;
[SerializeField] float explosionRadius = 4f;
[SerializeField] ParticleSystem explodeParticles;
[SerializeField] GameObject explosiveObject;
[SerializeField] Collider triggerCollider;
#endregion
private void Awake()
{
explosiveAnimator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
explosiveAnimator.enabled = false;
}
private void OnEnable()
{
StartCoroutine(SubscribeToEvents());
}
IEnumerator SubscribeToEvents()
{
yield return new WaitForEndOfFrame();
EventManager.Instance.onStartGameplay += StartWarningAnim;
EventManager.Instance.onEndGamePlay += StopWarningAnim;
}
private void OnDisable()
{
if(EventManager.Instance != null)
{
EventManager.Instance.onStartGameplay -= StartWarningAnim;
EventManager.Instance.onEndGamePlay -= StopWarningAnim;
}
}
// Update is called once per frame
void Update()
{
if(explosiveAnimator.enabled == true)
{
UpdateWarningAnimation();
}
}
private void StartWarningAnim()
{
hornet = FindObjectOfType<HornetController>();
warningClipTime = Vector3.Distance(this.transform.position, hornet.transform.position);
explosiveAnimator.enabled = true;
}
private void StopWarningAnim()
{
explosiveAnimator.enabled = false;
}
private void UpdateWarningAnimation()
{
distance = Vector3.Distance(this.transform.position, hornet.transform.position);
timeToImpact = distance / (hornet.CurrentSpeed());
animSpeed = warningClipTime / timeToImpact;
explosiveAnimator.speed = animSpeed;
}
public void GetStung()
{
Explode();
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, explosionRadius);
}
private void Explode()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);
foreach(Collider objectInRange in colliders)
{
TargetController target = objectInRange.GetComponent<TargetController>();
if(target != null)
{
target.GetMyRigidBody().AddExplosionForce(explosionForce, transform.position, explosionRadius, explosionUpForce, ForceMode.Impulse);
target.GetStung();
}
}
triggerCollider.enabled = false;
explodeParticles.Play();
StopWarningAnim();
Destroy(explosiveObject);
Destroy(gameObject, 8f);
}
}
|
using ContactManagement.Service.BLL.Services;
using ContactManagement.Service.BLL.Services.Impl;
using ContactManagement.Service.DLL.Models;
using ContactManagement.Service.DLL.Repository;
using System.Data.Entity;
using System.Web.Http;
using Unity;
using Unity.WebApi;
namespace ContactManagement.Service
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<DbContext, ContactsManagementDbContext>();
container.RegisterType<IContactRepository, ContactRepository>();
container.RegisterType<IContactService, ContactService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
} |
using UnityEngine;
using System.Collections;
public class SnowballController : MonoBehaviour {
public float throwSpeed;
public GameObject splash;
Rigidbody2D rigidBody;
// Use this for initialization
void Awake () {
rigidBody = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
transform.localScale = new Vector2(rigidBody.velocity.x > 0 ? 1 : -1, 1);
}
void OnTriggerEnter2D(Collider2D collider ){
switch(collider.tag){
case "Destroyer":
Instantiate(splash, transform.position, Quaternion.identity);
Destroy(gameObject);
break;
case "Kid":
case "Bully":
ExplodeObject();
break;
}
}
void OnCollisionEnter2D(Collision2D collider ){
if(collider.transform.CompareTag("Player")){
if(collider.gameObject.GetComponent<PlayerController>().IsDashing() == true) return;
ExplodeObject();
}
}
//Public
public void DestroyObject(){
Destroy(gameObject);
}
public void SetVelocity(Vector2 direction){
rigidBody.velocity = throwSpeed * direction;
}
//Private
void ExplodeObject(){
gameObject.GetComponent<Animator>().SetBool("explode",true);
rigidBody.velocity = Vector2.ClampMagnitude(rigidBody.velocity,5f);
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace NekoUchi.Model
{
public class QnAUpisivanje : QnA
{
public override List<QnA> GenerateQnA(Course course, string username, string lessonName, Quiz quiz)
{
var qnAs = new List<QnA>();
var lesson = course.Lessons.Find(l => l.Name == lessonName);
// Words are components of lesson in question
if (quiz.LessonComponent == "Riječi")
{
foreach (var word in lesson.Words)
{
var qna = new QnAUpisivanje();
qna.CourseId = course.Identification;
qna.LessonName = lessonName;
qna.Username = username;
var translations = new Translations();
string questionField = translations.PrijevodiPoljaRijeci[quiz.QuestionField];
string answerField = translations.PrijevodiPoljaRijeci[quiz.AnswerField];
qna.Question = (string)word.GetType().GetProperty(questionField).GetValue(word, null);
qna.Answer = (string)word.GetType().GetProperty(answerField).GetValue(word, null);
qnAs.Add(qna);
}
}
// Sentences are components of lesson in question
else if (quiz.LessonComponent == "Rečenice")
{
foreach (var sentence in lesson.Sentences)
{
// To do...
}
}
// This is not a valid component
else
{
qnAs = null;
}
return qnAs;
}
}
}
|
using UnityEngine;
public class MyGameEnding : MonoBehaviour
{
#region Fields
[SerializeField] private AudioSource _exitAudio;
[SerializeField] private HealthController _bossHealthController;
[SerializeField] private HealthController _playerHealthController;
[SerializeField] private UIOutputController _uiOutputController;
[SerializeField] private float _fadeDuration = 5.0f;
private bool _isGameEnd;
private float _timer;
private bool _hasAudioPlayed;
#endregion
#region UnityMethods
private void Start()
{
_bossHealthController.OnDie += EndGame;
_playerHealthController.OnDie += _playerHealthController_OnDie;
}
private void _playerHealthController_OnDie()
{
_uiOutputController.DisplayCheckPointMessage("Вы проиграли!!!", _fadeDuration);
_uiOutputController.ShowRestartRound();
Time.timeScale = 0;
}
private void Update()
{
if (_isGameEnd)
{
EndLevel(_exitAudio);
}
}
#endregion
#region Methods
public void EndGame()
{
_isGameEnd = true;
}
private void EndLevel(AudioSource audioSource)
{
if (!_hasAudioPlayed)
{
audioSource.Play();
_uiOutputController.DisplayCheckPointMessage("Вы победили!!!", _fadeDuration);
_uiOutputController.DisplayVictoryImage();
_hasAudioPlayed = true;
}
_timer += Time.deltaTime;
if (_timer > _fadeDuration)
Application.Quit();
}
#endregion
}
|
using Game.Models;
using System;
using Xunit;
namespace GameTest1
{
public class UnitTest1
{
[Fact]
public void DrawTest()
{
//arrange
draw d = new draw() { DrawID = "123", DrawName = "DailyJackpot", date_dt = DateTime.Now };
//act
//assert
//Assert.IsInstanceOfType(d, typeof(draw));
//Assert.AreEqual(d.DrawID, "123");
//Assert.AreEqual(d.DrawName, "DailyJackpot");
//Assert.AreEqual(d.date_dt, DateTime.Now);
}
}
}
|
namespace ZentryAnticheat.Client.Scans
{
public enum ScanEnum
{
full = 1,
pedOnly = 2,
VehicleOnly = 3,
PropOnly = 4
}
} |
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using DiscordBotTest.Helpers;
using DiscordBotTest.Modules;
using DiscordBotTest.Runners;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Timers;
namespace DiscordBotTest
{
public class Program
{
public static void Main(string[] args) => new Program().RunBotAsync().GetAwaiter().GetResult();
private DiscordSocketClient _client;
private static readonly HttpClient _httpClient = new HttpClient();
private CommandService _commands;
private TrackManiaMapLeaderboardModelCache _trackManiaMapLeaderboardCache;
private IServiceProvider _services;
private readonly string _botToken = Configuration.GetAppSettings().Keys.BotToken;
private readonly Timer CheckForUpdateTimer = new Timer(30 * 60 * 1000);
private readonly Timer CheckForUpdate1mTimer = new Timer(60 * 1000);
public const ulong MyServerId = 199189022894063627;
private readonly ulong _testServerId = 430643719880835072;
public const ulong MyUserId = 198806112852508672;
// private static readonly string _testUser = "TheSweMasterX#5203";
public async Task RunBotAsync()
{
_client = new DiscordSocketClient();
_commands = new CommandService();
_trackManiaMapLeaderboardCache = new TrackManiaMapLeaderboardModelCache();
_services = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commands)
.AddSingleton(_httpClient)
.BuildServiceProvider();
// Event subsciptions
_client.Log += LogEvent;
_client.UserJoined += UserJoinedEvent;
CheckForUpdate1mTimer.Enabled = true;
CheckForUpdate1mTimer.Elapsed += new ElapsedEventHandler(TmNewRecordNotification);
//CheckForUpdateTimer.Elapsed += new ElapsedEventHandler(UpdateTotalLevelEvent);
//CheckForUpdateTimer.Elapsed += new ElapsedEventHandler(LevelUpNotificationsEvent);
//CheckForUpdateTimer.Elapsed += new ElapsedEventHandler(UpdateFloorBallSheetEvent);
await SetBotGameStatus();
await RegisterCommandsAsync();
await _client.LoginAsync(TokenType.Bot, _botToken);
await _client.StartAsync();
await Task.Delay(-1);
}
private async void TmNewRecordNotification(object sender, ElapsedEventArgs e)
{
await TrackManiaNewRecordNotification.TrySendNotification(_client, _httpClient, _trackManiaMapLeaderboardCache);
}
private void UpdateFloorBallSheetEvent(object sender, ElapsedEventArgs e)
{
new UpdateFloorballSheetRunner().Run(0);
}
private void LevelUpNotificationsEvent(object sender, ElapsedEventArgs e)
{
RSNotificationHelper.LevelUpNotification(_client);
}
private void UpdateTotalLevelEvent(object source, ElapsedEventArgs e)
{
RSUpdateListHelper.UpdateAllNickNameTotalLevel(_client, _testServerId).Wait();
}
private async Task SetBotGameStatus()
{
await _client.SetGameAsync("as Torbjörn | !!help");
}
private async Task UserJoinedEvent(SocketGuildUser user)
{
var guild = user.Guild;
var channel = guild.DefaultChannel;
await channel.SendMessageAsync($":wave: Welcome {user.Mention} to {guild.Name}!");
}
private Task LogEvent(LogMessage arg)
{
Console.WriteLine(arg);
return Task.CompletedTask;
}
public async Task RegisterCommandsAsync()
{
_client.MessageReceived += HandleCommandAsync;
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
}
private async Task HandleCommandAsync(SocketMessage arg)
{
if (!(arg is SocketUserMessage message) || message.Author.IsBot)
return;
int argPos = 0;
if (message.HasStringPrefix("!!", ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))
{
var context = new SocketCommandContext(_client, message);
var result = await _commands.ExecuteAsync(context, argPos, _services);
if (!result.IsSuccess)
{
Console.WriteLine(result.ErrorReason);
}
}
}
}
}
|
using Model.Helper;
using Model.Schema.EIVO;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Utility;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
namespace Kiosk.Helper
{
public static class ExtensionMethods
{
public static String GetLeftQRCodeImageSrc(this InvoiceRootInvoice item, int qrVersion = 10)
{
bool retry = false;
String qrContent = null;
try
{
qrContent = item.GetQRCodeContent();
return qrContent.CreateQRCodeImageSrc(width: 180, height: 180, qrVersion: qrVersion);
}
catch (Exception ex)
{
retry = true;
Logger.Error(ex);
Logger.Warn($"產生發票QR Code失敗 => {item.InvoiceNumber},\r\n{qrContent}\r\n{ex}");
}
if (retry)
{
try
{
qrContent = $"{qrContent.Substring(0, 88)}:1:1:1:品項過長,詳列於發票明細:1:1:";
return qrContent.CreateQRCodeImageSrc(width: 180, height: 180, qrVersion: 10);
}
catch (Exception ex)
{
Logger.Error(ex);
Logger.Warn($"產生發票QR Code失敗 => {item.InvoiceNumber},\r\n{qrContent}\r\n{ex}");
}
}
return null;
}
public static String GetBarcode39ImageSrc(this String content, int width = 320, int height = 80, int margin = 0, int? wide = null, int? narrow = null)
{
using (Bitmap img = content.GetCode39(false, wide, narrow, height, margin))
{
return CreateBase64Content(img, 0);
}
}
public static string CreateBase64Content(Bitmap img, float dpi = 600f)
{
using (MemoryStream buffer = new MemoryStream())
{
if (dpi > 0)
{
img.SetResolution(dpi, dpi);
}
img.Save(buffer, ImageFormat.Gif);
StringBuilder sb = new StringBuilder("data:image/gif;base64,");
sb.Append(Convert.ToBase64String(buffer.ToArray()));
return sb.ToString();
}
}
public static String CreateQRCodeImageSrc(this String content, int width = 160, int height = 160, int margin = 0, int qrVersion = 10)
{
using (Bitmap img = content.CreateQRCode(width, height, margin, qrVersion))
{
return CreateBase64Content(img);
}
}
public static Bitmap CreateQRCode(this String content, int width = 160, int height = 160, int margin = 0, int qrVersion = 10)
{
if (String.IsNullOrEmpty(content))
{
return null;
}
IBarcodeWriter writer = new BarcodeWriter()
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions()
{
ErrorCorrection = ErrorCorrectionLevel.L,
Margin = margin,
Width = width,
Height = height,
QrVersion = qrVersion,
CharacterSet = "UTF-8" // 少了這一行中文就亂碼了
}
};
Bitmap picCode = writer.Write(content);
picCode.SetResolution(600f, 600f);
return picCode;
}
public static String GetQRCodeContent(this InvoiceRootInvoice item)
{
string finalEncryData = item.CustomerDefined?.ProjectNo;
StringBuilder sb = new StringBuilder();
DateTime invoiceDate;
if (DateTime.TryParseExact(String.Format("{0} {1}", item.InvoiceDate?.Replace("/","").Replace("-",""), item.InvoiceTime), "yyyyMMdd HH:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out invoiceDate))
{
sb.Append(item.InvoiceNumber);
sb.Append(String.Format("{0:000}{1:00}{2:00}", invoiceDate.Year - 1911, invoiceDate.Month, invoiceDate.Day));
sb.Append(item.InvoiceNumber);
sb.Append(String.Format("{0:X8}", item.SalesAmount > 0
? (int)item.SalesAmount
: item.ZeroTaxSalesAmount > 0
? (int)item.ZeroTaxSalesAmount
: item.FreeTaxSalesAmount > 0
? (int)item.FreeTaxSalesAmount
: 0));
sb.Append(String.Format("{0:X8}", (int)item.TotalAmount));
sb.Append(item.BuyerId=="0000000000" ? "00000000" : item.BuyerId);
sb.Append(item.SellerId);
sb.Append(finalEncryData);
sb.Append(":");
sb.Append("**********");
sb.Append(":");
sb.Append(item.InvoiceItem.Length);
sb.Append(":");
sb.Append(item.InvoiceItem.Length);
sb.Append(":");
sb.Append(2);
sb.Append(":");
StringBuilder details = new StringBuilder();
foreach (var p in item.InvoiceItem)
{
if (p.Quantity>0)
{
details.Append(p.Description);
details.Append(":");
details.Append(String.Format("{0:#0}", p.Quantity));
details.Append(":");
details.Append(String.Format("{0:#0}", p.UnitPrice));
details.Append(":");
}
}
sb.Append(Convert.ToBase64String(Encoding.Default.GetBytes(details.ToString())));
}
return sb.ToString();
}
public static String ReadToEnd(this HttpRequestBase request)
{
using(StreamReader reader = new StreamReader(request.InputStream,request.ContentEncoding))
{
return reader.ReadToEnd();
}
}
}
} |
using DataCenter.Data;
using DataCenter.Helpers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Types;
namespace DataCenter._05_Google
{
internal class Google : DataSource
{
public Google() : base() { }
public Google(bool reload) : base(reload) { }
public override async Task Prepare(DataContainer dataContainer)
{
// Delete old data
if (Reload)
Directory.Delete(Folder, true);
// Create folder
Directory.CreateDirectory(Folder);
// Inernal data
_InternalData internalData = new _InternalData();
// Draw header
base.DrawHeader();
// Search
await DownloadSearchs(dataContainer.Products);
// Parse
Parse(internalData);
// SeDeSerialize
Cache(dataContainer, internalData);
// End info
Console.WriteLine();
}
private async Task DownloadSearchs(List<Product> products)
{
string prefix = "1/3 Searching...";
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 0), ConsoleColor.Gray);
// Count when we update progress bar
int drawEvery = Utils.PercentIntervalByLength(products.Count + DataManager.Config.ImportantWords.Length);
// Download
try
{
for (int i = 0; i < products.Count + DataManager.Config.ImportantWords.Length; ++i)
{
// Downloading info
string query, targetFile;
if (i < products.Count)
{
Product p = products[i];
query = WebUtility.UrlEncode(HttpUtility.HtmlDecode(p.Name.Remove(",", "(The)", "Inc.", "Corporation", "Company", "Corp.")));
targetFile = Path.Combine(Folder, "Symbol-" + p.Symbol + ".json");
}
else
{
string word = DataManager.Config.ImportantWords[i - products.Count];
query = WebUtility.UrlEncode(word);
targetFile = Path.Combine(Folder, "Word-" + word + ".json");
}
// Download target range
string url = "http://www.google.com/trends/fetchComponent?q=" + query + "&cid=TIMESERIES_GRAPH_0&export=3";
if (Reload || !File.Exists(targetFile))
await Downloader.DownloadFileAsync(url, targetFile, null, DataManager.Config.GoogleCookies);
// Check if downloaded properly
string content = File.ReadAllText(targetFile);
if (content.Contains("http://www.google.com/trends/errorPage"))
{
File.Delete(targetFile);
Thread.Sleep(60 * 1000);
--i;
continue;
}
// Update progress bar
if (i % drawEvery == 0)
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, (double)i / (products.Count + DataManager.Config.ImportantWords.Length) * 100.0), ConsoleColor.Gray);
}
}
catch (Exception ex)
{
Console.WriteLine();
Utils.DrawMessage("", ex.Message, ConsoleColor.Red);
Console.WriteLine();
System.Environment.Exit(1);
}
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 100), ConsoleColor.Green);
Console.WriteLine();
}
private void Parse(_InternalData internalData)
{
string prefix = "2/3 Parsing...";
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 0), ConsoleColor.Gray);
// Files to parse
string[] files = Directory.GetFiles(Folder).Where(x => x.Contains(".json")).ToArray();
// Count when we update progress bar
int drawEvery = Utils.PercentIntervalByLength(files.Length);
// Download
try
{
if (Reload || !File.Exists(SerializedFile))
for (int i = 0; i < files.Length; ++i)
{
// Parse only no errors data
string content = File.ReadAllText(files[i]);
content = content.Substring(content.IndexOf('{'));
content = content.Substring(0, content.LastIndexOf('}') + 1);
JObject json = JObject.Parse(content);
if (((string)json["status"]) == "ok")
{
JArray rows = (JArray)json["table"]["rows"];
foreach (JObject row in rows)
{
// Parse date
string dateStr = ((JConstructor)row["c"][0]["v"]).ToString();
string[] parts = dateStr.Split(new char[] { '\n' }).Select(x => x.Trim().Replace(",", "")).ToArray();
int year = int.Parse(parts[1]);
int month = int.Parse(parts[2]);
if (month == 0)
{
month = 12;
--year;
}
int day = int.Parse(parts[3]);
DateTime date = new DateTime(year, month, day).AddMonths(1);
month = date.Month;
// Parse value
int value = int.Parse((string)row["c"][1]["f"]);
// Save event to every day of month
while (date.Month == month)
{
internalData.Events.Add(new _Event()
{
Name = Path.GetFileNameWithoutExtension(files[i]).Split(new char[] { '-' })[1],
Date = date,
Value = value
});
date = date.AddDays(1);
}
}
}
// Update progress bar
if (i % drawEvery == 0)
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, (double)i / files.Length * 100.0), ConsoleColor.Gray);
}
}
catch (Exception ex)
{
Console.WriteLine();
Utils.DrawMessage("", ex.Message, ConsoleColor.Red);
Console.WriteLine();
System.Environment.Exit(1);
}
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 100), ConsoleColor.Green);
Console.WriteLine();
}
private void Cache(DataContainer dataContainer, _InternalData internalData)
{
string prefix = "3/3 Caching...";
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 0), ConsoleColor.Gray);
try
{
// Serialize or deserialize
_Cache cache = null;
if (Reload || !File.Exists(SerializedFile))
{
cache = new _Cache(internalData);
Serializer.Serialize(SerializedFile, cache);
}
else
cache = (_Cache)Serializer.Deserialize(SerializedFile);
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 50), ConsoleColor.Gray);
int drawEvery = Utils.PercentIntervalByLength(cache.Name.Count * 2);
// Save to datacontainer
for (int i = 0; i < cache.Name.Count; ++i)
{
// Create forex data
_GoogleData gd = new _GoogleData()
{
Value = cache.Value[i]
};
// Add to data container
dataContainer.GetEvent(new DateTime(cache.Date[i])).GoogleDatas.Add(cache.Name[i], gd);
if (i % drawEvery == 0)
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 50 + (double)i / cache.Name.Count * 50), ConsoleColor.Gray);
}
}
catch (Exception ex)
{
Console.WriteLine();
Utils.DrawMessage("", ex.Message, ConsoleColor.Red);
Console.WriteLine();
System.Environment.Exit(1);
}
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 100), ConsoleColor.Green);
Console.WriteLine();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NikeaaDesignWebsite.Models;
namespace NikeaaDesignWebsite.Api.Admin
{
[Route("api/admin/my-new-screen")]
[ApiController]
public class MyNewScreenController : ControllerBase
{
private readonly NikeaaDesignDBContext _context;
public MyNewScreenController(NikeaaDesignDBContext context)
{
_context = context;
}
// GET: api/admin/my-new-screen
[HttpGet]
public async Task<ActionResult<IEnumerable<MyNewScreen>>> GetMyNewScreen(int? page, int? size)
{
IQueryable<MyNewScreen> data = _context.MyNewScreen;
if (page != null && size != null)
{
data = data.Skip(((int)page - 1) * (int)size).Take((int)size);
}
return await data.ToListAsync();
}
// GET: api/admin/my-new-screen/5
[HttpGet("{id}")]
public async Task<ActionResult<MyNewScreen>> GetMyNewScreen(int id)
{
var MyNewScreen = await _context.MyNewScreen.FindAsync(id);
if (MyNewScreen == null)
{
return NotFound();
}
return MyNewScreen;
}
// PUT: api/admin/my-new-screen/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
public async Task<IActionResult> PutMyNewScreen(int id, MyNewScreen myNewScreen)
{
if (id != myNewScreen.Id)
{
return BadRequest();
}
_context.Entry(MyNewScreen).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MyNewScreenExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/admin/my-new-screen
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<MyNewScreen>> PostMyNewScreen(MyNewScreen myNewScreen)
{
_context.MyNewScreen.Add(myNewScreen);
await _context.SaveChangesAsync();
return CreatedAtAction("GetMyNewScreen", new { id = myNewScreen.Id }, MyNewScreen);
}
// DELETE: api/admin/my-new-screen/5
[HttpDelete("{id}")]
public async Task<ActionResult<MyNewScreen>> DeleteMyNewScreen(int id)
{
MyNewScreen myNewScreen = await _context.MyNewScreen.FindAsync(id);
if (myNewScreen == null)
{
return NotFound();
}
_context.MyNewScreen.Remove(myNewScreen);
await _context.SaveChangesAsync();
return myNewScreen;
}
private bool MyNewScreenExists(int id)
{
return _context.MyNewScreen.Any(e => e.Id == id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
namespace ConsoleAppliaction
{
class Program
{
static void Main(string[] args)
{
Person person = new Person("Alex", 18);
Console.WriteLine(person.ToString());
}
}
}
|
using System;
namespace Shakespokemon.Core
{
public static class Argument
{
public static void IsNotNullOrWhitespace(string value, string argumentName)
{
if(string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Can't be null or empty.", nameof(argumentName));
}
}
public static void IsNotNull(object value, string argumentName)
{
if(value == null)
{
throw new ArgumentNullException(nameof(argumentName));
}
}
public static void IsValid(bool condition, string message)
{
if(!condition)
{
throw new ArgumentException(message);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DissoleController : MonoBehaviour
{
[SerializeField]
private Material dissolveMat;
public Transform deadPoint;
[SerializeField]
private float dissolveRange = 0;
[SerializeField]
private bool isEnter = false;
// Use this for initialization
void Awake ()
{
dissolveRange = 0;
}
// Update is called once per frame
void Update ()
{
if (isEnter)
{
dissolveRange += 0.5f * Time.deltaTime;
}
Dissolve();
}
private void Dissolve()
{
dissolveMat.SetFloat("_Threshold", dissolveRange);
if (dissolveMat.GetFloat("_Threshold") >= 1.0f)
{
isEnter = false;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.tag == "Enemy")
{
isEnter = true;
}
}
public void Reset()
{
isEnter = false;
dissolveRange = 0;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace uppgift_1a
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("skriv en mening så kommer programmet \natt hitta antal stora A och små a:");
string test = Console.ReadLine();
int A = 0;
int a = 0;
foreach (char c in test)// loopar i genom string och får char värdet av varige string
{
if (c == 'A')//jämför om char värdet är lika med bokstaven A
{
A++;
}
else if (c == 'a')//jämför om char värdet är lika med bokstaven a
{
a++;
}
}
Console.WriteLine("antal stora A: {0}\nantal små a: {1}",A , a);
}
}
}
|
namespace Whale.Shared.Models.Meeting.MeetingMessage
{
public class GetMessagesDTO
{
public string MeetingId { get; set; }
public string Email { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Degree.Models;
using Degree.Models.Twitter;
using Degree.Services.TextAnalysis.Azure.Models;
namespace Degree.Services.TextAnalysis.Azure
{
public static class TweetCognitive
{
public static async Task<List<TweetSentiment>> AnalyzeTweetSentiment(List<TweetRaw> tweets)
{
var tweetsSentiment = new List<TweetSentiment>();
int page = 0;
int itemPerPage = 50;
var temp = new List<TweetRaw>();
temp.AddRange(tweets.Skip(itemPerPage * page++).Take(itemPerPage));
while (temp.Count > 0)
{
var textBatchInput = new TextAnalyticsBatchInput();
foreach (var t in temp)
{
var textAnalysis = new TextAnalyticsInput
{
Id = t.Id.ToString(),
Text = t.Text
};
textBatchInput.Documents.Add(textAnalysis);
}
var sentimentResponse = await AzureSentiment.SentimentV3PreviewPredictAsync(textBatchInput);
Console.WriteLine($"Tweets analyzed:{itemPerPage + itemPerPage * (page - 1)}");
foreach (var document in sentimentResponse.Documents)
{
var tweetSentiment = new TweetSentiment
{
TweetRawId = long.Parse(document.Id),
PositiveScore = document.DocumentScores.Positive,
NeutralScore = document.DocumentScores.Neutral,
NegativeScore = document.DocumentScores.Negative,
Sentiment = Enum.Parse<Degree.Models.DocumentSentimentLabel>(document.Sentiment.ToString()),
};
if (document.Sentences != null && document.Sentences.Count() > 0)
{
foreach (var sentence in document.Sentences)
{
var s = new TweetSentenceSentiment()
{
TweetSentimentId = long.Parse(document.Id),
Length = sentence.Length,
PositiveScore = sentence.SentenceScores.Positive,
NeutralScore = sentence.SentenceScores.Neutral,
NegativeScore = sentence.SentenceScores.Negative,
Offset = sentence.Offset,
Sentiment = Enum.Parse<Degree.Models.SentenceSentimentLabel>(sentence.Sentiment.ToString()),
Warnings = sentence.Warnings
};
tweetSentiment.Sentences.Add(s);
}
}
tweetsSentiment.Add(tweetSentiment);
}
temp.Clear();
temp.AddRange(tweets.Skip(itemPerPage * page++).Take(itemPerPage));
}
return tweetsSentiment;
}
public static async Task<List<TweetEntityRecognized>> AnalyzeTweetEntity(List<TweetRaw> tweets)
{
var tweetsEntity = new List<TweetEntityRecognized>();
int page = 0;
int itemPerPage = 50;
var temp = new List<TweetRaw>();
temp.AddRange(tweets.Skip(itemPerPage * page++).Take(itemPerPage));
while (temp.Count > 0)
{
var textBatchInput = new TextAnalyticsBatchInput();
foreach (var t in temp)
{
var textAnalysis = new TextAnalyticsInput
{
Id = t.Id.ToString(),
Text = t.Text
};
textBatchInput.Documents.Add(textAnalysis);
}
var entityRecognitionResponse = await AzureEntityRecognition.EntityRecognitionV3PreviewPredictAsync(textBatchInput);
Console.WriteLine($"Tweets analyzed:{itemPerPage + itemPerPage * (page - 1)}");
foreach (var document in entityRecognitionResponse.Documents)
{
foreach (var entity in document.Entities)
{
var tweetEntity = new TweetEntityRecognized
{
EntityName = entity.Text,
EntityType = entity.Type,
Length = entity.Length,
Offset = entity.Offset,
Score = entity.Score,
TweetRawId = long.Parse(document.Id)
};
tweetsEntity.Add(tweetEntity);
}
}
temp.Clear();
temp.AddRange(tweets.Skip(itemPerPage * page++).Take(itemPerPage));
}
return tweetsEntity;
}
}
}
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using PurificationPioneer.Scriptable;
using ReadyGamerOne.Utility;
using UnityEngine;
using UnityEngine.Assertions;
namespace ReadyGamerOne.Network
{
public class UdpHelper
{
public bool IsValid => clientSocket != null;
public int LocalUdpPort { get; private set; }
public string LocalIp { get; private set; }
public string TargetIp { get; private set; }
public int TargetPort { get; private set; }
#region private
private Socket clientSocket;
private Thread recvThread;
private byte[] udpRecvBuff;
private IPEndPoint targetIpEndPoint;
private Action<byte[], int, int> onRecvCmd;
private Action<Exception> onException;
private Func<bool> ifEnableSocketLog = () => true;
private bool shouldKill = false;
#endregion
public UdpHelper(
string targetIp,
int targetPort,
int localPort,
Action<Exception> onException,
Action<byte[],int,int> onRecvCmd,
int maxUdpPackageSize,
Func<bool> enableSocketLog=null,
Action onFinishedSetup=null,
byte[] initBytes=null)
{
Assert.IsNotNull(onException);
Assert.IsNotNull(onRecvCmd);
if (null != enableSocketLog)
this.ifEnableSocketLog = enableSocketLog;
this.onException = onException;
this.onRecvCmd = onRecvCmd;
this.udpRecvBuff=new byte[maxUdpPackageSize];
this.LocalUdpPort = localPort;
this.TargetIp = targetIp;
this.TargetPort = targetPort;
this.targetIpEndPoint = new IPEndPoint(IPAddress.Parse(TargetIp), TargetPort);
NetUtil.SetupUdp(
targetIpEndPoint,
LocalUdpPort,
RecvThread,
(localIp, socket, recvThread) =>
{
this.LocalIp = localIp;
//创建udpSocket
try
{
this.clientSocket = socket;
this.recvThread = recvThread;
#if DebugMode
if(ifEnableSocketLog())
Debug.Log($"Udp[local-{this.LocalIp}:{LocalUdpPort}] 开始接收");
#endif
onFinishedSetup?.Invoke();
}
catch (Exception e)
{
this.onException(e);
}
});
}
/// <summary>
/// 关闭接收器
/// </summary>
public void CloseReceiver()
{
shouldKill = true;
udpRecvBuff = null;
if (null != recvThread)
{
try
{
recvThread.Interrupt();
recvThread.Abort();
}
catch (Exception e)
{
#if DebugMode
if (GameSettings.Instance.EnableSocketClosingException)
{
Debug.Log($"[Udp.recvThread.Abort]{e}");
}
#endif
}
}
recvThread = null;
if (this.clientSocket != null && this.clientSocket.Connected)
{
try
{
this.clientSocket.Close();
}
catch (Exception e)
{
#if DebugMode
if (GameSettings.Instance.EnableSocketClosingException)
{
Debug.Log($"[Udp.clientSocket.Close]{e}");
}
#endif
}
}
this.clientSocket = null;
#if DebugMode
if(ifEnableSocketLog())
Debug.Log($"Udp[local-{this.LocalIp}:{LocalUdpPort}] 关闭连接");
#endif
}
/// <summary>
/// 发送内容
/// </summary>
/// <param name="content"></param>
public void Send(byte[] content)
{
try
{
this.clientSocket.BeginSendTo(
content,
0,
content.Length,
SocketFlags.None,
targetIpEndPoint,
OnUdpSend,
this.clientSocket);
#if DebugMode
if(ifEnableSocketLog())
Debug.Log($"Udp[Local:{this.LocalIp}:{LocalUdpPort}->{TargetIp}:{TargetPort}] 发送数据[{content.Length}]");
#endif
}
catch (Exception e)
{
onException(e);
}
}
#region Private
/// <summary>
/// UDP收数据线程
/// </summary>
private void RecvThread()
{
while (true)
{
if (shouldKill)
{
try
{
Thread.CurrentThread.Abort();
}
catch (Exception e)
{
#if DebugMode
if (GameSettings.Instance.EnableSocketClosingException)
{
Debug.Log($"[Udp.shouldKill.Abort]{e}");
}
#endif
}
break;
}
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
try
{
var receivedLength = this.clientSocket.ReceiveFrom(this.udpRecvBuff,ref remote);
#if DebugMode
if(ifEnableSocketLog())
Debug.Log($"Udp[local-{this.LocalIp}:{LocalUdpPort}] 收到数据[{receivedLength}]");
#endif
this.onRecvCmd(this.udpRecvBuff, 0, receivedLength);
}
catch (Exception e)
{
if(this.onException!=null)
this.onException(e);
break;
}
}
}
private void OnUdpSend(IAsyncResult ar)
{
try
{
var client = ar.AsyncState as Socket;
Assert.IsNotNull(client);
client.EndSendTo(ar);
}
catch (Exception e)
{
onException(e);
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace cosmetic_hub__e_shopping_system_.Models
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal ProductPrice { get; set; }
public string ShortProductDetails { get; set; }
public string LongProductDetails{ get; set; }
public string Image { get; set; }
public string ImageThumbnail { get; set; }
public bool IsPreferredProduct { get; set; }
public bool InStock { get; set; }
public int ProductCategoryId { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
}
}
|
namespace ProWritingAid.SDK.Model.Async
{
public interface IAsyncResponse<TBody>
{
string TaskId { get; set; }
TBody Result { get; set; }
}
} |
using Braspag.Domain.DTO;
using Braspag.Domain.Validators.Usuario;
using FluentValidation;
namespace Braspag.Domain.Commands
{
public static class UsuarioValidations
{
public static void ValidaUsuario(this UsuarioDto dto)
{
UsuarioValidators validator = new UsuarioValidators();
validator.ValidateAndThrow(dto);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Test
{
static void Main()
{
Person p1 = new Person("Todor");
Console.WriteLine(p1.ToString());
Person p2 = new Person("Misho", 20);
Console.WriteLine(p2.ToString());
Person p3 = new Person("Gosho", null);
Console.WriteLine(p3.ToString());
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using IVeraControl.Model;
using UpnpModels.Model;
using UpnpModels.Model.UpnpDevice;
using UpnpModels.Model.UpnpService;
using VeraControl.Model.UpnpService;
using VeraControl.Service;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace Test.UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Go_OnClick(object sender, RoutedEventArgs e)
{
Start();
}
private async Task Start()
{
var veraService = new VeraControlService();
var controllers = await veraService.GetControllers(
Username.Text,
Password.Text);
var veraPlus = controllers.FirstOrDefault(c => c.DeviceSerialId == "50102163");
var binaryLight = new BinaryLight1(veraPlus) { DeviceNumber = 49 };
var binaryLightStatus = await binaryLight.GetStateVariableAsync(ServiceType.SwitchPower1, SwitchPower1StateVariable.Status, ConnectionType.Local);
await binaryLight.ActionAsync(ServiceType.SwitchPower1, SwitchPower1Action.SetTarget, !binaryLightStatus, ConnectionType.Local);
}
}
}
|
namespace Belot.UI.Windows
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Belot.Engine;
using Belot.Engine.Game;
using Belot.Engine.GameMechanics;
using Belot.Engine.Players;
public class UiPlayer : IPlayer
{
private const int WaitTimeForAction = 50;
public event EventHandler<PlayerGetBidContext> InfoChangedInGetBid;
public event EventHandler<PlayerGetAnnouncesContext> InfoChangedInGetAnnounces;
public event EventHandler<PlayerPlayCardContext> InfoChangedInPlayCard;
public BidType? GetBidAction { get; set; }
public IList<Announce> GetAnnouncesAction { get; set; }
public PlayCardAction PlayCardAction { get; set; }
public BidType GetBid(PlayerGetBidContext context)
{
this.InfoChangedInGetBid?.Invoke(this, context);
while (this.GetBidAction == null)
{
Task.Delay(WaitTimeForAction);
}
var returnAction = this.GetBidAction.Value;
this.GetBidAction = null;
return returnAction;
}
public IList<Announce> GetAnnounces(PlayerGetAnnouncesContext context)
{
this.InfoChangedInGetAnnounces?.Invoke(this, context);
return context.AvailableAnnounces;
/*
while (this.GetAnnouncesAction == null)
{
Task.Delay(WaitTimeForAction);
}
var returnAction = this.GetAnnouncesAction;
this.GetAnnouncesAction = null;
return returnAction;
*/
}
public PlayCardAction PlayCard(PlayerPlayCardContext context)
{
this.InfoChangedInPlayCard?.Invoke(this, context);
while (this.PlayCardAction == null || !context.AvailableCardsToPlay.Contains(this.PlayCardAction.Card))
{
Task.Delay(WaitTimeForAction);
}
var returnAction = this.PlayCardAction;
this.PlayCardAction = null;
return returnAction;
}
public void EndOfTrick(IEnumerable<PlayCardAction> trickActions)
{
}
public void EndOfRound(RoundResult roundResult)
{
}
public void EndOfGame(GameResult gameResult)
{
}
}
}
|
using System;
using KelpNet.Common;
using KelpNet.Common.Functions;
namespace KelpNet.Functions.Activations
{
[Serializable]
public class Sigmoid : CompressibleActivation
{
const string FUNCTION_NAME = "Sigmoid";
public Sigmoid(string name = FUNCTION_NAME, string[] inputNames = null, string[] outputNames = null, bool gpuEnable = false) : base(FUNCTION_NAME, null, name, inputNames, outputNames, gpuEnable)
{
}
internal override Real ForwardActivate(Real x)
{
return 1 / (1 + Math.Exp(-x));
}
internal override Real BackwardActivate(Real gy, Real y)
{
return gy * y * (1 - y);
}
}
}
|
namespace ETLBox.DataFlow
{
/// <summary>
/// The mode of operation a DbMerge may work in.
/// Full means that source contains all data, NoDeletions that source contains all data but no deletions are executed,
/// Delta means that source has only delta information and deletions are deferred from a particular property and
/// OnlyUpdates means that only updates are applied to the destination.
/// </summary>
public enum MergeMode
{
Full = 0,
NoDeletions = 1,
Delta = 2,
OnlyUpdates = 3
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ExperianOfficeArrangement
{
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void OnPropertyChanged<T>(Expression<Func<T>> propertySelector)
{
this.OnPropertyChanged(PropertyName.Get(propertySelector));
}
protected void SetProperty<T>(ref T backingField, T value, [CallerMemberName] string callingMember = "")
{
backingField = value;
this.OnPropertyChanged(callingMember);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Swiddler.IO
{
public class CachedBlockIterator
{
readonly int BlockSize = Constants.BlockSize;
readonly Dictionary<long, ChunkDictionary> blocks = new Dictionary<long, ChunkDictionary>(); // key is block index (offset/blocksize)
public BlockReader Reader { get; }
public long EndingBlockIndex { get; private set; } = -1; // highest valid block in the file
public CachedBlockIterator(BlockReader reader)
{
Reader = reader;
}
public IEnumerable<ChunkDictionary> EnumerateBlocks(long fromOffset)
{
var blockIndex = fromOffset / BlockSize;
if (!blocks.TryGetValue(blockIndex, out var block))
block = ReadBlock(blockIndex);
while (block != null)
{
if (block.IsDirty)
RefreshBlock(block);
yield return block;
blockIndex++;
if (!blocks.TryGetValue(blockIndex, out block))
block = ReadBlock(blockIndex);
}
}
ChunkDictionary ReadBlock(long blockIndex)
{
if (blocks.TryGetValue(blockIndex - 1, out var prevBlock))
{
var prevChunkEndOffset = prevBlock.LastChunk.ActualOffset + prevBlock.LastChunk.ActualLength;
if (prevChunkEndOffset / BlockSize >= blockIndex) // previous chunk overlaps with current block
Reader.BaseStream.Position = prevBlock.LastChunk.ActualOffset;
else
Reader.BaseStream.Position = prevChunkEndOffset; // move to the next chunk because previous is ended in previous block
Reader.Read();
}
else
{
Reader.Position = blockIndex * BlockSize; // Seek & Read first chunk in block
}
ChunkDictionary block = null;
if (Reader.CurrentChunk != null)
{
block = new ChunkDictionary() { FirstSequenceNumber = Reader.CurrentChunk.SequenceNumber, BlockIndex = blockIndex };
blocks.Add(blockIndex, FillBlock(block));
}
if (block != null)
{
if (Reader.EndOfStream)
EndingBlockIndex = block.BlockIndex;
else if (blockIndex > EndingBlockIndex)
EndingBlockIndex = -1;
}
return block;
}
private void RefreshBlock(ChunkDictionary block)
{
block.IsDirty = false;
// try read next chunk recently added
Reader.BaseStream.Position = block.LastChunk.ActualOffset + block.LastChunk.ActualLength;
Reader.Read();
FillBlock(block);
}
private ChunkDictionary FillBlock(ChunkDictionary block)
{
while (Reader.CurrentChunk != null)
{
var chunk = Reader.CurrentChunk;
if (chunk.ActualOffset / BlockSize > block.BlockIndex) break;
block.Add(chunk.SequenceNumber, chunk);
block.LastSequenceNumber = chunk.SequenceNumber;
Reader.Read();
}
return block;
}
/// <summary>
/// Clean all blocks not in use.
/// </summary>
public void Invalidate()
{
foreach (var key in blocks.Keys.ToArray())
{
var block = blocks[key];
if (block.IsValid)
block.IsValid = false;
else
blocks.Remove(key);
}
}
internal void FileChanged() // called from Storage after data was written
{
if (blocks.TryGetValue(EndingBlockIndex, out var endingBlock)) endingBlock.IsDirty = true;
}
public void ClearCache()
{
blocks.Clear();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReadAndPlaceTree : MonoBehaviour {
public GameObject tree;
public TextAsset data;
private string text;
// Use this for initialization
void Start () {
if (data != null)
{
text = data.ToString();
text = text.Replace('.', ',');
processText(text);
}
}
private void processText(string text)
{
string[] lines = text.Split('\n');
foreach (string line in lines){
string[] treeData = line.Split(';');
if(treeData.Length == 5)
{
GameObject treeTemp = Instantiate(tree, new Vector3(float.Parse(treeData[0]), float.Parse(treeData[2]), float.Parse(treeData[1])), tree.transform.rotation, transform) as GameObject;
//update the houppier scale
GameObject houppier = treeTemp.transform.GetChild(0).gameObject;
float heightHouppier = ((houppier.GetComponent<MeshFilter>()).mesh.bounds).size.z;
float houppierSize = (float.Parse(treeData[3]) - float.Parse(treeData[2]));
float scale = houppierSize / heightHouppier;
houppier.transform.localScale = new Vector3(scale,scale,scale);
//update the leaves position and scale
GameObject leaves = treeTemp.transform.GetChild(1).gameObject;
//put leaves on houppier
leaves.transform.localPosition = new Vector3(leaves.transform.localPosition.x, leaves.transform.localPosition.y, houppierSize);
//calculate the actual topTree
float topHeightLeaves = ((leaves.GetComponent<MeshFilter>()).mesh.bounds).max.z + houppierSize;
//calculate the treetop based on the z tree
float treetop = float.Parse(treeData[4]) - float.Parse(treeData[2]);
float leavesScale = (treetop -houppierSize ) / (topHeightLeaves - houppierSize);
//scale leaves on z
leaves.transform.localScale = new Vector3(1, 1, leavesScale);
}
}
}
}
|
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace NtApiDotNet.Win32.Security.Audit
{
#pragma warning disable 1591
/// <summary>
/// Policy audit event type.
/// </summary>
public enum AuditPolicyEventType
{
System = 0,
Logon,
ObjectAccess,
PrivilegeUse,
DetailedTracking,
PolicyChange,
AccountManagement,
DirectoryServiceAccess,
AccountLogon
}
}
|
// <copyright file="DataDrivenHelper.cs" company="Objectivity Bespoke Software Specialists">
// Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved.
// </copyright>
// <license>
// The MIT License (MIT)
// 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.
// </license>
namespace Objectivity.Test.Automation.Tests.NUnit.DataDriven
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Common.Exceptions;
using global::NUnit.Framework;
/// <summary>
/// XML DataDriven methods for NUnit test framework <see href="https://github.com/ObjectivityLtd/Test.Automation/wiki/DataDriven-tests-from-Xml-files">More details on wiki</see>
/// </summary>
public static class DataDrivenHelper
{
/// <summary>
/// Reads the data drive file and set test name.
/// </summary>
/// <param name="folder">Full path to XML DataDriveFile file</param>
/// <param name="testData">Name of the child element in xml file.</param>
/// <param name="diffParam">Values of listed parameters will be used in test case name.</param>
/// <param name="testName">Name of the test, use as prefix for test case name.</param>
/// <returns>
/// IEnumerable TestCaseData
/// </returns>
/// <exception cref="System.ArgumentNullException">Exception when element not found in file</exception>
/// <exception cref="DataDrivenReadException">Exception when parameter not found in row</exception>
/// <example>How to use it: <code>
/// public static IEnumerable Credentials
/// {
/// get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "credential", new[] { "user", "password" }, "credential"); }
/// }
/// </code></example>
public static IEnumerable<TestCaseData> ReadDataDriveFile(string folder, string testData, string[] diffParam, [Optional] string testName)
{
var doc = XDocument.Load(folder);
if (!doc.Descendants(testData).Any())
{
throw new ArgumentNullException(string.Format(" Exception while reading Data Driven file\n row '{0}' not found \n in file '{1}'", testData, folder));
}
foreach (XElement element in doc.Descendants(testData))
{
var testParams = element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value);
var testCaseName = string.IsNullOrEmpty(testName) ? testData : testName;
try
{
testCaseName = TestCaseName(diffParam, testParams, testCaseName);
}
catch (DataDrivenReadException e)
{
throw new DataDrivenReadException(
string.Format(
" Exception while reading Data Driven file\n test data '{0}' \n test name '{1}' \n searched key '{2}' not found in row \n '{3}' \n in file '{4}'",
testData,
testName,
e.Message,
element,
folder));
}
var data = new TestCaseData(testParams);
data.SetName(testCaseName);
yield return data;
}
}
/// <summary>
/// Reads the data drive file without setting test name.
/// </summary>
/// <param name="folder">Full path to XML DataDriveFile file</param>
/// <param name="testData">Name of the child element in xml file.</param>
/// <returns>
/// IEnumerable TestCaseData
/// </returns>
/// <exception cref="System.ArgumentNullException">Exception when element not found in file</exception>
/// <example>How to use it: <code>
/// public static IEnumerable Credentials
/// {
/// get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "credential"); }
/// }
/// </code></example>
public static IEnumerable<TestCaseData> ReadDataDriveFile(string folder, string testData)
{
var doc = XDocument.Load(folder);
if (!doc.Descendants(testData).Any())
{
throw new ArgumentNullException(string.Format(CultureInfo.CurrentCulture, "Exception while reading Data Driven file\n row '{0}' not found \n in file '{1}'", testData, folder));
}
return doc.Descendants(testData).Select(element => element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value)).Select(testParams => new TestCaseData(testParams));
}
/// <summary>
/// Get the name of test case from value of parameters.
/// </summary>
/// <param name="diffParam">The difference parameter.</param>
/// <param name="testParams">The test parameters.</param>
/// <param name="testCaseName">Name of the test case.</param>
/// <returns>Test case name</returns>
/// <exception cref="NullReferenceException">Exception when trying to set test case name</exception>
private static string TestCaseName(string[] diffParam, Dictionary<string, string> testParams, string testCaseName)
{
if (diffParam != null && diffParam.Any())
{
foreach (var p in diffParam)
{
string keyValue;
bool keyFlag = testParams.TryGetValue(p, out keyValue);
if (keyFlag)
{
if (!string.IsNullOrEmpty(keyValue))
{
testCaseName += "_" + Regex.Replace(keyValue, "[^0-9a-zA-Z]+", "_");
}
}
else
{
throw new DataDrivenReadException(p);
}
}
}
return testCaseName;
}
}
}
|
namespace HangmanGame.UnitTests.TestData
{
public class ServerResponses
{
public static string WordAssociationsJsonResponse = @"
{
'version': '1.0',
'code': 200,
'request': {
'text': [
'hobby'
],
'lang': 'en',
'type': 'stimulus',
'limit': 50,
'pos': 'noun',
'indent': 'yes'
},
'response': [
{
'text': 'hobby',
'items': [
{
'item': 'Gardening',
'weight': 100,
'pos': 'noun'
},
{
'item': 'Collecting',
'weight': 97,
'pos': 'noun'
},
{
'item': 'Cooking',
'weight': 80,
'pos': 'noun'
}
]
}
]
}
".Replace("'", "\"");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using JoveZhao.Framework;
namespace BPiaoBao.DomesticTicket.Platform.Plugin
{
//<platformSection>
// <platforms>
// <platform name="517" provider="PiaoBao.BTicket.Platform._517._517Platform,PiaoBao.BTicket.Platform">
// <areas defaultCity="ctu">
// <area city="ctu">
// <parameters>
// <parameter name="aa" value="aa" description="a的参数" />
// </parameters>
// </area>
// </areas>
// </platform>
// </platforms>
//</platformSection>
public class PlatformConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("platforms")]
public PlatformElementCollection Platforms
{
get { return (PlatformElementCollection)base["platforms"]; }
set { base["platforms"] = value; }
}
}
public class PlatFormElement : ConfigurationElement
{
[ConfigurationProperty("code")]
public string Code
{
get { return (string)base["code"]; }
set { base["code"] = value; }
}
[ConfigurationProperty("name")]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("showcount")]
public int ShowCount
{
get { return (int)base["showcount"]; }
set { base["showcount"] = value; }
}
[ConfigurationProperty("areas")]
public AreaElementCollection Areas
{
get { return (AreaElementCollection)base["areas"]; }
set { base["areas"] = value; }
}
[ConfigurationProperty("issueSpeed")]
public string IssueSpeed
{
get { return (string)base["issueSpeed"]; }
set { base["issueSpeed"] = value; }
}
[ConfigurationProperty("isClosed")]
public bool IsClosed
{
get { return (bool)base["isClosed"]; }
set { base["isClosed"] = value; }
}
[ConfigurationProperty("paidIsTest")]
public bool paidIsTest
{
get { return (bool)base["paidIsTest"]; }
set { base["paidIsTest"] = value; }
}
[ConfigurationProperty("b2bClose")]
public string b2bClose
{
get { return (string)base["b2bClose"]; }
set { base["b2bClose"] = value; }
}
[ConfigurationProperty("bspClose")]
public string bspClose
{
get { return (string)base["bspClose"]; }
set { base["bspClose"] = value; }
}
}
public class PlatformElementCollection : BaseElementCollection<PlatFormElement>
{
public PlatFormElement this[string name]
{
get
{
return this.OfType<PlatFormElement>().Where(p => string.Compare(p.Name, name, true) == 0).FirstOrDefault();
}
}
protected override object GetKey(PlatFormElement t)
{
return t.Name;
}
protected override string ItemName
{
get { return "platform"; }
}
}
public class ParameterElement : ConfigurationElement
{
[ConfigurationProperty("name")]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("value")]
public string Value
{
get { return (string)base["value"]; }
set { base["value"] = value; }
}
[ConfigurationProperty("description")]
public string Description
{
get { return (string)base["description"]; }
set { base["description"] = value; }
}
}
public class ParameterElementCollection : BaseElementCollection<ParameterElement>
{
protected override object GetKey(ParameterElement t)
{
return t.Name;
}
protected override string ItemName
{
get { return "parameter"; }
}
public ParameterElement this[string name]
{
get
{
return this.OfType<ParameterElement>().Where(p => p.Name == name).FirstOrDefault();
}
}
}
public class AreaElement : ConfigurationElement
{
[ConfigurationProperty("city")]
public string City
{
get { return (string)base["city"]; }
set { base["city"] = value; }
}
[ConfigurationProperty("parameters")]
public ParameterElementCollection Parameters
{
get { return (ParameterElementCollection)base["parameters"]; }
set { base["parameters"] = value; }
}
}
public class AreaElementCollection : BaseElementCollection<AreaElement>
{
[ConfigurationProperty("defaultCity")]
public string DefaultCity
{
get { return (string)base["defaultCity"]; }
set { base["defaultCity"] = value; }
}
protected override object GetKey(AreaElement t)
{
return t.City;
}
protected override string ItemName
{
get { return "area"; }
}
public ParameterElementCollection GetByArea(ref string area)
{
var areaCity = area;
var o = this.OfType<AreaElement>().Where(p => p.City == areaCity).FirstOrDefault();
if (o == null)
{
o = this.OfType<AreaElement>().Where(p => p.City == DefaultCity).FirstOrDefault();
area = DefaultCity;
}
if (o == null)
throw new NotFoundResourcesException(string.Format("没有找到区域为:{0}或默认区域{1}的接口配置项", area, DefaultCity));
return o.Parameters;
}
}
public class PlatformSection
{
public static PlatformConfigurationSection GetInstances()
{
return SectionManager.GetConfigurationSection<PlatformConfigurationSection>("platformSection");
}
public static void Save()
{
SectionManager.SaveConfigurationSection("platformSection");
}
}
} |
using LuaInterface;
using RO;
using SLua;
using System;
using UnityEngine;
public class Lua_RO_RolePartBodyMount : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
RolePartBodyMount o = new RolePartBodyMount();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_audioSource(IntPtr l)
{
int result;
try
{
RolePartBodyMount rolePartBodyMount = (RolePartBodyMount)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, rolePartBodyMount.audioSource);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_audioSource(IntPtr l)
{
int result;
try
{
RolePartBodyMount rolePartBodyMount = (RolePartBodyMount)LuaObject.checkSelf(l);
AudioSource audioSource;
LuaObject.checkType<AudioSource>(l, 2, out audioSource);
rolePartBodyMount.audioSource = audioSource;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_audioEffects(IntPtr l)
{
int result;
try
{
RolePartBodyMount rolePartBodyMount = (RolePartBodyMount)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, rolePartBodyMount.audioEffects);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_audioEffects(IntPtr l)
{
int result;
try
{
RolePartBodyMount rolePartBodyMount = (RolePartBodyMount)LuaObject.checkSelf(l);
string[] audioEffects;
LuaObject.checkArray<string>(l, 2, out audioEffects);
rolePartBodyMount.audioEffects = audioEffects;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.RolePartBodyMount");
LuaObject.addMember(l, "audioSource", new LuaCSFunction(Lua_RO_RolePartBodyMount.get_audioSource), new LuaCSFunction(Lua_RO_RolePartBodyMount.set_audioSource), true);
LuaObject.addMember(l, "audioEffects", new LuaCSFunction(Lua_RO_RolePartBodyMount.get_audioEffects), new LuaCSFunction(Lua_RO_RolePartBodyMount.set_audioEffects), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_RolePartBodyMount.constructor), typeof(RolePartBodyMount), typeof(RolePart));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RevisoHomework.model
{
public class Payment
{
public string PaymentID { get; set; }
public string CustomerID { get; set; }
public string ProjectID { get; set; }
public double Price { get; set; }
public DateTime PaymentDate{ get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManagerSoftware.CoreEngine
{
internal class Salesman : Employee
{
Stack<Archive> stack = new Stack<Archive>();
Archive[] array = new Archive[list.count];
public Salesman(string name, string email, string contact) : base(name,email,contact)
{
this.name = name;
this.email = email;
this.contact = contact;
}
//Save a estrutura de dados (recebe uma lista)
public SaveData(List<Archive> list)
{
foreach (Archive a in archives)
{
stack.Push(a);
}
}
//Reset da estrutura de dados
public ResetData()
{
stack.Clear();
}
//Get da Estrutura de dados
public GetData(List<Archive> list)
{
this.list = list;
}
//Ordena por id (ascendente) - Utilizar o BubbleSort
// É necessário converter os dados para um array, usar o BubbleSort e passá-los novamente (já ordenados) para uma lista
public SortData()
{
list.CopyTo(array);
SortAlgorithm.Bubblesort(array, array.Length);
return List<Archive> list.ToList(array);
}
//Método envio dos dados em forma de Lista
public SetData()
{
return Stack < Archive > newQueue.ToList();
}
}
} |
using OPAM.Interface;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using Windows.Storage;
using OPAM.Model;
using OPAM.Common;
namespace OPAM.Camera.Win.Implementations
{
public class FileHandler : IFileHandler
{
string targetFolderName;
public string TargetFolderName
{
get
{
return targetFolderName;
}
set
{
targetFolderName = value;
}
}
/// <summary>
/// Used to move a file from one location to other location
/// </summary>
/// <param name="fromPath">to pass </param>
/// <param name="destFileName"></param>
/// <returns></returns>
public async Task<bool> MoveFile(string fromPath, string destFileName, bool IsExternalFolder = false)
{
var sourceFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(fromPath);
var appFolder = GetAppFolder();
StorageFolder destinationFolder = null;
try
{
if (String.IsNullOrEmpty(targetFolderName))
{
destinationFolder = appFolder;
}
else if (!IsExternalFolder)
{
if (!String.IsNullOrEmpty(targetFolderName) && await appFolder.TryGetItemAsync(targetFolderName) == null)
{
destinationFolder = await appFolder.CreateFolderAsync(targetFolderName);
}
else if (!String.IsNullOrEmpty(targetFolderName) && await appFolder.TryGetItemAsync(targetFolderName) != null)
{
destinationFolder = await appFolder.GetFolderAsync(targetFolderName);
}
}
else if (!String.IsNullOrEmpty(targetFolderName) && IsExternalFolder)
{
// If we need to create folder for this user starts
/*
string targetFolderName1 = targetFolderName;
StorageFolder destinationFolder0 = await StorageFolder.GetFolderFromPathAsync(targetFolderName1);
if (await destinationFolder0.TryGetItemAsync(CommonClass.UserName)==null)
{
await destinationFolder0.CreateFolderAsync(CommonClass.UserName);
}
targetFolderName1 += "\\" + CommonClass.UserName;
destinationFolder = await StorageFolder.GetFolderFromPathAsync(targetFolderName1);
*/
//If we need to create folder for each user ends
destinationFolder = await StorageFolder.GetFolderFromPathAsync(targetFolderName);
}
await sourceFile.CopyAsync(destinationFolder, destFileName, NameCollisionOption.ReplaceExisting);
}
catch (Exception ex)
{
throw;
}
return true;
}
/// <summary>
/// Used to check whether the given file is exists in the specified folder or not
/// </summary>
/// <param name="fileName">To pass File name to check</param>
/// <returns>True/False value</returns>
public async Task<bool> CheckFileExists(string fileName)
{
//Read the local folder
StorageFolder targetFolder = GetAppFolder();
if (!String.IsNullOrEmpty(targetFolderName))
{
targetFolder = await GetTargetFolder(targetFolderName);
}
return (await targetFolder.TryGetItemAsync(fileName) != null);
}
/// <summary>
/// Used to check whether folder name is exists or not
/// </summary>
/// <param name="folderName">to pass the folder name to check</param>
/// <returns></returns>
public async Task<bool> CheckFolderExists(string folderName)
{
//Read the local folder
var appFolder = GetAppFolder();
IStorageItem stItem = await appFolder.TryGetItemAsync(folderName);
return (stItem != null);
}
public async Task<bool> CreateFolderIfNotExist(string folderName)
{
if (await CheckFolderExists(folderName) == true)
{
return true;
}
else
{
await CreateFolder(folderName);
return true;
}
}
/// <summary>
/// Used to delete the specified folder
/// </summary>
/// <param name="fileName">To pass folder name to delete</param>
/// <returns></returns>
public async Task<bool> DeleteFile(string fileName)
{
StorageFolder targetFolder = GetAppFolder();
if (!String.IsNullOrEmpty(targetFolderName))
{
targetFolder = await GetTargetFolder(targetFolderName);
}
if (await targetFolder.TryGetItemAsync(fileName) != null)
{
var fileTobeDeleted = await targetFolder.GetFileAsync(fileName);
await fileTobeDeleted.DeleteAsync();
return true;
}
return false;
}
/// <summary>
/// Used to read file list from the specified path
/// </summary>
/// <param name="folderName"></param>
/// <returns></returns>
public async Task<List<string>> GetFileList(string folderName)
{
List<string> pathList = new List<string>();
StorageFolder targetFolder = await GetTargetFolder(folderName);
var fileList = await targetFolder.GetFilesAsync();
if (fileList != null && fileList.Count > 0)
{
foreach (StorageFile file in fileList)
{
pathList.Add(file.Path);
}
}
return pathList;
}
/// <summary>
/// Used to read file list from the specified path
/// </summary>
/// <param name="folderName"></param>
/// <returns></returns>
public async Task<string> GetFilePath(string fileName)
{
List<string> pathList = new List<string>();
StorageFolder targetFolder = await GetTargetFolder(Constants.PhotoFolderName);
var file = await targetFolder.GetFileAsync(fileName);
return file.Path;
}
public async Task<bool> CheckFilesExists(string folderName)
{
StorageFolder appFolder = GetAppFolder();
//StorageFolder targetFolder=null;
//IStorageItem stItem = await appFolder.TryGetItemAsync(folderName);
//if (stItem != null)
//{
if (await CheckFolderExists(folderName))
{
StorageFolder targetFolder = await GetTargetFolder(folderName);
var fileList = await targetFolder.GetFilesAsync();
if (fileList.Count == 0)
{
return true;
}
return false;
}
//}
return true;
}
/// <summary>
/// Used to read file list from the specified path
/// </summary>
/// <param name="folderName"></param>
/// <returns></returns>
public async Task<List<ImageItem>> GetFileListComposite(string folderName)
{
List<ImageItem> fileInfoList = new List<ImageItem>();
StorageFolder targetFolder = await GetTargetFolder(folderName);
var fileList = await targetFolder.GetFilesAsync();
ImageItem fileInfo = new ImageItem();
if (fileList != null && fileList.Count > 0)
{
foreach (StorageFile file in fileList)
{
fileInfo = new ImageItem()
{
DateCreated = file.DateCreated.DateTime.ToString(),
Path = file.Path,
Name = file.Name
};
fileInfoList.Add(fileInfo);
}
}
return fileInfoList;
}
public async Task<bool> CreateRawFile(string fileName, byte[] rawData)
{
Windows.Storage.StorageFolder appFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFolder targetFolder = await appFolder.GetFolderAsync(targetFolderName);
StorageFile targetFile = await targetFolder.GetFileAsync(fileName);
return false;
}
public Task<bool> CreateTextFile(string fileName, string content)
{
throw new NotImplementedException();
}
public Task<List<Stream>> GetFileListAsStreams(string folderName)
{
throw new NotImplementedException();
}
public Task<byte[]> GetRawDataFromFile(string fileName)
{
throw new NotImplementedException();
}
public Task<string> GetTextFromFile(string fileName)
{
throw new NotImplementedException();
}
public async Task<StorageFolder> CreateFolder(string TargetFolderName)
{
Windows.Storage.StorageFolder appFolder = GetAppFolder();
if (await appFolder.TryGetItemAsync(TargetFolderName) == null)
{
return await appFolder.CreateFolderAsync(TargetFolderName);
}
else
{
return await appFolder.GetFolderAsync(TargetFolderName);
}
}
#region "Supporting Functions"
private StorageFolder GetAppFolder()
{
return Windows.Storage.ApplicationData.Current.LocalFolder;
}
private async Task<StorageFolder> GetTargetFolder(string targetFolder)
{
Windows.Storage.StorageFolder appFolder = GetAppFolder();
Windows.Storage.StorageFolder folder = await appFolder.GetFolderAsync(targetFolder);
return folder;
}
public async Task<bool> MoveFolder(string fromFolder, string destFolderName, bool IsExternalFolder = false)
{
int flag = 0;
try
{
StorageFolder targetFolder = await GetTargetFolder(fromFolder);
var fileList = await targetFolder.GetFilesAsync();
if (fileList != null && fileList.Count > 0)
{
foreach (StorageFile file in fileList)
{
//set the destination as target
targetFolderName = destFolderName;
if (await MoveFile(file.Path, file.Name, IsExternalFolder))
{
//set the deleting file folder
targetFolderName = fromFolder;
await DeleteFile(file.Name);
flag++;
}
}
}
else
return false;
if (flag == 0)
return false;
else
return true;
}
catch (Exception ex)
{
throw;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App1.Services
{
public interface IDownload
{
void DownloadFile();
long GetDownloadSize();
string GetFilename();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XPowerAPI.Models;
using XPowerAPI.Repository.Collections;
namespace XPowerAPI.Services
{
public interface IStatisticService
{
Task<IPagedList<IStatistic>> GetStatisticsForDeviceAsync(long deviceId, string sessionKey);
Task<IPagedList<IStatistic>> GetStatisticsForDeviceSummarizedAsync(long deviceId, string sessionKey);
Task<IPagedList<IStatistic>> GetStatisticsForDeviceAsync(long deviceId, DateTime since, string sessionKey);
Task<IDictionary<Device, IPagedList<IStatistic>>> GetStatisticsForGroupAsync(long groupId, string sessionKey);
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Windows.Controls;
using Hardcodet.Wpf.TaskbarNotification;
using KaVE.RS.Commons;
using KaVE.VS.Commons;
using KaVE.VS.FeedbackGenerator.Generators;
using KaVE.VS.FeedbackGenerator.Menu;
namespace KaVE.VS.FeedbackGenerator.UserControls.TrayNotification
{
public abstract class BalloonPopupBase : UserControl
{
protected void OpenUploadWizard()
{
Registry.GetComponent<IKaVECommandGenerator>().FireOpenEventManager();
ClosePopup();
var actionexec = Registry.GetComponent<ActionExecutor>();
actionexec.ExecuteActionGuarded<UploadWizardAction>();
}
protected void ClosePopup()
{
var taskbarIcon = TaskbarIcon.GetParentTaskbarIcon(this);
taskbarIcon.CloseBalloon();
}
}
} |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Dz10.Migrations
{
public partial class AddOneToManyAndMantToOne : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "AirplaneId",
table: "Tickets",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "PersonId",
table: "Tickets",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Tickets_AirplaneId",
table: "Tickets",
column: "AirplaneId");
migrationBuilder.CreateIndex(
name: "IX_Tickets_PersonId",
table: "Tickets",
column: "PersonId");
migrationBuilder.AddForeignKey(
name: "FK_Tickets_Airplanes_AirplaneId",
table: "Tickets",
column: "AirplaneId",
principalTable: "Airplanes",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Tickets_People_PersonId",
table: "Tickets",
column: "PersonId",
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Tickets_Airplanes_AirplaneId",
table: "Tickets");
migrationBuilder.DropForeignKey(
name: "FK_Tickets_People_PersonId",
table: "Tickets");
migrationBuilder.DropIndex(
name: "IX_Tickets_AirplaneId",
table: "Tickets");
migrationBuilder.DropIndex(
name: "IX_Tickets_PersonId",
table: "Tickets");
migrationBuilder.DropColumn(
name: "AirplaneId",
table: "Tickets");
migrationBuilder.DropColumn(
name: "PersonId",
table: "Tickets");
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
namespace _2048.Model
{
public class CellItem : INotifyPropertyChanged
{
private Dictionary<int, Brush> colorDict = new Dictionary<int, Brush>()
{
{ 0, Brushes.LemonChiffon},
{ 1, Brushes.Wheat },
{ 2, Brushes.SandyBrown },
{ 3, Brushes.Gold },
{ 4, Brushes.Goldenrod },
{ 5, Brushes.Orange},
{ 6, Brushes.DarkOrange },
{ 7, Brushes.LightCoral },
{ 8, Brushes.IndianRed },
{ 9, Brushes.Salmon},
{ 10, Brushes.Coral},
{ 11, Brushes.Tomato},
{ 12, Brushes.Orange },
{ 13, Brushes.Red },
{ 14, Brushes.Crimson },
{ 15, Brushes.Firebrick },
{ 16, Brushes.DarkRed },
{ 17, Brushes.Sienna },
{ 18, Brushes.Brown },
{ 19, Brushes.Black }
};
[JsonRequired]
[JsonProperty("val")]
private int value;
[JsonIgnore]
public int Value
{
get { return Convert.ToInt32(Math.Pow(2, value)); }
private set
{
this.value = value;
OnPropertyChanged("Value");
}
}
[JsonIgnore]
public Brush BackColor
{
get { return colorDict[value]; }
}
[JsonProperty("x")]
public int Xcoord { get; private set; }
[JsonProperty("y")]
public int Ycoord { get; private set; }
[JsonIgnore]
public bool IsEmpty
{
get { return value == 0; }
}
public CellItem(int x, int y)
{
Xcoord = x;
Ycoord = y;
}
[JsonConstructor]
public CellItem(int val, int x, int y)
{
this.Value = val;
this.Xcoord = x;
this.Ycoord = y;
}
public void Plus()
{
value++;
}
public void Merge(CellItem[] items, Action moveAction, Action<int> counterAction, Action<string> messageAction)
{
if (this.IsEmpty) return;
CellItem tempItem = null;
for (int i = 0; i < items.Length; i++)
{
if (items[i].IsEmpty)
{
tempItem = items[i];
continue;
}
else
{
if (items[i].value == this.value)
{
items[i].Plus();
this.Value = 0;
counterAction(items[i].Value);
moveAction();
return;
}
break;
}
}
if (tempItem != null)
{
tempItem.Value = this.value;
this.Value = 0;
moveAction();
}
}
internal void SetRandomValue()
{
Thread.Sleep(100);
var random = new Random();
int[] arr = new int[] { 1, 2 };
value = arr[random.Next(arr.Length)];
}
public override string ToString()
{
if (IsEmpty) return string.Empty;
else return Value.ToString();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
|
using RestSharp;
namespace TrafficControl.DAL.RestSharp
{
/// <summary>
/// Interface
/// </summary>
public interface ITCDataConnection
{
string ApiDirectory { get; set; }
IRestResponse TCAPIconnection(Method b, string c);
IRestResponse TCAPIconnection(string ApiSubDirectory, Method b, object c);
IRestResponse TCAPIconnection(string ApiSubDirectory, Method b, int c = 0);
IRestResponse TCAPIconnection(Method b, long c = 0, object d = null);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace Assignent1_PrivateSchoolStructure
{
class Program
{
static void Main(string[] args)
{
CultureInfo myCI = new CultureInfo("el-GR");
var random = new Random();
var school = new School();
Console.WriteLine("===== Welcome to school management portal =====\n");
Console.WriteLine("Note1: A course assignment has not oral/total mark and cannot be created without passing a valid course.");
Console.WriteLine("Note2: Each student(personal) assignment inherits from the corresponding course assignment and has oral and total mark.");
Console.WriteLine("Note3: When a new assigment is added to a course, the system will automatically create personal assigments for all students assigned to that course.");
Console.WriteLine("Note4: When a new student is added to a course, the system will create his personal assignments based on all assignments the course has.");
Console.WriteLine("Note5: Assignment title will be automatically set based on the number of assignments a course has. E.g. the title of the first assignment of a course will be set to \"Assignment1\", the title of the second assignment of the same course will be set to \"Assignment2\" etc.\n");
string mainMenuSelection = String.Empty;
while (mainMenuSelection.ToLower() != "q")
{
Console.WriteLine("Enter the number that corresponds to the desired action or type \"q\" to quit.");
Console.WriteLine("(1) Course creation menu");
Console.WriteLine("(2) Student creation menu");
Console.WriteLine("(3) Trainer creation menu");
Console.WriteLine("(4) Defining relationships between courses/students/trainers menu");
Console.WriteLine("(5) Course assignments creation menu");
Console.WriteLine("(6) Reports menu");
Console.Write("Select action: ");
mainMenuSelection = Console.ReadLine();
Console.WriteLine();
switch (mainMenuSelection)
{
case ("1"):
String subMenu1Selection = String.Empty;
while (subMenu1Selection.ToLower() != "b")
{
Console.WriteLine("===== Course Creation Menu =====");
Console.WriteLine("(1) Create manually a course");
Console.WriteLine("(2) Create a number of random courses");
Console.WriteLine("Type 'b' to return to main menu");
Console.Write("Select action: ");
subMenu1Selection = Console.ReadLine();
Console.WriteLine();
switch (subMenu1Selection)
{
case ("1"):
Console.WriteLine("Enter course Title, Stream, Type, Start Date(year,month,day) separated by komma.");
Console.WriteLine("Course End Date will be automatically set based on Type(Full time => 3 months, Part time => 6 months)");
Console.Write("Course info: ");
try
{
school.CreateCourseFromUserInput(Console.ReadLine(), random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
case ("2"):
Console.Write("Enter the number of courses to create (max 200): ");
try
{
int numberOfCoursesToCreate = Int32.Parse(Console.ReadLine());
school.AddRandomCourses(SyntheticData.CourseTitles, numberOfCoursesToCreate, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
case ("b"):
Console.WriteLine();
break;
default:
Console.WriteLine("Selection is not recognized.");
break;
}
}
break;
case ("2"):
String subMenu2Selection = String.Empty;
while (subMenu2Selection.ToLower() != "b")
{
Console.WriteLine("===== Student Creation menu =====");
Console.WriteLine("(1) Create manually a student");
Console.WriteLine("(2) Create a number of random students (max: 200)");
Console.WriteLine("Type 'b' to return to main menu");
Console.Write("Selection: ");
subMenu2Selection = Console.ReadLine();
Console.WriteLine();
switch (subMenu2Selection)
{
case ("1"):
Console.Write("Enter student's First Name, Last Name, Date of Birth(year,month,day) separated by komma.\nStudent info: ");
try
{
school.CreateStudentFromUserInput(Console.ReadLine(), random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
case ("2"):
Console.Write("Enter the number of students to create (max 200): ");
try
{
int numberOfStudentsToCreate = Int32.Parse(Console.ReadLine());
school.AddRandomStudents(SyntheticData.FirstNames, SyntheticData.LastNames, numberOfStudentsToCreate, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
case ("b"):
Console.WriteLine();
break;
default:
Console.WriteLine("Selection is not recognized.");
break;
}
}
break;
case ("3"):
String subMenu3Selection = String.Empty;
while (subMenu3Selection.ToLower() != "b")
{
Console.WriteLine("===== Trainer Creation menu =====");
Console.WriteLine("(1) Create manually a trainer");
Console.WriteLine("(2) Create a number of random trainers (max: 200)");
Console.WriteLine("Type 'b' to return to main menu");
Console.Write("Selection: ");
subMenu3Selection = Console.ReadLine();
Console.WriteLine();
switch (subMenu3Selection)
{
case ("1"):
Console.Write("Enter trainer's First Name, Last Name, Subject\nTrainer info: ");
try
{
school.CreateTrainerFromUserInput(Console.ReadLine(), random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
case ("2"):
Console.Write("Enter the number of trainers to create (max 200): ");
try
{
int numberOfTrainersToCreate = Int32.Parse(Console.ReadLine());
school.AddRandomTrainers(SyntheticData.FirstNames, SyntheticData.LastNames, SyntheticData.TrainerSubjects, numberOfTrainersToCreate, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
case ("b"):
Console.WriteLine();
break;
default:
Console.WriteLine("Selection is not recognized.");
break;
}
}
break;
case ("4"):
String subMenu4Selection = String.Empty;
while (subMenu4Selection.ToLower() != "b")
{
Console.WriteLine("===== Defining relationships between courses/students/trainers menu =====");
Console.WriteLine("(1) Assign manually a student to a course");
Console.WriteLine("(2) Assign random number of students to a course");
Console.WriteLine("(3) Assign random number of students to a random course");
Console.WriteLine("(4) Assign random number of students to each course.");
Console.WriteLine("(5) Assign manually a trainer to a course");
Console.WriteLine("(6) Assign random number of trainers to a course");
Console.WriteLine("(7) Assign random number of trainers to a random course");
Console.WriteLine("(8) Assign random number of trainers to each course");
Console.WriteLine("Type 'b' to return to main menu");
Console.Write("Select action: ");
subMenu4Selection = Console.ReadLine();
Console.WriteLine();
switch (subMenu4Selection)
{
case ("1"):
{
try
{
school.PrintAllStudentsLite();
Console.WriteLine();
Console.Write("Enter student id: ");
var studentId = Int32.Parse(Console.ReadLine());
Console.WriteLine();
school.PrintAllCourses();
Console.WriteLine();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
school.AssignStudentToACourse(studentId, courseId);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("2"):
{
try
{
school.PrintAllCourses();
Console.WriteLine();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
school.AssignRandomNumberOfStudentsToACourse(courseId, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("3"):
{
try
{
school.AssignRandomNumberOfStudentsToARandomCourse(random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("4"):
{
try
{
school.RandomlyAssignStudentsToAllCourses(random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("5"):
{
try
{
school.PrintAllTrainers();
Console.WriteLine();
Console.Write("Enter trainer id: ");
var trainerId = Int32.Parse(Console.ReadLine());
Console.WriteLine();
school.PrintAllCourses();
Console.WriteLine();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
school.AssignTrainerToCourse(trainerId, courseId);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("6"):
{
try
{
school.PrintAllCourses();
Console.WriteLine();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
school.AssignRandomNumberOfTrainersToACourse(courseId, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("7"):
{
try
{
school.AssignRandomNumberOfTrainersToARandomCourse(random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("8"):
{
try
{
school.RandomlyAssignTrainersToAllCourses(random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("b"):
Console.WriteLine();
break;
default:
Console.WriteLine("Selection is not recognized.");
break;
}
}
break;
case ("5"):
String subMenu5Selection = String.Empty;
while (subMenu5Selection.ToLower() != "b")
{
Console.WriteLine("===== Course assignments creation menu =====");
Console.WriteLine("(1) Create manually an assignment for a course");
Console.WriteLine("(2) Create a number of random assignments for a course");
Console.WriteLine("(3) Create random number(max 5) of assignments for all courses");
Console.WriteLine("(4) Set total marks for all student assignments of a course to random values");
Console.WriteLine("Type 'b' to return to main menu");
Console.Write("Select action: ");
subMenu5Selection = Console.ReadLine();
Console.WriteLine();
switch (subMenu5Selection)
{
case ("1"):
{
try
{
if (school.Courses.Count != 0)
school.PrintAllCourses();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter assigments's Description, Submission DateAndTime(yyyy,MM,dd hh:mm) separated by komma.");
Console.Write("Assignment info: ");
var assignmentInfo = Console.ReadLine();
school.CreateAssignmentFromUserInput(assignmentInfo, courseId);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("2"):
{
try
{
if (school.Courses.Count != 0)
school.PrintAllCourses();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
Console.Write("Enter number of assignments to create: ");
var numberOfAssignments = Int32.Parse(Console.ReadLine());
school.AddRandomAssignmentsToACourse(courseId, numberOfAssignments, SyntheticData.AssignmentDescriptions, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("3"):
{
try
{
school.AddRandomNumberOfAssignmetsToAllCourses(5, SyntheticData.AssignmentDescriptions, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("4"):
{
try
{
if (school.Courses.Count != 0)
school.PrintAllCourses();
Console.Write("Enter course id: ");
var courseId = Int32.Parse(Console.ReadLine());
school.SetRandomMarkToAllStudentsAssignmetsOfACourse(courseId, random);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("b"):
Console.WriteLine();
break;
default:
Console.WriteLine("Selection is not recognized.");
break;
}
}
break;
case ("6"):
String subMenu6Selection = String.Empty;
while (subMenu6Selection.ToLower() != "b")
{
Console.WriteLine("===== Reports menu =====");
Console.WriteLine("(1) Print list of all courses");
Console.WriteLine("(2) Print list of all students");
Console.WriteLine("(3) Print list of all trainers");
Console.WriteLine("(4) Print students per course");
Console.WriteLine("(5) Print course assignments per course");
Console.WriteLine("(6) Print student assignments per course");
Console.WriteLine("(7) Print personal assignments per student");
Console.WriteLine("(8) Print trainers per course");
Console.WriteLine("(9) Print students that belong to more than one courses");
Console.WriteLine("(10) Print students that need to submit one or more assignments on a given date");
Console.WriteLine("Type 'b' to return to main menu");
Console.Write("Select action: ");
subMenu6Selection = Console.ReadLine();
Console.WriteLine();
switch (subMenu6Selection)
{
case ("1"):
{
try
{
school.PrintAllCourses();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("2"):
{
try
{
school.PrintAllStudents();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("3"):
{
try
{
school.PrintAllTrainers();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("4"):
{
try
{
school.PrintStudentsForAllCourses();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("5"):
{
try
{
school.PrintAssignmentsForAllCourses();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("6"):
{
try
{
school.PrintAllStudentAssignmentsForAllCourses();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("7"):
{
try
{
school.PrintAllAssignmentsPerStudent();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("8"):
{
try
{
school.PrintTrainersForAllCourses();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("9"):
{
try
{
school.PrintStudentsThatBelongToMoreThanOneCourse();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("10"):
{
try
{
Console.Write("Enter date: ");
DateTime date = DateTime.Parse(Console.ReadLine());
school.PrintStudentsThatNeedToSubmitAssigmentsInTheSpecifiedWeek(date, myCI);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
break;
}
case ("b"):
break;
default:
Console.WriteLine("Selection is not recognized.");
break;
}
}
break;
case ("q"):
Console.WriteLine("Goodbye");
break;
default:
Console.WriteLine("Unrecognized selection\n");
break;
}
}
}
}
}
|
namespace Plus.Communication.Packets.Outgoing.Inventory.Purse
{
internal class HabboActivityPointNotificationComposer : MessageComposer
{
public int Balance { get; }
public int Notify { get; }
public int Type { get; }
public HabboActivityPointNotificationComposer(int balance, int notify, int type = 0)
: base(ServerPacketHeader.HabboActivityPointNotificationMessageComposer)
{
Balance = balance;
Notify = notify;
Type = type;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(Balance);
packet.WriteInteger(Notify);
packet.WriteInteger(Type);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace TimPhongTro.Models
{
[Table("NHANXET")]
public partial class NHANXET
{
[Key]
public int MaNhanXet { get; set; }
public int? MaPhong { get; set; }
public int? MaKH { get; set; }
[StringLength(300)]
public string NoiDung { get; set; }
public virtual NGUOIDUNG NGUOIDUNG { get; set; }
public virtual PHONGTRO PHONGTRO { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreSystem : MonoBehaviour
{
#region Variables
public Text scoreTextObject;
public Text highScoreTextObject;
int currentScore;
#endregion
private void Start()
{
// Sets highScoreTextObject.text to value stored in PlayerPrefs for key "HighScore" with a default value of 0 if nothing currently exsits.
highScoreTextObject.text = "High Score: " + PlayerPrefs.GetInt("HighScore", 0).ToString();
// Initializes score at 0 to start game.
currentScore = 0;
scoreTextObject.text = "Score: " + currentScore.ToString();
}
// Adds whatever the value of additionalScore is to the currentScore
// Sets highScore value when currentScore exceeds previous highScore value
public void UpdateScore(int additionalScore)
{
currentScore += additionalScore;
Debug.Log("Player's score has increased by " + additionalScore + ". The total is now: " + currentScore);
scoreTextObject.text = "Score: " + currentScore.ToString();
if (currentScore > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", currentScore);
highScoreTextObject.text = "High Score: " + currentScore.ToString();
}
}
// Removes current highScore value key
public void ResetHighScore()
{
PlayerPrefs.DeleteKey("HighScore");
highScoreTextObject.text = "High Score: " + PlayerPrefs.GetInt("HighScore", 0).ToString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.