text stringlengths 13 6.01M |
|---|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nomad.Core;
using Vortex.Network;
using Vortex.Activation.Kernels;
using Vortex.Cost.Kernels.Categorical;
using Vortex.Cost.Kernels.Legacy;
using Vortex.Initializer.Kernels;
using Vortex.Optimizer.Kernels;
using Vortex.Layer.Kernels;
using Vortex.Metric.Kernels.Categorical;
using Vortex.Pooler.Kernels;
namespace VortexTests
{
[TestClass]
public class Network
{
[TestMethod]
[ExpectedException(typeof(InvalidOperationException), "Network is Locked.")]
public void NetworkLockedExceptionInit()
{
var net = new Sequential(new QuadraticCost(), new NesterovMomentum(0.03));
net.CreateLayer(new Dense(3, new Tanh()));
net.CreateLayer(new Output(1, new Tanh()));
net.InitNetwork();
net.InitNetwork();
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException), "Network is Locked.")]
public void NetworkLockedExceptionLayer()
{
var net = new Sequential(new QuadraticCost(), new NesterovMomentum(0.03));
net.CreateLayer(new Dense(3, new Tanh()));
net.CreateLayer(new Output(1, new Tanh()));
net.InitNetwork();
net.CreateLayer(new Dense(3, new Tanh()));
}
[TestMethod]
public void SequentialXor()
{
var net = new Sequential(new QuadraticCost(), new NesterovMomentum(0.03));
net.CreateLayer(new Dense(3, new Tanh()));
net.CreateLayer(new Dense(3, new Tanh(), null, new HeUniform()));
net.CreateLayer(new Dense(3, new Tanh()));
net.CreateLayer(new Output(1, new Tanh()));
net.InitNetwork();
_ = net.Y;
var inputs = new List<Matrix>();
var outputs = new List<Matrix>();
// 0 0 0 => 0
inputs.Add(new Matrix(new[,] { { 0.0 }, { 0.0 }, { 0.0 } }));
outputs.Add(new Matrix(new[,] { { 0.0 } }));
// 0 0 1 => 1
inputs.Add(new Matrix(new[,] { { 0.0 }, { 0.0 }, { 1.0 } }));
outputs.Add(new Matrix(new[,] { { 1.0 } }));
// 0 1 0 => 1
inputs.Add(new Matrix(new[,] { { 0.0 }, { 1.0 }, { 0.0 } }));
outputs.Add(new Matrix(new[,] { { 1.0 } }));
// 0 1 1 => 0
inputs.Add(new Matrix(new[,] { { 0.0 }, { 1.0 }, { 1.0 } }));
outputs.Add(new Matrix(new[,] { { 1.0 } }));
// 1 0 0 => 1
inputs.Add(new Matrix(new[,] { { 1.0 }, { 0.0 }, { 0.0 } }));
outputs.Add(new Matrix(new[,] { { 1.0 } }));
// 1 0 1 => 0
inputs.Add(new Matrix(new[,] { { 1.0 }, { 0.0 }, { 1.0 } }));
outputs.Add(new Matrix(new[,] { { 0.0 } }));
// 1 1 0 => 0
inputs.Add(new Matrix(new[,] { { 1.0 }, { 1.0 }, { 0.0 } }));
outputs.Add(new Matrix(new[,] { { 0.0 } }));
// 1 1 1 => 1
inputs.Add(new Matrix(new[,] { { 1.0 }, { 1.0 }, { 1.0 } }));
outputs.Add(new Matrix(new[,] { { 1.0 } }));
for (var i = 0; i < 8; i++) net.Train(inputs[i % 8], outputs[i % 8]);
var correct = 0;
for (var i = 0; i < 10; i++)
{
correct += Math.Abs(net.Forward(inputs[0])[0, 0]) < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[1])[0, 0]) - 1 < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[2])[0, 0]) - 1 < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[3])[0, 0]) < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[4])[0, 0]) - 1 < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[5])[0, 0]) < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[6])[0, 0]) < 0.1 ? 1 : 0;
correct += Math.Abs(net.Forward(inputs[7])[0, 0]) - 1 < 0.1 ? 1 : 0;
}
var acc = correct / 80.0 * 100.0;
Trace.WriteLine(" Acc: " + acc);
Trace.WriteLine(" Metrics Accuracy: ");
Assert.IsTrue(acc > 80.0, "Network did not learn XOR");
}
[TestMethod]
public void DenseMnist()
{
// Load Train Data
var lines = File.ReadAllLines("..\\..\\..\\..\\..\\datasets\\mnist_train.csv").ToList();
var mnistLables = new List<Matrix>();
var mnistData = new List<Matrix>();
for (var j = 1; j < lines.Count; j++)
{
var t = lines[j];
var data = t.Split(',').ToList();
mnistLables.Add(new Matrix(10, 1).Fill(0));
mnistLables[j - 1][int.Parse(data[0]), 0] = 1.0;
var mnist = new Matrix(784, 1);
for (var i = 1; i < data.Count; i++)
{
mnist[i - 1, 0] = double.Parse(data[i]);
}
mnistData.Add(mnist);
}
// Load Test Data
var testlines = File.ReadAllLines("..\\..\\..\\..\\..\\datasets\\mnist_test.csv").ToList();
var mnistTestLables = new List<Matrix>();
var mnistTestData = new List<Matrix>();
for (var j = 1; j < testlines.Count; j++)
{
var t = testlines[j];
var data = t.Split(',').ToList();
mnistTestLables.Add(new Matrix(10, 1).Fill(0));
mnistTestLables[j - 1][int.Parse(data[0]), 0] = 1.0;
var mnist = new Matrix(784, 1);
for (var i = 1; i < data.Count; i++)
{
mnist[i - 1, 0] = double.Parse(data[i]);
}
mnistTestData.Add(mnist);
}
// Create Network
var net = new Sequential(new CategoricalCrossEntropy(), new Adam(0.3), null, 128);
net.CreateLayer(new Dense(784, new Relu()));
net.CreateLayer(new Dense(128, new Relu()));
net.CreateLayer(new Output(10, new Softmax()));
net.InitNetwork();
// Train Network
for (var i = 0; i < mnistData.Count / 100; i++)
{
net.Train(mnistData[i % mnistData.Count], mnistLables[i % mnistData.Count]);
}
// Test Network
for (var i = 0; i < mnistTestData.Count / 100; i++)
{
var mat = net.Forward(mnistTestData[i % mnistTestData.Count]);
var matx = mnistTestLables[i % mnistTestData.Count];
}
Trace.WriteLine(" Metrics Accuracy: ");
//Assert.IsTrue(acc > 80.0, "Network did not learn MNIST");
}
[TestMethod]
public void ConvolutionalMnist()
{
// Load Data
var lines = File.ReadAllLines("..\\..\\..\\..\\..\\datasets\\mnist_train.csv").ToList();
var mnistLables = new List<Matrix>();
var mnistData = new List<Matrix>();
for (var j = 1; j < lines.Count; j++)
{
var t = lines[j];
var data = t.Split(',').ToList();
mnistLables.Add(new Matrix(1, 1).Fill(int.Parse(data[0])));
var mnist = new Matrix(784, 1);
for (var i = 1; i < data.Count; i++)
{
mnist[i - 1, 0] = double.Parse(data[i]);
}
mnistData.Add(mnist);
}
// Create Network
var net = new Sequential(new QuadraticCost(), new NesterovMomentum(0.03));
net.CreateLayer(new Convolutional(784, new Average(), new Tanh()));
net.CreateLayer(new Convolutional(100, new Average(), new Tanh()));
net.CreateLayer(new Dense(100, new Tanh()));
net.CreateLayer(new Output(10, new Softmax()));
net.InitNetwork();
// Train Network
for (var i = 0; i < 800; i++)
{
net.Train(mnistData[i % mnistData.Count], mnistLables[i % mnistData.Count]);
}
// Write Acc Result
// Trace.WriteLine(" Metrics Accuracy: " + acc);
// Assert.IsTrue(acc > 80.0, "Network did not learn MNIST");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SwordandScale
{
class Square
{
public Square last; //last square in path
public int x;
public int y; //current point
public int fs; //distance from start to current
public int tf; //distance from current to finish (Manhattan)
public int score;
public Square(int x, int y, int fs, int tf, Square last)
{
this.x = x;
this.y = y;
this.fs = fs;
this.tf = tf;
this.score = tf + fs;
this.last = last;
}
public int getScore()
{
return this.score;
}
public bool equals(Square n)
{
return this.x == n.x && this.y == n.y;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DAL.Models;
using DAL.Models.DTO;
namespace ApiDashboard
{
public class MappingProfiles : Profile
{
public MappingProfiles()
{
CreateMap<Product, ProductDTO>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Thunder : MonoBehaviour {
public AudioSource thunder;
// starting in 60 seconds a sound will be played every 60 seconds
void Start () {
InvokeRepeating("playAudio", 3.0f,60.0f);
}
void playAudio () {
thunder.Play();
}
}
|
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
using RimlightArchive.Defs;
namespace RimlightArchive.Apparel
{
/// <summary>
/// Adds the ability for apparel to hold Stormlight.
/// </summary>
[StaticConstructorOnStartup]
public class InfusedApparel : RimWorld.Apparel
{
private readonly float ApparelScorePerStormlightMax = 0.25f;
public int stormlight = 0;
public override string GetInspectString() => $"{base.GetInspectString()}{System.Environment.NewLine}{this.stormlight} / {this.StormlightMax} Stormlight";
public int StormlightMax => (int)this.GetStatValue(RadiantDefOf.StormlightMax, true);
public float StormlightPercentage => this.stormlight / (float)this.StormlightMax;
public float StormlightGainPerTick => this.GetStatValue(RadiantDefOf.StormlightRechargeRate, true) / 60f;
public override IEnumerable<Gizmo> GetWornGizmos()
{
if (Find.Selector.SingleSelectedThing == base.Wearer && !base.Wearer.Dead)
{
yield return new GizmoStormlightApparelStatus
{
apparel = this
};
}
}
public override float GetSpecialApparelScoreOffset()
{
return this.StormlightMax * this.ApparelScorePerStormlightMax;
}
public override void Tick()
{
base.Tick();
if (!Utils.CanBeInfused(this) && !Utils.CanBeInfused(this.Wearer) && this.stormlight < this.StormlightMax)
return;
// recharge if outside in a highstorm
this.stormlight = System.Math.Min(this.stormlight + (int)Mathf.Max(this.StormlightGainPerTick, 1f), this.StormlightMax);
}
public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref this.stormlight, "stormlight", 0, false);
}
}
}
|
using System;
using System.Data;
using NUnit.Framework;
namespace CS.Sandbox.Db
{
[TestFixture]
public class SQLiteFileTest
{
[Test]
public void RunTests()
{
var connectionString = "URI=file:DatabaseTest.db";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
CreateDatabase(connection);
InsertData(connection);
QueryData(connection);
}
}
private void CreateDatabase(IDbConnection connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = @"
DROP TABLE IF EXISTS employee;
CREATE TABLE employee (
firstname varchar(32),
lastname varchar(32)
)";
command.ExecuteNonQuery();
}
}
private void InsertData(IDbConnection connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = @"
INSERT INTO
employee
VALUES
('Lars', 'Tackmann')";
command.ExecuteNonQuery();
}
}
private void QueryData(IDbConnection connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT
firstname, lastname
FROM
employee
";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string FirstName = reader.GetString(0);
string LastName = reader.GetString(1);
Console.WriteLine("Name is: " + FirstName + " " + LastName);
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Desideals.Models;
namespace Desideals.Pages
{
public class ReportPage
{
public List<Report> Reports { get; set; }
public Newsletter Newsletter { get; set; }
}
public class ReportDetailPage
{
public DateTime ReportDate { get; set; }
public List<ReportDetail> ReportDetails { get; set; }
public Newsletter Newsletter { get; set; }
}
} |
using System;
using System.Text.RegularExpressions;
namespace Password
{
class Program
{
static void Main(string[] args)
{
var regex = @"^(.+)>([\d]{3})\|([a-z]{3})\|([A-Z]{3})\|([^<>]{3})<\1$";
var numberOfInputs = int.Parse(Console.ReadLine());
for (int i = 0; i < numberOfInputs; i++)
{
var password = Console.ReadLine();
if (Regex.IsMatch(password,regex))
{
var groups = Regex.Match(password, regex).Groups;
Console.WriteLine($"Password: {groups[2].ToString() + groups[3].ToString() + groups[4].ToString() + groups[5].ToString()}");
}
else
{
Console.WriteLine("Try another password!");
}
}
}
}
}
|
//using eMAM.Service.Contracts;
//using Google.Apis.Auth.OAuth2;
//using Google.Apis.Auth.OAuth2.Flows;
//using Google.Apis.Auth.OAuth2.Responses;
//using Google.Apis.Gmail.v1;
//using Google.Apis.Services;
//using Microsoft.Extensions.DependencyInjection;
//namespace eMAM.UI.Utills
//{
// public static class IServiceCollectionExtensions
// {
// public static IServiceCollection AddGmailService(this IServiceCollection services)
// {
// services.AddScoped<GmailService>(provider =>
// {
// using (var scope = provider.CreateScope())
// {
// var userData = scope.ServiceProvider.GetRequiredService<IGmailUserDataService>().Get();
// var authorizationCodeFlowInitializer = new AuthorizationCodeFlow.Initializer(
// "https://accounts.google.com/o/oauth2/v2/auth", // валиден
// "https://oauth2.googleapis.com/token" // валиден
// );
// authorizationCodeFlowInitializer.ClientSecrets = new ClientSecrets
// {
// ClientId = "667407283017-hjbtv4a5sjr3garaprkidqo36qs4u7o3.apps.googleusercontent.com", // валиден
// ClientSecret = "cH5tErPh_uqDZDmp1F1aDNIs" // валиден
// };
// var authcodeflow = new AuthorizationCodeFlow(authorizationCodeFlowInitializer);
// var tokenResponse = new TokenResponse()
// {
// AccessToken = userData.AccessToken, // не го бърка
// RefreshToken = userData.RefreshToken // трябва да е валиден
// };
// return new GmailService(new BaseClientService.Initializer()
// {
// HttpClientInitializer = new UserCredential(authcodeflow, "me", tokenResponse)
// });
// }
// });
// return services;
// }
// }
//}
|
using System;
using System.Linq;
namespace Codility
{
public class EquivalenceIndex
{
public static int Find(int[] numbers)
{
if (numbers.Length == 0)
return -1;
var asLong = numbers.Select(Convert.ToInt64).ToArray();
long sumBefore = 0;
long sumAfter = asLong.Skip(1).Sum();
if (sumAfter == sumBefore) return 0;
for (var i = 1; i < asLong.Length; i++)
{
sumBefore += asLong[i - 1];
if (i == asLong.Length - 1)
{
sumAfter = 0;
}
else
{
sumAfter -= asLong[i];
}
if (sumAfter == sumBefore)
return i;
}
return -1;
}
}
}
|
using Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Data.Desktop;
using UI.Desktop.Preferences;
using System.Text.RegularExpressions;
namespace UI.Desktop.Checkout
{
/// <summary>
/// Interaction logic for CheckoutWindow.xaml
/// </summary>
public partial class CheckoutWindow : Window
{
private CheckoutStep1 step1;
private CheckoutStep2 step2;
private CheckoutStep3 step3;
private CheckoutStep4 step4;
private CompletedCheckoutPage step5;
private LogInPage logIn;
private ShoppingCart shoppingCart;
private DataHandler dataHandler;
public CheckoutWindow(DataHandler data)
{
dataHandler = data;
shoppingCart = data.GetCart();
InitializeComponent();
wizardSteps.Background = (Brush)App.Current.Resources["DarkComplement"];
initWizSteps(wStep1, "Konto", "UserImage");
initWizSteps(wStep2, "Frakt", "ShipmentImage");
initWizSteps(wStep3, "Betalning", "PaymentImage");
initWizSteps(wStep4, "Bekräfta", "ConfirmImage");
step1 = new CheckoutStep1(data);
step1.NextStep += step1_NextStep;
step1.LogIn += step1_LogIn;
step2 = new CheckoutStep2(data);
step2.NextStep2 += step2_NextStep2;
step2.BackStep2 += step2_BackStep2;
step3 = new CheckoutStep3(data);
step3.NextStep3 += step3_NextStep3;
step3.BackStep3 += step3_BackStep3;
step4 = new CheckoutStep4();
step4.ExitCheckout += step4_ExitCheckout;
step4.BackStep4 += step4_BackStep4;
step4.DataContext = data.GetCart();
logIn = new LogInPage(data);
logIn.NextStep += logIn_NextStep;
logIn.BackStep += logIn_BackStep;
step5 = new CompletedCheckoutPage();
step5.ExitWizard += step5_ExitWizard;
step5.ShowReciept += step5_ShowReciept;
if (data.GetUser() != null)
{
PageGrid.Children.Add(step2);
logInUser.Content = data.GetUser().Email;
logInStatus.Content = "Inloggad som: ";
wStep2.StepActive = true;
}
else
{
PageGrid.Children.Add(step1);
logInStatus.Content = "Inte inloggad!";
wStep1.StepActive = true;
}
}
public static bool isTextAllowed(String s)
{
Regex regex = new Regex("[^0-9]+");
return regex.IsMatch(s);
}
void step5_ShowReciept(object sender, EventArgs e)
{
this.Close();
PreferencesWindow pref = new PreferencesWindow(dataHandler, PreferencesWindow.StartupView.Account);
pref.Owner = MainWindow.WindowContainer;
pref.ShowDialog();
}
void step5_ExitWizard(object sender, EventArgs e)
{
this.Close();
}
private void initWizSteps(WizardSteps wStep, String title, String img)
{
wStep.Title = title;
wStep.ImgSource = img;
wStep.StepActive = false;
}
void step1_LogIn(object sender, EventArgs e)
{
PageGrid.Children.Clear();
PageGrid.Children.Add(logIn);
}
void logIn_BackStep(object sender, EventArgs e)
{
PageGrid.Children.Clear();
PageGrid.Children.Add(step1);
}
void logIn_NextStep(object sender, EventArgs e)
{
ActivateStep2();
wStep2.StepActive = true;
wStep1.StepActive = false;
}
void step4_BackStep4(object sender, EventArgs e)
{
ActivateStep3();
wStep3.StepActive = true;
wStep4.StepActive = false;
}
void step3_NextStep3(object sender, EventArgs e)
{
ActivateStep4();
wStep4.StepActive = true;
wStep3.StepActive = false;
}
void step3_BackStep3(object sender, EventArgs e)
{
ActivateStep2();
wStep2.StepActive = true;
wStep3.StepActive = false;
}
void step4_ExitCheckout(object sender, EventArgs e)
{
PageGrid.Children.Clear();
PageGrid.Children.Add(step5);
wStep4.StepActive = false;
if (shoppingCart != null)
{
dataHandler.GetOrders().Insert(0, new Order(shoppingCart, DateTime.Now, 1337));
shoppingCart.Clear();
}
}
void step2_BackStep2(object sender, EventArgs e)
{
ActivateStep1();
wStep1.StepActive = true;
wStep2.StepActive = false;
}
void step2_NextStep2(object sender, EventArgs e)
{
ActivateStep3();
wStep3.StepActive = true;
wStep2.StepActive = false;
}
void step1_NextStep(object sender, EventArgs e)
{
ActivateStep2();
wStep2.StepActive = true;
wStep1.StepActive = false;
if (dataHandler.GetUser() != null)
{
logInUser.Content = dataHandler.GetUser().Email;
logInStatus.Content = "Inloggad som: ";
}
else
{
logInStatus.Content = "Inte inloggad!";
}
}
public void ActivateStep1()
{
PageGrid.Children.Clear();
PageGrid.Children.Add(step1 = new CheckoutStep1(dataHandler));
step1.NextStep += step1_NextStep;
step1.LogIn += step1_LogIn;
}
public void ActivateStep2()
{
PageGrid.Children.Clear();
PageGrid.Children.Add(step2);
if (dataHandler.GetUser() != null)
{
step2.EmailTextBox.Text = dataHandler.GetUser().ShippingAddress.Email;
}
}
private void ActivateStep3()
{
PageGrid.Children.Clear();
PageGrid.Children.Add(step3);
if (step2.PickupInStore.IsChecked == true)
{
step3.PayOnPickup.IsEnabled = true;
}
else
{
step3.PayOnPickup.IsEnabled = false;
}
step3.PayWithCard.IsChecked = true;
}
public void ActivateStep4()
{
PageGrid.Children.Clear();
PageGrid.Children.Add(step4);
step4.displayContent();
if (step3.PayOnPickup.IsChecked == true)
{
step4.chosenPaymentOption.Text = "Du betalar dina varor vid upphämtning.";
step4.chosenPaymentAnswer.Text = null;
}
else
{
step4.chosenPaymentOption.Text = "Du betalar med kort med nr: ";
step4.chosenPaymentAnswer.Text = step3.CardNumber1.Text + " " + step3.CardNumber2.Text + " " + step3.CardNumber3.Text + " " + step3.CardNumber4.Text;
}
if (step2.HomeDelivery.IsChecked == true)
{
step4.chosenDeliveryOption.Text = "Dina varor kommer levereras hem till: ";
step4.chosenDeliveryAnswer.Text = step2.AddressTextBox.Text;
}
else
{
ComboBoxItem ci = (ComboBoxItem)step2.StoreComboBox.SelectedItem;
string temp = ci.Content.ToString();
step4.chosenDeliveryOption.Text = "Dina varor kommer levereras till: ";
step4.chosenDeliveryAnswer.Text = temp;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Users.Mapeamentos;
using Welic.Dominio.Patterns.Pattern.Ef6;
namespace Welic.Dominio.Models.Uploads.Maps
{
public class UploadsMap : Entity
{
public Guid UploadId { get; set; }
public string Path { get; set; }
public string UserId { get; set; }
public AspNetUser User { get; set; }
}
}
|
using System;
namespace Atc.Math.Geometry
{
/// <summary>
/// The TriangleHelper module contains procedures used to preform math operations on a triangle.
/// </summary>
public static class TriangleHelper
{
/// <summary>
/// Determines whether [is sum of the angles A triangle] [the specified angle A].
/// </summary>
/// <param name="angleA">The angle A.</param>
/// <param name="angleB">The angle B.</param>
/// <param name="angleC">The angle C.</param>
/// <returns>
/// <c>true</c> if [is sum of the angles A triangle] [the specified angle A]; otherwise, <c>false</c>.
/// </returns>
public static bool IsSumOfTheAnglesATriangle(double? angleA, double? angleB, double? angleC)
{
if (angleA == null)
{
throw new ArgumentNullException(nameof(angleA));
}
if (angleB == null)
{
throw new ArgumentNullException(nameof(angleB));
}
if (angleC == null)
{
throw new ArgumentNullException(nameof(angleC));
}
return IsSumOfTheAnglesATriangle((double)angleA, (double)angleB, (double)angleC);
}
/// <summary>
/// Determines whether [is sum of the angles A triangle] [the specified angle A].
/// </summary>
/// <param name="angleA">The angle A.</param>
/// <param name="angleB">The angle B.</param>
/// <param name="angleC">The angle C.</param>
/// <returns>
/// <c>true</c> if [is sum of the angles A triangle] [the specified angle A]; otherwise, <c>false</c>.
/// </returns>
public static bool IsSumOfTheAnglesATriangle(double angleA, double angleB, double angleC)
{
return (angleA + angleB + angleC).IsEqual(180);
}
/// <summary>
/// Calculate the unspecified side (unspecified with NULL).
/// </summary>
/// <param name="sideA">The side A.</param>
/// <param name="sideB">The side B.</param>
/// <param name="sideC">The side C.</param>
public static double Pythagorean(double? sideA, double? sideB, double? sideC)
{
int i = Convert.ToInt32(sideA.HasValue) + Convert.ToInt32(sideB.HasValue) + Convert.ToInt32(sideC.HasValue);
if (i != 2)
{
throw new ArithmeticException("One and only one argument have to be null.");
}
if (sideA == null && sideB != null && sideC != null)
{
// Calc sideA
return System.Math.Sqrt(System.Math.Pow((double)sideC, 2) - System.Math.Pow((double)sideB, 2));
}
if (sideA != null && sideB == null && sideC != null)
{
// Calc sideB
return System.Math.Sqrt(System.Math.Pow((double)sideC, 2) - System.Math.Pow((double)sideA, 2));
}
if (sideA != null && sideB != null && sideC == null)
{
// Calc sideC
return System.Math.Sqrt(System.Math.Pow((double)sideA, 2) + System.Math.Pow((double)sideB, 2));
}
throw new ArithmeticException("Expected early return - Bad implementation.");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PieShop.Models;
using PieShop.ViewModels;
namespace PieShop.Controllers
{
public class PieController : Controller
{
private readonly IPieRepository _pieRepository;
private readonly ICategoryRepository _categoryRepository;
public PieController(IPieRepository pieRepository,ICategoryRepository categoryRepository)
{
_pieRepository = pieRepository;
_categoryRepository = categoryRepository;
}
//public ViewResult List()
//{
// PieListViewModel pieListViewModel = new PieListViewModel();
// pieListViewModel.Pies = _pieRepository.AllPies;
// pieListViewModel.CurrentCategory = "Chees cakes";
// return View(pieListViewModel);
//}
public ViewResult List(string category)
{
PieListViewModel pieListViewModel = new PieListViewModel();
if (category != null)
{
pieListViewModel.Pies = _pieRepository.AllPies.Where(p => p.Category.CategoryName == category);
pieListViewModel.CurrentCategory = category;
} else
{
pieListViewModel.Pies = _pieRepository.AllPies;
pieListViewModel.CurrentCategory = "All Pies";
}
return View(pieListViewModel);
}
public IActionResult Details(int id)
{
Pie pie = _pieRepository.GetPieById(id);
if (pie == null)
return NotFound();
return View(pie);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BinaryTree
{
class Node
{
public int label;
public Node left;
public Node right;
public Node(int data)
{
label = data;
left = null;
right = null;
}
public void AddNode(Node root)
{
if (root == null)
{
Console.WriteLine("Could not call 'AddNode' because root was null");
return;
}
else if (root.label == label)
{
Console.WriteLine("Duplicate values not allowed");
return;
}
else if (label < root.label)
{
//go left
if (root.left != null)
{
AddNode(root.left);
}
else
{
Console.WriteLine("Added " + label + " to the left of " + root.label);
root.left = this;
}
}
else if (label > root.label)
{
//go right
if (root.right != null)
{
AddNode(root.right);
}
else
{
Console.WriteLine("Added " + label + " to the right of " + root.label);
root.right = this;
}
}
}
}
} |
namespace Sentry;
public readonly partial struct MeasurementUnit
{
/// <summary>
/// An information size unit
/// </summary>
/// <seealso href="https://getsentry.github.io/relay/relay_metrics/enum.InformationUnit.html"/>
public enum Information
{
/// <summary>
/// Bit unit (1/8 of byte)
/// </summary>
/// <remarks>
/// Some computer systems may have a different number of bits per byte.
/// </remarks>
Bit,
/// <summary>
/// Byte unit
/// </summary>
Byte,
/// <summary>
/// Kilobyte unit (10^3 bytes)
/// </summary>
Kilobyte,
/// <summary>
/// Kibibyte unit (2^10 bytes)
/// </summary>
Kibibyte,
/// <summary>
/// Megabyte unit (10^6 bytes)
/// </summary>
Megabyte,
/// <summary>
/// Mebibyte unit (2^20 bytes)
/// </summary>
Mebibyte,
/// <summary>
/// Gigabyte unit (10^9 bytes)
/// </summary>
Gigabyte,
/// <summary>
/// Gibibyte unit (2^30 bytes)
/// </summary>
Gibibyte,
/// <summary>
/// Terabyte unit (10^12 bytes)
/// </summary>
Terabyte,
/// <summary>
/// Tebibyte unit (2^40 bytes)
/// </summary>
Tebibyte,
/// <summary>
/// Petabyte unit (10^15 bytes)
/// </summary>
Petabyte,
/// <summary>
/// Pebibyte unit (2^50 bytes)
/// </summary>
Pebibyte,
/// <summary>
/// Exabyte unit (10^18 bytes)
/// </summary>
Exabyte,
/// <summary>
/// Exbibyte unit (2^60 bytes)
/// </summary>
Exbibyte
}
/// <summary>
/// Implicitly casts a <see cref="MeasurementUnit.Information"/> to a <see cref="MeasurementUnit"/>.
/// </summary>
public static implicit operator MeasurementUnit(Information unit) => new(unit);
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NGeoNames;
using NGeoNames.Parsers;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NGeoNamesTests
{
internal class FileUtil
{
// Compares two data files using a GenericEntity to easily compare actual values without bothering with newline differences,
// comments etc. nor trying to "understand" what they mean
public static void EnsureFilesAreFunctionallyEqual(string src, string dst, int expectedfields, int skiplines, char[] fieldseparators, Encoding encoding, bool hascomments)
{
var parser_in = new GenericParser(expectedfields, skiplines, fieldseparators, encoding, hascomments);
var parser_out = new GenericParser(expectedfields, 0, fieldseparators, encoding, false);
var expected = new GeoFileReader().ReadRecords<GenericEntity>(src, FileType.Plain, parser_in).ToArray();
var actual = new GeoFileReader().ReadRecords<GenericEntity>(dst, FileType.Plain, parser_out).ToArray();
CollectionAssert.AreEqual(expected, actual, new GenericEntityComparer());
}
private class GenericParser : IParser<GenericEntity>
{
public bool HasComments { get; private set; }
public int SkipLines { get; private set; }
public int ExpectedNumberOfFields { get; private set; }
public Encoding Encoding { get; private set; }
public char[] FieldSeparators { get; private set; }
public GenericParser(int expectedfields, int skiplines, char[] fieldseparators, Encoding encoding, bool hascomments)
{
this.SkipLines = skiplines;
this.ExpectedNumberOfFields = expectedfields;
this.FieldSeparators = fieldseparators;
this.Encoding = encoding;
this.HasComments = hascomments;
}
public GenericEntity Parse(string[] fields)
{
Assert.AreEqual(this.ExpectedNumberOfFields, fields.Length);
return new GenericEntity { Data = fields };
}
}
private class GenericEntity
{
public string[] Data { get; set; }
}
private class GenericEntityComparer : IComparer<GenericEntity>, IComparer
{
public int Compare(GenericEntity x, GenericEntity y)
{
int r = x.Data.Length.CompareTo(y.Data.Length);
if (r != 0)
return r;
for (int i = 0; i < x.Data.Length && r == 0; i++)
r = x.Data[i].CompareTo(y.Data[i]);
return r;
}
public int Compare(object x, object y)
{
return this.Compare(x as GenericEntity, y as GenericEntity);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace iTrellis.TripCalculator.Models.Enums
{
public enum TransactionType
{
CREDIT = 0,
DEBIT = 1
}
} |
using System;
namespace AspNetCoreGettingStarted.Model
{
public class Tenant
{
public Guid TenantId { get; set; }
public string Name { get; set; }
}
}
|
using System.Collections.Generic;
using System.ComponentModel;
using TopJSRepos.Models;
using TopJSRepos.Services;
namespace TopJSRepos.ViewModels
{
public class RepositoriesViewModel : BaseViewModel
{
private readonly IRepositoryService repositoryService;
public RepositoriesViewModel(IRepositoryService repositoryService) {
this.repositoryService = repositoryService;
GetRepositories();
}
private IList<Repository> _Repositories;
public IList<Repository> Repositories {
get { return _Repositories; }
set { _Repositories = value; OnPropertyChanged(nameof(Repositories)); }
}
private async void GetRepositories()
{
Repositories = await repositoryService.GetItemsAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Stolons.Models
{
public abstract class User
{
[Key]
[Display(Name = "Identifiant")]
public int Id { get; set; }
[Display(Name = "Nom")]
[Required]
public string Name { get; set; }
[Display(Name = "Prénom")]
[Required]
public string Surname { get; set; }
[Display(Name = "Avatar")]
public string Avatar { get; set; } //Lien vers l'image sur le serveur
[Display(Name = "Adresse")]
public string Address { get; set; }
[Display(Name = "Code postal")]
public string PostCode { get; set; }
[Display(Name = "Ville")]
public string City { get; set; }
[Display(Name = "Courriel")]
[EmailAddress]
public string Email { get; set; }
[Display(Name = "Téléphone")]
[Phone]
public string PhoneNumber { get; set; }
[Display(Name = "Cotisation réglée")]
public bool Cotisation { get; set; } = true;
[Display(Name = "Actif / Inactif")]
public bool Enable { get; set; } = true;
[Display(Name = "Date d'enregistrement")]
public DateTime RegistrationDate { get; set; }
[Display(Name = "Raison du blocage")]
public string DisableReason { get; set; }
public List<News> News { get; set; }
}
}
|
using Alabo.Domains.Entities;
using System.Collections.Generic;
namespace Alabo.UI.Design.AutoPreviews {
/// <summary>
/// 自动预览对应zk-priview组件
/// </summary>
public class AutoPreview {
/// <summary>
/// 命名空间
/// </summary>
public string Key { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 图标
/// </summary>
public string Icon { get; set; }
/// <summary>
/// 键值对
/// </summary>
public IList<KeyValue> KeyValues { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace SSDAssignmentBOX.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
//A user in ASP.NET Identity is represented by the ApplicationUser class which inherits the IdentityUser base class
public class ApplicationUser : IdentityUser //IdentityUser base class contains basic user details(Microsoft.AspNetCore.Identity) such as UserName, Password and Email.
{
[Required]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$", ErrorMessage = "Please Enter your Full Name")]
public string FullName { get; set; }
[Required]
[RegularExpression("^(s|t)[0-9]{7}[a-jz]{1}$", ErrorMessage = "Please Enter a valid NRIC eg.S1234567X")]
public string Nric { get; set; }
[RegularExpression(@"^[MF]+[a-z]+$", ErrorMessage = "Gender is required (Male/Female)")]
[StringLength(7, MinimumLength = 4, ErrorMessage = "Gender is required (Male/Female)")]
[Required(ErrorMessage = "Gender is required (Male/Female)")]
public string Gender { get; set; }
[Required(ErrorMessage = "Please select a valid Birthdate")]
[Display(Name = "Birthdate")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
[Required(ErrorMessage = "Please Enter Your StudentID")]
[RegularExpression("^(s|t)[0-9]{8}[a-jz]{1}$", ErrorMessage = "Please Enter a valid StudentID eg.S12345678X")]
[Display(Name = "StudentID ")]
public string StudentID { get; set; }
[Required]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$", ErrorMessage = "Please Enter your School (e.g Ngee Ann Polytechnic) ")]
[Display(Name = "School's Name")]
public string SchoolName { get; set; }
}
} |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using Sfa.Poc.ResultsAndCertification.Dfe.Models.Configuration;
using Sfa.Poc.ResultsAndCertification.Dfe.Application.Configuration;
using Sfa.Poc.ResultsAndCertification.Dfe.Web.Authentication;
using Sfa.Poc.ResultsAndCertification.Dfe.Web.Authentication.Interfaces;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using System.Globalization;
using Sfa.Poc.ResultsAndCertification.Dfe.Api.Client.Interfaces;
using Sfa.Poc.ResultsAndCertification.Dfe.Api.Client.Clients;
using Sfa.Poc.ResultsAndCertification.Dfe.Web.Filters;
namespace Sfa.Poc.ResultsAndCertification.Layout.Web
{
public class Startup
{
private readonly IConfiguration _config;
private readonly ILogger<Startup> _logger;
private readonly IWebHostEnvironment _env;
protected ResultsAndCertificationConfiguration ResultsAndCertificationConfiguration;
public Startup(IConfiguration configuration, ILogger<Startup> logger, IWebHostEnvironment env)
{
_config = configuration;
_logger = logger;
_env = env;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
ResultsAndCertificationConfiguration = ConfigurationLoader.Load(
_config[Constants.EnvironmentNameConfigKey],
_config[Constants.ConfigurationStorageConnectionStringConfigKey],
_config[Constants.VersionConfigKey],
_config[Constants.ServiceNameConfigKey]);
//services.AddControllersWithViews();
//services.AddRazorPages();
services.AddApplicationInsightsTelemetry();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAntiforgery(options =>
{
options.Cookie.Name = "tlevels-rc-x-csrf";
options.FormFieldName = "_csrfToken";
options.HeaderName = "X-XSRF-TOKEN";
});
services.AddMvc(config => {
if (!_env.IsDevelopment())
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
}
config.Filters.Add<AutoValidateAntiforgeryTokenAttribute>();
// TODO: Need to add custom exception filter
config.Filters.Add<CustomExceptionFilterAttribute>();
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
//services.AddSession(options =>
//{
// options.IdleTimeout = TimeSpan.FromMinutes(5);
// options.Cookie.HttpOnly = true;
// options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
//});
services.AddSingleton(ResultsAndCertificationConfiguration);
services.AddHttpClient<ITokenRefresher, TokenRefresher>();
services.AddTransient<ITokenService, TokenService>();
services.AddTransient<ITokenServiceClient, TokenServiceClient>();
services.AddHttpClient<IResultsAndCertificationInternalApiClient, ResultsAndCertificationInternalApiClient>();
services
.AddTransient<CustomCookieAuthenticationEvents>()
//.AddTransient<AccessTokenHttpMessageHandler>()
.AddHttpContextAccessor();
//services.AddHttpContextAccessor();
services.AddWebAuthentication(ResultsAndCertificationConfiguration, _logger, _env);
services.AddAuthorization();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var cultureInfo = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseExceptionHandler("/Home/Error");
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseXContentTypeOptions();
app.UseReferrerPolicy(opts => opts.NoReferrer());
app.UseXXssProtection(opts => opts.EnabledWithBlockMode());
app.UseXfo(xfo => xfo.Deny());
app.UseCsp(options => options
.ScriptSources(s =>
{
s.Self()
.CustomSources("https://az416426.vo.msecnd.net/",
"https://www.google-analytics.com/analytics.js",
"https://www.googletagmanager.com/",
"https://tagmanager.google.com/",
"https://www.smartsurvey.co.uk/")
.UnsafeInline();
}
));
app.UseStaticFiles();
app.UseRouting();
//app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseCookiePolicy();
app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
app.UseEndpoints(endpoints =>
{
//endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
//endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Unity.Profiling;
using UnityEngine.TestTools;
using UnityAtoms.BaseAtoms;
using UnityAtoms.Tags;
using UnityEngine;
using UnityEngine.TestTools.Constraints;
using Is = UnityEngine.TestTools.Constraints.Is;
using Random = UnityEngine.Random;
namespace UnityAtoms.Tags.Tests
{
public class AtomTagsTests
{
[UnityTest]
public IEnumerator TestingAndProfiling()
{
var go = new GameObject();
var atomicTags = go.AddComponent<AtomTags>();
List<string> random_tags_raw = new List<string>() { "a", "c", "e", "g", "i", "k", "m" };
random_tags_raw.OrderBy((s => Random.value)).ToList();
var fieldinfo = typeof(StringConstant).GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance);
for (int i = 0; i < random_tags_raw.Count; ++i)
{
var stringConstant = ScriptableObject.CreateInstance<StringConstant>();
fieldinfo.SetValue(stringConstant, random_tags_raw[i]);
atomicTags.AddTag(stringConstant);
}
var newConstant = ScriptableObject.CreateInstance<StringConstant>();
fieldinfo.SetValue(newConstant, "b");
yield return null;
yield return new WaitForFixedUpdate();
// with the help of those ProfilerMarkers you can check GC Alloc in the Profiler Window Pretty easy
// an alternative would be: https://docs.unity3d.com/2018.3/Documentation/ScriptReference/TestTools.Constraints.AllocatingGCMemoryConstraint.html
// Assert.That(() => { }, Is.Not.AllocatingGCMemory()); but it does not work correctly half of the time
Assert.That(() => { var t1 = atomicTags.Tags; }, Is.Not.AllocatingGCMemory());
Assert.That(() => { var t1 = atomicTags.Tags[1]; }, Is.Not.AllocatingGCMemory());
Assert.That(() => { var t1 = atomicTags.Tags[2].Value; }, Is.Not.AllocatingGCMemory());
Assert.That(() => { atomicTags.HasTag(null); }, Is.Not.AllocatingGCMemory());
Assert.AreSame(go, AtomTags.FindByTag("e"));
using (new ProfilerMarker("MySystem.FindByTag").Auto())
{
AtomTags.FindByTag("e");
}
// THIS:
// Assert.That(() => { var t1 = AtomicTags.FindByTag("e"); }, Is.AllocatingGCMemory());
// says it allocates, the profiler says it does not
using (new ProfilerMarker("MySystem.MultpleGet").Auto())
{
var t1 = atomicTags.Tags;
var t10 = t1[0];
var t11 = atomicTags.Tags[0];
var t2 = atomicTags.Tags;
}
using (new ProfilerMarker("MySystem.GetGlobal").Auto())
{
AtomTags.GetTagsForGameObject(go);
}
Assert.AreEqual(random_tags_raw.Count, atomicTags.Tags.Count);
for (var i = 0; i < atomicTags.Tags.Count - 1; i++)
{
Assert.IsTrue(String.CompareOrdinal(atomicTags.Tags[i].Value, atomicTags.Tags[i + 1].Value) < 0);
}
using (new ProfilerMarker("MySystem.AddCompletelyNewTag").Auto())
{
atomicTags.AddTag(newConstant);
}
Assert.AreEqual(random_tags_raw.Count + 1, atomicTags.Tags.Count);
for (var i = 0; i < atomicTags.Tags.Count - 1; i++)
{
Assert.IsTrue(String.CompareOrdinal(atomicTags.Tags[i].Value, atomicTags.Tags[i + 1].Value) < 0);
}
using (new ProfilerMarker("MySystem.RemoveTag").Auto())
{
atomicTags.RemoveTag(newConstant.Value);
}
Assert.AreEqual(random_tags_raw.Count, atomicTags.Tags.Count);
Assert.IsFalse(atomicTags.HasTag(newConstant.Value));
using (new ProfilerMarker("MySystem.AddTagAgain").Auto())
{
atomicTags.AddTag(newConstant);
}
Assert.IsTrue(atomicTags.HasTag("a"));
using (new ProfilerMarker("MySystem.HasTagTrue1").Auto())
{
atomicTags.HasTag("a");
}
Assert.IsTrue(go.HasTag("a"));
using (new ProfilerMarker("MySystem.HasTagTrue1Global").Auto())
{
go.HasTag("a");
}
Assert.IsTrue(go.HasTag("m"));
using (new ProfilerMarker("MySystem.HasTagTrue2").Auto())
{
go.HasTag("m");
}
Assert.IsFalse(go.HasTag("z"));
using (new ProfilerMarker("MySystem.HasTagFalse").Auto())
{
go.HasTag("z");
}
var falseList = new List<string>() { "d", "f", "h", "j", "l" };
var truelist = new List<string>() { "d", "f", "h", "j", "m" };
Assert.IsFalse(go.HasAnyTag(falseList));
using (new ProfilerMarker("MySystem.HasAnyTag_allFalse").Auto())
{
go.HasAnyTag(falseList);
}
Assert.IsTrue(go.HasAnyTag(truelist));
using (new ProfilerMarker("MySystem.HasAnyTag_lastTrue").Auto())
{
go.HasAnyTag(truelist);
}
yield return null;
}
}
}
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Test.Utilities.Common
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Helper class to create a test directory and put files
/// in it.
/// </summary>
public class TestDirBuilder
{
private readonly string directoryName;
private readonly List<string> fileNames = new List<string>();
private readonly List<string> filePaths = new List<string>();
public TestDirBuilder(string directoryName)
{
this.directoryName = directoryName;
Directory.CreateDirectory(directoryName);
}
public TestDirBuilder AddFile(string sourceFileName, string destFileName)
{
string filePath = Path.Combine(directoryName, destFileName);
File.WriteAllText(filePath, File.ReadAllText(sourceFileName));
fileNames.Add(destFileName);
filePaths.Add(filePath);
return this;
}
public IDisposable Pushd()
{
return new DirStack(directoryName);
}
public string DirectoryName
{
get { return directoryName; }
}
public IList<string> FileNames
{
get { return fileNames; }
}
public IList<string> FilePaths
{
get { return filePaths; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfAukcija
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public List<Klijent> VratiKlijente()
{
return ListaKlijenata.Instance.klijenti.ToList();
}
public Klijent LogIn(string ime, string prezime)
{
Klijent k = ListaKlijenata.Instance.klijenti
.Where(x => x.Ime.Equals(ime) && x.Prezime.Equals(prezime))
.FirstOrDefault();
return k;
}
public List<Eksponat> VratiEksponate()
{
return ListaEksponata.Instance.eksponati.ToList();
}
public Eksponat VratiPrviEksponat()
{
return ListaEksponata.Instance.eksponati[0];
}
public void DodajPonudu(string cena, Klijent klijent, int trenutniBrojEksponata)
{
Eksponat eksponat = VratiTrenutniEksponat(trenutniBrojEksponata);
eksponat.Cena = cena;
eksponat.IdKlijenta = klijent.Id;
}
public Eksponat VratiTrenutniEksponat(int broj)
{
if(ListaEksponata.Instance.eksponati.Count>broj)
return ListaEksponata.Instance.eksponati[broj];
return null;
}
}
}
|
using Testing.Views;
using Xamarin.Forms;
namespace Testing
{
public partial class TestingPage : MasterDetailPage
{
//Andri Fannar
public TestingPage()
{
InitializeComponent();
Detail = new NavigationPage(new Page1());
IsPresented = false;
}
void Handle_Clicked(object sender, System.EventArgs e)
{
Detail = new NavigationPage(new Page1());
IsPresented = false;
}
void Handle_Clicked2(object sender, System.EventArgs e)
{
Detail = new NavigationPage(new Page2());
IsPresented = false;
}
}
}
|
namespace Thingy.GraphicsPlus.SmdConverter
{
internal class SmdVertex
{
public float NormX { get; internal set; }
public float NormY { get; internal set; }
public float NormZ { get; internal set; }
public int ParentBone { get; internal set; }
public float PosX { get; internal set; }
public float PosY { get; internal set; }
public float PosZ { get; internal set; }
public float TextureU { get; internal set; }
public float TextureV { get; internal set; }
}
} |
using Microsoft.Extensions.DependencyInjection;
using SimplySqlSchema.SQLite;
using SimplySqlSchema.SqlServer;
namespace SimplySqlSchema
{
public static class SqlServerExtensions
{
public static IServiceCollection AddSqlServerSupport(this IServiceCollection services)
{
return services
.AddScoped<IConnectionFactory, SqlServerConnectionFactory>()
.AddScoped<ISchemaManager, SqlServerSchemaManager>()
.AddScoped<ISchemaQuerier, SqlServerQuerier>();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
private static GameManager _instance;
public RectTransform pauseScreen;
public RectTransform mainMenu;
public static GameManager Instance
{
get {
//create logic to create instance
if (_instance == null) {
GameObject go = new GameObject ("GameManager");
go.AddComponent<GameManager> ();
}
return _instance;
}
}
public int Score { get; set; }
public bool IsDead { get; set; }
void Awake()
{
_instance = this;
}
void Start()
{
Score = 10;
Time.timeScale = 1;
pauseScreen.gameObject.SetActive(false);
}
void Update()
{
if (IsDead) {
this.TogglePauseMenu ();
}
}
public void TogglePauseMenu()
{
pauseScreen.gameObject.SetActive(true);
Invoke("loadMainMenu", 1.5f);
}
public void loadMainMenu()
{
Application.LoadLevel ("MainMenu");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using Happiness.Filters;
using Happiness.Models;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Objects;
using System.IO;
using OfficeOpenXml;
namespace Happiness.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
if (Roles.IsUserInRole("admin") || IsAccess("Employee", User.Identity.Name, db))
{
return View();
}
else
{
return RedirectToAction("Noaccess", "Account");
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
WebSecurity.Logout();
return RedirectToAction("Login", "Account");
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
SelectList list = new SelectList(Roles.GetAllRoles());
ViewBag.Roles = list;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
model.Emp_isActive = true;
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new
{
EmployeeCode = model.EmployeeCode,
EmployeeName = model.EmployeeName,
Emp_Address = model.Emp_Address,
Emp_Email = model.Emp_Email,
Emp_isActive = model.Emp_isActive,
Emp_Tel = model.Emp_Tel,
Emp_Mob = model.Emp_Mob,
Emp_Reporting_Authority = model.Emp_Reporting_Authority
});
Roles.AddUserToRole(model.UserName, model.RoleID);
//WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Account");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Disassociate(string provider, string providerUserId)
{
string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
ManageMessageId? message = null;
// Only disassociate the account if the currently logged in user is the owner
if (ownerAccount == User.Identity.Name)
{
// Use a transaction to prevent the user from deleting their last login credential
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
{
OAuthWebSecurity.DeleteAccount(provider, providerUserId);
scope.Complete();
message = ManageMessageId.RemoveLoginSuccess;
}
}
}
return RedirectToAction("Manage", new { Message = message });
}
//
// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
catch (Exception)
{
ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetAllroles()
{
SelectList list = new SelectList(Roles.GetAllRoles().ToList(), "Id", "Name");
return Json(list, JsonRequestBehavior.AllowGet);
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
{
string provider = null;
string providerUserId = null;
if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
// Check if user already exists
if (user == null)
{
// Insert name into the profile table
db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
db.SaveChanges();
OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
}
}
}
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[AllowAnonymous]
[ChildActionOnly]
public ActionResult ExternalLoginsList(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
}
[ChildActionOnly]
public ActionResult RemoveExternalLogins()
{
ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
List<ExternalLogin> externalLogins = new List<ExternalLogin>();
foreach (OAuthAccount account in accounts)
{
AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);
externalLogins.Add(new ExternalLogin
{
Provider = account.Provider,
ProviderDisplayName = clientData.DisplayName,
ProviderUserId = account.ProviderUserId,
});
}
ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
return PartialView("_RemoveExternalLoginsPartial", externalLogins);
}
#region Helpers
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
}
internal class ExternalLoginResult : ActionResult
{
public ExternalLoginResult(string provider, string returnUrl)
{
Provider = provider;
ReturnUrl = returnUrl;
}
public string Provider { get; private set; }
public string ReturnUrl { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
}
}
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
#region UserProfileIndex
UsersContext db = new UsersContext();
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
UserProfile division = db.UserProfiles.Find(id);
db.UserProfiles.Remove(division);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult DeleteAJAX(int divsID)
{
try
{
//UserProfile child = (from t in db.UserProfiles where t.Report_MasterID == divsID select t).FirstOrDefault();
//db.ReportingAuthorityAllocationChild.Remove(child);
//db.SaveChanges();
UserProfile division = db.UserProfiles.Find(divsID);
db.UserProfiles.Remove(division);
db.SaveChanges();
return Json("Record deleted successfully!");
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
private int SortString(string s1, string s2, string sortDirection)
{
return sortDirection == "asc" ? s1.CompareTo(s2) : s2.CompareTo(s1);
}
private int SortInteger(string s1, string s2, string sortDirection)
{
long i1 = long.Parse(s1);
long i2 = long.Parse(s2);
return sortDirection == "asc" ? i1.CompareTo(i2) : i2.CompareTo(i1);
}
private int SortDateTime(string s1, string s2, string sortDirection)
{
DateTime d1 = DateTime.Parse(s1);
DateTime d2 = DateTime.Parse(s2);
return sortDirection == "asc" ? d1.CompareTo(d2) : d2.CompareTo(d1);
}
public static List<ReportingAuthorityAllocation> GetAllTransactions()
{
using (var context = new UsersContext())
{
return (from pd in context.ReportingAuthorityAllocation
join od in context.ReportingAuthority on pd.Report_id equals od.id
select new
{
id = pd.id,
Report_id = pd.Report_id,
Reporting_auth_name = od.Reporting_auth_name
// StudentName = od.StudentName
}).AsEnumerable().Select(x => new ReportingAuthorityAllocation
{
id = x.id,
Report_id = x.Report_id,
Reporting_auth_name = x.Reporting_auth_name
// StudentName = x.StudentName
}).ToList();
}
}
private List<UserProfile> FilterData(ref int recordFiltered, int start, int length, string search, int sortColumn, string sortDirection)
{
List<UserProfile> list = new List<UserProfile>();
if (search == null)
{
list = db.UserProfiles.ToList();
}
else
{
// simulate search
foreach (UserProfile dataItem in db.UserProfiles.ToList())
{
try
{
if (dataItem.EmployeeCode.ToUpper().Contains(search.ToUpper()) ||
dataItem.EmployeeName.ToUpper().Contains(search.ToUpper()) ||
Convert.ToString(dataItem.Emp_Mob).Contains(search.ToUpper()) ||
Convert.ToString(dataItem.Emp_Email).Contains(search.ToUpper()))
{
list.Add(dataItem);
}
}
catch (Exception ex)
{
continue;
}
}
}
// simulate sort
if (sortColumn == 0)
{// sort Name
list.Sort((x, y) => SortString(x.EmployeeCode, y.EmployeeCode, sortDirection));
}
if (sortColumn == 1)
{// sort Name
list.Sort((x, y) => SortString(x.EmployeeName, y.EmployeeName, sortDirection));
}
if (sortColumn == 3)
{// sort Name
list.Sort((x, y) => SortString(x.Emp_Email, y.Emp_Email, sortDirection));
}
//else if (sortColumn == 1)
//{// sort Name
// list.Sort((x, y) => SortInteger(x.StudentRegno, y.StudentRegno, sortDirection));
//}
//else if (sortColumn == 2)
//{// sort Age
// list.Sort((x, y) => SortInteger(x.StudentAppNo, y.StudentAppNo, sortDirection));
//}
//else if (sortColumn == 3)
//{
// list.Sort((x, y) => SortInteger(x.RechargeCardNo, y.RechargeCardNo, sortDirection));
// // sort DoB
// // list.Sort((x, y) => SortDateTime(x.DoB, y.DoB, sortDirection));
//}
recordFiltered = list.Count;
// get just one page of data
list = list.GetRange(start, Math.Min(length, list.Count - start));
return list;
}
public class DataTableData
{
public int draw { get; set; }
public int recordsTotal { get; set; }
public int recordsFiltered { get; set; }
public List<UserProfile> data { get; set; }
}
public ActionResult GettAllData(int draw, int start, int length)
{
string search = Request.QueryString["search[value]"];
int sortColumn = -1;
string sortDirection = "asc";
if (length == -1)
{
// length = TOTAL_ROWS;
}
// note: we only sort one column at a time
if (Request.QueryString["order[0][column]"] != null)
{
sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
}
if (Request.QueryString["order[0][dir]"] != null)
{
sortDirection = Request.QueryString["order[0][dir]"];
}
DataTableData dataTableData = new DataTableData();
dataTableData.draw = draw;
// dataTableData.recordsTotal = TOTAL_ROWS;
int recordsFiltered = 0;
dataTableData.data = FilterData(ref recordsFiltered, start, length, search, sortColumn, sortDirection);
dataTableData.recordsFiltered = recordsFiltered;
return Json(dataTableData, JsonRequestBehavior.AllowGet);
}
public JsonResult Employees()
{
return Json(db.UserProfiles.ToList(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult CardActivateOrDeactivate(int StudID)
{
try
{
UserProfile userpro = db.UserProfiles.Find(StudID);
if (userpro.Emp_isActive == true)
{
userpro.Emp_isActive = false;
}
else
{
userpro.Emp_isActive = true;
}
db.Entry(userpro).State = EntityState.Modified;
db.SaveChanges();
}
catch (Exception ex)
{
}
UserProfile studM = db.UserProfiles.Find(StudID);
bool cardStatus = studM.Emp_isActive;
return Json(studM.Emp_isActive, JsonRequestBehavior.AllowGet);
}
#endregion
#region Edit
public ActionResult Edit(long id = 0)
{
UserProfile UserPro = db.UserProfiles.Find(id);
// division.PhotoPath = "~/Upload/" + division.PhotoPath;
ViewBag.Report_ID = UserPro.Emp_Reporting_Authority;
ViewBag.roleId = Roles.GetRolesForUser(UserPro.UserName);
SelectList list = new SelectList(Roles.GetAllRoles());
ViewBag.Roles = list;
if (UserPro == null)
{
return HttpNotFound();
}
return View(UserPro);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserProfile UserProfile)
{
if (ModelState.IsValid)
{
try
{
UserProfile.Emp_isActive = true;
db.Entry(UserProfile).State = EntityState.Modified;
db.SaveChanges();
var role= Roles.GetRolesForUser(UserProfile.UserName);
Roles.RemoveUserFromRole(UserProfile.UserName,role.ToList().SingleOrDefault());
Roles.AddUserToRole(UserProfile.UserName, UserProfile.RoleID);
return RedirectToAction("Index");
}
catch (Exception ex)
{
//if (ex.Message.Contains("DBException"))
//{
ModelState.AddModelError("", "You are updating with existing data!! please correct the data");
//}
}
}
return View(UserProfile);
}
#endregion
#region ExcelUpload
public ActionResult ExcelUpload()
{
return View();
}
[HttpPost]
public ActionResult ExcelUpload(FormCollection fromcollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
string extension = Path.GetExtension(file.FileName);
if (file != null && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
if (extension == ".xlsx")
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
try
{
string EmployeeCode = workSheet.Cells[rowIterator, 1].Value.ToString();
string employeeName = workSheet.Cells[rowIterator, 2].Value.ToString();
string ReportAuth = workSheet.Cells[rowIterator, 3].Value.ToString();
string EmployeeAddress = null;
if (workSheet.Cells[rowIterator, 4].Value != null)
{
EmployeeAddress = workSheet.Cells[rowIterator, 4].Value.ToString();
}
string mobile = null;
if (workSheet.Cells[rowIterator, 5].Value != null)
{
mobile = workSheet.Cells[rowIterator, 5].Value.ToString();
}
string telephone=null;
if (workSheet.Cells[rowIterator, 6].Value != null)
{
telephone = workSheet.Cells[rowIterator, 6].Value.ToString();
}
string Email = null;
if (workSheet.Cells[rowIterator, 7].Value != null)
{
Email = workSheet.Cells[rowIterator, 7].Value.ToString();
}
string username = workSheet.Cells[rowIterator, 8].Value.ToString();
string password = workSheet.Cells[rowIterator, 9].Value.ToString();
string RoleName = workSheet.Cells[rowIterator, 10].Value.ToString();
var EmpC = db.UserProfiles.Where(u => u.EmployeeCode == EmployeeCode).FirstOrDefault();
var UserN = db.UserProfiles.Where(u => u.UserName == username).FirstOrDefault();
ReportingAuthority reportA = db.ReportingAuthority.Where(u => u.Reporting_auth_name == ReportAuth).FirstOrDefault();
if (EmpC != null)
{
ModelState.AddModelError("",
"Employee Code" + EmployeeCode + " Already Exists");
}
if (UserN != null)
{
ModelState.AddModelError("",
"UserName " + username + " Already Exists");
}
if (reportA == null)
{
ModelState.AddModelError("",
"Report Authority " + username + " Npt Exists");
}
if (EmpC == null && UserN == null && password != null && reportA != null && RoleName !=string.Empty)
{
bool Emp_isActive = true;
WebSecurity.CreateUserAndAccount(username, password, new
{
EmployeeCode = EmployeeCode,
EmployeeName = employeeName,
Emp_Address = EmployeeAddress,
Emp_Email = Email,
Emp_isActive = Emp_isActive,
Emp_Tel = telephone,
Emp_Mob = mobile,
Emp_Reporting_Authority = reportA.id
});
Roles.AddUserToRole(username, RoleName);
}
}
catch (Exception ex)
{
ModelState.AddModelError("", "Error :" + ex.Message + "Row No:" + rowIterator);
continue;
}
}
}
}
else
{
ModelState.AddModelError("", "Please Select valid Excel file");
}
}
}
return View();
}
#endregion
#region Roles
public ActionResult CreateRoles()
{
return View();
}
[Authorize(Roles = "Admin")]
public ActionResult RoleIndex()
{
var roles = Roles.GetAllRoles();
return View(roles);
}
[Authorize(Roles = "Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateRoles(string RoleName)
{
if (Request.Form["RoleName"] != string.Empty)
{
Roles.CreateRole(Request.Form["RoleName"]);
// ViewBag.ResultMessage = "Role created successfully !";
return RedirectToAction("RoleIndex", "Account");
}
else
{
ModelState.AddModelError("RoleName","Please enter RoleName");
return View();
}
}
[Authorize(Roles = "Admin")]
public ActionResult RoleDelete(string RoleName)
{
Roles.DeleteRole(RoleName);
// ViewBag.ResultMessage = "Role deleted succesfully !";
return Json("Record deleted successfully!");
}
#endregion
#region Permission
[Authorize(Roles = "Admin")]
[HttpGet]
public ActionResult Permission(string RoleName)
{
if (RoleName != null)
{
if (Roles.RoleExists(RoleName))
{
ViewBag.RoleName = RoleName;
List<Permission> perm = new List<Models.Permission>();
perm = db.Permission.ToList().Where(u=>u.rolName == RoleName).ToList();
if (perm.Count > 0)
{
return View(perm);
}
else
{
perm.Add(new Permission() { id = 0, MenuName = "Reporting Authority", rolName = RoleName, permission = false });
perm.Add(new Permission() { id = 0, MenuName = "Employee", rolName = RoleName, permission = false });
perm.Add(new Permission() { id = 0, MenuName = "Emotions", rolName = RoleName, permission = false });
perm.Add(new Permission() { id = 0, MenuName = "Assign Report Head", rolName = RoleName, permission = false });
perm.Add(new Permission() { id = 0, MenuName = "Reports", rolName = RoleName, permission = false });
perm.Add(new Permission() { id = 0, MenuName = "Company Registration", rolName = RoleName, permission = false });
perm.Add(new Permission() { id = 0, MenuName = "Email configuration", rolName = RoleName, permission = false });
return View(perm);
}
}
else
{
return RedirectToAction("RoleIndex", "Account");
}
}
else
{
return RedirectToAction("RoleIndex", "Account");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Permission(List<Permission> Permission)
{
int i = 0;
foreach (Permission per in Permission)
{
if (i == 0)
{
List<Permission> perm = db.Permission.ToList().Where(u => u.rolName == per.rolName).ToList();
if (perm.Count > 0)
{
db.Permission.RemoveRange(perm);
db.SaveChanges();
}
}
db.Permission.Add(per);
db.SaveChanges();
i++;
}
return RedirectToAction("RoleIndex", "Account");
}
public static bool IsAccess(string MenuName,string username ,UsersContext db)
{
string[] role = Roles.GetRolesForUser(username);
if (role.Count() > 0)
{
var temp = role[0];
Permission Perm = db.Permission.Where(u => u.rolName == temp.ToString() && u.MenuName == MenuName).SingleOrDefault();
if (Perm.permission == true)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public ActionResult Noaccess()
{
return View();
}
#endregion
}
}
|
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
using Union.Gateway.Abstractions;
namespace Union.Gateway.Traffic
{
public class UnionTrafficServiceHostedService : IHostedService
{
private readonly IUnionMsgConsumer jT808MsgConsumer;
private readonly IUnionTraffic jT808Traffic;
public UnionTrafficServiceHostedService(
IUnionTraffic jT808Traffic,
IUnionMsgConsumer jT808MsgConsumer)
{
this.jT808MsgConsumer = jT808MsgConsumer;
this.jT808Traffic = jT808Traffic;
}
public Task StartAsync(CancellationToken cancellationToken)
{
jT808MsgConsumer.Subscribe();
jT808MsgConsumer.OnMessage((item) => {
//string str = item.Data.ToHexString();
jT808Traffic.Increment(item.TerminalNo, DateTime.Now.ToString("yyyyMMdd"), item.Data.Length);
});
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
jT808MsgConsumer.Unsubscribe();
return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BenefitDeductionAPI.Models.FamilyMembers
{
public class FamilyMemberDto
{
public int EmployeeId { get; set; }
public int FamilyMemberId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; } = "";
public string LastName { get; set; }
public bool IsSpouse { get; set; } = false;
public bool IsChild { get; set; } = false;
}
}
|
using System;
using System.Collections.Generic;
using Pe.Stracon.SGC.Infraestructura.Core.Base;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Repository.Query.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel;
namespace Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual
{
/// <summary>
/// Definición del Repositorio Listado Contrato Logic
/// </summary>
public interface IContratoCorporativoLogicRepository : IQueryRepository<ContratoCorporativoLogic>
{
/// <summary>
/// Realiza la búsqueda de Contratos corporativos
/// </summary>
/// <param name="codigoUnidadOperativa">Código de unidad operativa</param>
/// <param name="codigoTipoServicio">Código de Tipo de Servicio</param>
/// <param name="codigoTipoRequerimiento">Código de Tipo de Requerimiento</param>
/// <param name="codigoTipoDocumento">Código de Tipo de Documento</param>
/// <param name="codigoEstado">Código de Estado de contrato</param>
/// <param name="numeroContrato">Número de Contrato</param>
/// <param name="descripcion">Descripción de Contrato</param>
/// <param name="fechaInicioVigencia">Fecha inicio de vigencia</param>
/// <param name="fechaFinVigencia">Fecah fin de vigencia</param>
/// <param name="nombreProveedor">Proveedor</param>
/// <param name="numeroPagina">Total de Páginas</param>
/// <param name="registroPagina">Total de Registros por Página</param>
/// <returns>Lista de contratos</returns>
List<ContratoCorporativoLogic> BuscarContratosCorporativos(Guid? codigoUnidadOperativa,
string codigoTipoServicio,
string codigoTipoRequerimiento,
string codigoTipoDocumento,
string codigoEstado,
string numeroContrato,
string descripcion,
DateTime? fechaInicioVigencia,
DateTime? fechaFinVigencia,
string nombreProveedor,
int numeroPagina,
int registroPagina);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DigitalFormsSteamLeak.Entity.IModels;
namespace DigitalFormsSteamLeak.Entity.Models
{
[Table("T_Work_Order_Status_Session")]
public class WorkOrderStatusSession : IWorkOrderStatusSession
{
[Key]
[Column("Work_Order_Status_Id")]
public Guid WorkOrderStatusId { get; set; }
[Required]
[Column("Work_Done_By")]
public string WorkDoneBy { get; set; }
[Required]
[Column("Work_Order_Status")]
public string WorkOrderStatus { get; set; }
[Required]
[Column("Work_Order_Status_Comments")]
public string WorkOrderStatusComments { get; set; }
[Column("Work_Order_Completed_Date")]
public DateTime WorkOrderCompletedDate { get; set; }
[Required]
[Column("Leak_Details_Id")]
public Guid LeakDetailsId { get; set; }
public virtual LeakDetails LeakDetails { get; set; }
}
} |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ProjektTEM
{
public partial class Form1 : Form
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
public Form1()
{
InitializeComponent();
morphologyTypeDropdownList.Items.AddRange(Enum.GetNames(typeof(Morphology)));
morphologyTypeDropdownList.SelectedItem = morphologyTypeDropdownList.Items[0];
}
private void LoadImageButton_Click(object sender, EventArgs e)
{
FileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Image Files(*.BMP; *.JPG; *.PNG)| *.BMP; *.JPG; *.PNG; | All files(*.*) | *.*";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
pictureBoxBefore.ImageLocation = fileDialog.FileName;
}
}
private void FilterButton_Click(object sender, EventArgs e)
{
if (pictureBoxAfterThreshold.Image == null)
MessageBox.Show("Generate binary image first.");
else
pictureBoxFiltered.Image = ImageFiltering.Filter((Bitmap)pictureBoxAfterThreshold.Image, (Morphology)Enum.Parse(typeof(Morphology), morphologyTypeDropdownList.SelectedItem.ToString()));
}
private void ThresholdButton_Click(object sender, EventArgs e)
{
if (pictureBoxBefore.Image == null)
MessageBox.Show("Load image first.");
else
pictureBoxAfterThreshold.Image = ImageFiltering.Threshold(pictureBoxBefore.ImageLocation, (float)thresholdFactor.Value);
}
private void saveThresholdButton_Click(object sender, EventArgs e)
{
saveFileDialog.FileName = ImageUtil.AddSuffix(pictureBoxBefore.ImageLocation, "Thresholded");
if (saveFileDialog.ShowDialog() == DialogResult.OK)
pictureBoxAfterThreshold.Image.Save(saveFileDialog.FileName);
}
private void saveFilteredButton_Click(object sender, EventArgs e)
{
saveFileDialog.FileName = ImageUtil.AddSuffix(pictureBoxBefore.ImageLocation, morphologyTypeDropdownList.SelectedItem.ToString());
if (saveFileDialog.ShowDialog() == DialogResult.OK)
pictureBoxFiltered.Image.Save(saveFileDialog.FileName);
}
}
}
|
using System;
using Uintra.Features.Links.Models;
namespace Uintra.Features.Mention.Models
{
public class MentionUserModel
{
public Guid Id { get; set; }
public string Value { get; set; }
public UintraLinkModel Url { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Web.Http;
namespace Demonstracao.Controllers
{
public class EspeciariaController : ApiController
{
// GET api/especiaria
public IEnumerable<Especiaria> Get()
{
return new List<Especiaria>()
{
new Especiaria()
{Id = 1, Nome = "Melange", Data = DateTime.Now, Valor = 50, Comestivel = true},
new Especiaria()
{Id = 2, Nome = "Pó de pirinpinpin", Data = DateTime.Now, Valor = 5, Comestivel = false}
};
}
// GET api/especiaria/5
public Especiaria Get(int id)
{
return new Especiaria() { Id = 2, Nome = "Pó de pirinpinpin", Data = DateTime.Now, Valor = 5, Comestivel = false };
}
// POST api/especiaria
public void Post([FromBody]Especiaria value)
{
}
// PUT api/especiaria/5
public void Put(int id, [FromBody]Especiaria value)
{
}
// DELETE api/especiaria/5
public void Delete(int id)
{
id = id + 2;
}
}
public class Especiaria
{
public int Id { get; set; }
public string Nome { get; set; }
public DateTime Data { get; set; }
public int Valor { get; set; }
public bool Comestivel { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPI.Models;
namespace MyWebAPI.Controllers
{
public class ProductController : ApiController
{
private ProductRepository pr = new ProductRepository();
public IEnumerable<Product> Get()
{
return pr.FindAll();
}
public Product Get(string id)
{
return pr.Find(id);
}
}
}
|
using AkvelonTaskMilosBelic.Interfaces;
using AkvelonTaskMilosBelic.Models.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace AkvelonTaskMilosBelic.Controllers
{
public class ProjectTasksController : ApiController
{
public IProjectTaskService service { get; set; }
public ProjectTasksController(IProjectTaskService service)
{
this.service = service;
}
public IEnumerable<ProjectTaskDTO> GetAll()
{
return service.GetAll();
}
[Route("api/Projects/TasksFromProject")]
public IEnumerable<ProjectTaskDTO> GetTasksFromProject(ProjectDTO projectDTO)
{
return service.GetTasksFromProject(projectDTO);
}
[ResponseType(typeof(ProjectTaskDTO))]
public IHttpActionResult GetById(int id)
{
var projectTask = service.GetById(id);
if (projectTask == null)
{
return NotFound();
}
return Ok(projectTask);
}
[HttpPost()]
[ResponseType(typeof(ProjectTaskDTO))]
public IHttpActionResult Post(ProjectTaskRequest projectTaskRequest)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
service.Create(projectTaskRequest);
return Created("DefaultApi", projectTaskRequest);
}
[HttpPut]
[ResponseType(typeof(ProjectTaskDTO))]
public IHttpActionResult Put(int id, ProjectTaskRequest projectTaskRequest)
{
var projectTask = service.GetById(id);
if (projectTask == null)
{
return NotFound();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
service.Update(id, projectTaskRequest);
}
catch
{
return Conflict();//I think that Conflict() will be the best status code if we have concurrency problem
}
return StatusCode(HttpStatusCode.NoContent);
}
[HttpDelete]
[ResponseType(typeof(ProjectTaskDTO))]
public IHttpActionResult Delete(int id)
{
service.Delete(id);
return StatusCode(HttpStatusCode.NoContent);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace SQMS.Services.ReferenceServices
{
/// <summary>
/// 在实现FetchData的时候,在SQL中必须要有两个列,分别命名为value和text,大小写无关
/// </summary>
public interface IReferenceService
{
DataTable FetchReferenceData();
}
}
|
#region using
using System;
#endregion
namespace iSukces.Code.Interfaces
{
public partial class Auto
{
#region Nested
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ReactivePropertyAttribute : PropertyAttributeBase
{
#region Constructors
public ReactivePropertyAttribute(string name, Type propertyType, string description = null)
{
Name = name;
PropertyType = propertyType;
Description = description;
}
#endregion
#region Properties
public Visibilities FieldVisibility { get; set; } = Visibilities.Private;
#endregion
}
#endregion
}
} |
using Tomelt.Environment.Extensions;
using Tomelt.Layouts.Framework.Elements;
using Tomelt.Layouts.Helpers;
namespace Tomelt.Widgets.Layouts.Elements {
[TomeltFeature("Tomelt.Widgets.Elements")]
public class Widget : Element {
public override string Category {
get { return "Widgets"; }
}
public override bool IsSystemElement {
get { return true; }
}
public override bool HasEditor {
get { return false; }
}
public int? WidgetId {
get { return this.Retrieve(x => x.WidgetId); }
set { this.Store(x => x.WidgetId, value); }
}
}
} |
using UnityEngine;
using System.Collections;
using System.Security.Permissions;
using UnityEngine.UI;
public class SendShipsPanel : MonoBehaviour
{
public Text ShipsCount;
public Text TargetPlanetName;
public Text TravelTimeText;
public Slider Slider;
public Text SliderValueText;
public Text SliderValueTextRemaining;
public UnityEngine.UI.Button SendButton;
public PlanetEntity TargetPlanet { get; private set; }
public PlanetEntity SourcePlanet { get; private set; }
public int Slidervalue { get; private set; }
public void UpdatePanel(PlanetEntity planet)
{
SourcePlanet = planet;
TargetPlanetName.text = "-------------";
TravelTimeText.text = "--- Days";
ShipsCount.text = planet.ships + "/" + planet.hangarSize;
Slider.minValue = 1;
Slider.maxValue = planet.ships;
Slider.value = (int)(planet.ships/2);
SliderValueChanged();
SendButton.interactable = false;
if (planet.ships == 0)
{
Slider.minValue = 0;
}
}
public void UpdateTargetPlanet(PlanetEntity target)
{
if (SourcePlanet.ships == 0 || target == SourcePlanet)
{
return;
}
if (TargetPlanet != null )
{
TargetPlanet.DisableOutline();
}
SendButton.interactable = true;
target.SetOutline(Color.red);
TargetPlanet = target;
TargetPlanetName.text = target.planetName;
TravelTimeText.text = target.GetTravelTime(SourcePlanet) + " Days";
}
public void SliderValueChanged()
{
Slidervalue = (int) Mathf.Floor(Slider.value);
if (Slidervalue == 0 && SourcePlanet.ships == 1){
Slidervalue = 1;
}
SliderValueText.text = Slidervalue.ToString();
SliderValueTextRemaining.text = "/ " + (SourcePlanet.ships - Slidervalue);
}
}
|
namespace Ach.Fulfillment.Data.Specifications
{
using System;
using System.Linq.Expressions;
using Ach.Fulfillment.Data.Common;
public class RoleByName : SpecificationBase<RoleEntity>
{
private readonly string name;
public RoleByName(string name)
{
this.name = name;
}
public override Expression<Func<RoleEntity, bool>> IsSatisfiedBy()
{
return m => m.Name == this.name;
}
}
} |
using KeepTeamAutotests.Model;
using KeepTeamAutotests.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KeepTeamAutotests.AppLogic
{
public class KPIHelper
{
private AppManager app;
private PageManager pages;
public KPIHelper(AppManager app)
{
this.app = app;
this.pages = app.Pages;
}
public void createKPI(KPI kpi)
{
editKPI(kpi);
}
public void editKPI(KPI kpi)
{
//заполнение полей создания KPI
pages.newKPIPopup.ensurePageLoaded();
pages.newKPIPopup.setNameField(kpi.KPIName);
pages.newKPIPopup.setDateField(kpi.KPIDate);
pages.newKPIPopup.setDescriptionField(kpi.KPIDescription);
//pages.newKPIPopup.setEmployeeField(kpi.KPIEmployee);
pages.newKPIPopup.setProgressBar(kpi.KPIProgress);
pages.newKPIPopup.setActionsField(kpi.KPIActions);
pages.newKPIPopup.setMeasuringField(kpi.KPIMeasuring);
pages.newKPIPopup.addClick();
refreshpage();
}
public void refreshpage()
{
//перезагрузка страницы, для проверки введенных полей
pages.newKPIPopup.waitSaveDone();
pages.newKPIPopup.refreshPage();
}
public bool CompareKPI(KPI KPI1, KPI KPI2)
{
KPI1.WriteToConsole();
KPI2.WriteToConsole();
return
KPI1.KPIName == KPI2.KPIName &&
KPI1.KPIDate == KPI2.KPIDate &&
KPI1.KPIEmployee == KPI2.KPIEmployee &&
KPI1.KPIDescription == KPI2.KPIDescription &&
KPI1.KPIProgress == KPI2.KPIProgress &&
KPI1.KPIMeasuring == KPI2.KPIMeasuring &&
KPI1.KPIActions == KPI2.KPIActions;
}
public KPI getKPIPopup()
{
openFirstKPI();
//переход к первой записи
pages.newKPIPopup.ensurePageLoaded();
KPI kpi = new KPI();
kpi.KPIDate = pages.newKPIPopup.getDate();
kpi.KPIDescription = pages.newKPIPopup.getDescription();
kpi.KPIEmployee = pages.newKPIPopup.getEmployee();
kpi.KPIMeasuring = pages.newKPIPopup.getMeasuring();
kpi.KPIActions = pages.newKPIPopup.getActions();
kpi.KPIName = pages.newKPIPopup.getName();
kpi.KPIProgress = pages.newKPIPopup.getProgress();
pages.newKPIPopup.closePopup();
return kpi;
}
public void DeleteCurrentKPI()
{
//Удаление через троеточие
openDeleteMessageFromThreeDots();
pages.deleteMessagePage.yesButtonClick();
pages.deleteMessagePage.waitSaveDone();
}
public void openDeleteMessageFromThreeDots()
{
//Открытие меню удаления
pages.personalKPIPage.ensurePageLoaded();
pages.personalKPIPage.deleteFromThreeDots();
//клик по кнопке удаления
pages.contextMenuPage.ensurePageLoaded();
pages.contextMenuPage.byIndexClick(0);
pages.deleteMessagePage.ensurePageLoaded();
}
/* public KPI getKPIFromPersonalTable() пока закомментировал, потому как нет разницы в персональной и общей таблице
{
KPI kpi = new KPI();
kpi.KPIName = pages.personalKPIPage.getKPIName();
kpi.KPIDate = pages.personalKPIPage.getKPIDate();
kpi.KPIProgress = pages.personalKPIPage.getKPIProgress();
return kpi;
}*/
public KPI getKPIFromTable()
{
KPI kpi = new KPI();
kpi.KPIName = pages.personalKPIPage.getKPIName();
kpi.KPIDate = pages.personalKPIPage.getKPIDate();
kpi.KPIProgress = pages.personalKPIPage.getKPIProgress();
kpi.KPIEmployee = pages.personalKPIPage.getKPIEmployee();
return kpi;
}
public void openFirstKPI()
{
//получение информации о KPI
pages.personalKPIPage.ensurePageLoaded();
pages.personalKPIPage.openKPIPopup();
}
public void clearKPIPopup()
{
//Очистка полей попапа KPI
pages.newKPIPopup.ensurePageLoaded();
pages.newKPIPopup.clearName();
pages.newKPIPopup.clearDate();
//pages.newKPIPopup.clearEmployee();
pages.newKPIPopup.clearDescription();
pages.newKPIPopup.clearProgress();
pages.newKPIPopup.clearMeasuring();
pages.newKPIPopup.clearActions();
}
}
}
|
using FluentAssertions;
using ModaTime;
using NUnit.Framework;
using System;
using System.Collections;
using System.Globalization;
namespace ModaTime.Test
{
class MonthTextOfYearTests
{
[SetUp]
public void Setup()
{
}
[Test, TestCaseSource("TestCases_ZHTW")]
public void Get_MonthNameOfYear_ZHTW(DateTime date, string dayText)
{
var actual = date.MonthNameOfYear();
actual.Should().Be(dayText);
}
public static IEnumerable TestCases_ZHTW
{
get
{
yield return new TestCaseData(new DateTime(2019, 1, 1), "一月");
yield return new TestCaseData(new DateTime(2019, 2, 1), "二月");
yield return new TestCaseData(new DateTime(2019, 3, 1), "三月");
yield return new TestCaseData(new DateTime(2019, 4, 1), "四月");
yield return new TestCaseData(new DateTime(2019, 5, 1), "五月");
yield return new TestCaseData(new DateTime(2019, 6, 1), "六月");
yield return new TestCaseData(new DateTime(2019, 7, 1), "七月");
yield return new TestCaseData(new DateTime(2019, 8, 1), "八月");
yield return new TestCaseData(new DateTime(2019, 9, 1), "九月");
yield return new TestCaseData(new DateTime(2019, 10, 1), "十月");
yield return new TestCaseData(new DateTime(2019, 11, 1), "十一月");
yield return new TestCaseData(new DateTime(2019, 12, 1), "十二月");
}
}
[Test, TestCaseSource("TestCases_ENUS")]
public void Get_MonthNameOfYear_ENUS(DateTime date, string dayText)
{
var actual = date.MonthNameOfYear(CultureInfo.InvariantCulture);
actual.Should().Be(dayText);
}
public static IEnumerable TestCases_ENUS
{
get
{
yield return new TestCaseData(new DateTime(2019, 1, 1), "January");
yield return new TestCaseData(new DateTime(2019, 2, 1), "February");
yield return new TestCaseData(new DateTime(2019, 3, 1), "March");
yield return new TestCaseData(new DateTime(2019, 4, 1), "April");
yield return new TestCaseData(new DateTime(2019, 5, 1), "May");
yield return new TestCaseData(new DateTime(2019, 6, 1), "June");
yield return new TestCaseData(new DateTime(2019, 7, 1), "July");
yield return new TestCaseData(new DateTime(2019, 8, 1), "August");
yield return new TestCaseData(new DateTime(2019, 9, 1), "September");
yield return new TestCaseData(new DateTime(2019, 10, 1), "October");
yield return new TestCaseData(new DateTime(2019, 11, 1), "November");
yield return new TestCaseData(new DateTime(2019, 12, 1), "December");
}
}
}
}
|
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using NodaMoney;
using System;
namespace NHibernate.NodaMoney.Tests.TestDomain
{
public class Order
{
public virtual Guid Id { get; set; }
public virtual Money OrderValue { get; set; }
public virtual Money OrderValueEUR { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Xlns.BusBook.Core.Model;
namespace Xlns.BusBook.UI.Web.Models
{
public class UtenteView
{
public List<DettaglioUtenteView> Utente { get; set; }
public String SearchString { get; set; }
public String Iniziale { get; set; }
public UtenteView(List<Utente> utentiOriginali, String s, String ini)
{
Utente = new List<DettaglioUtenteView>();
SearchString = s;
Iniziale = ini;
foreach (var u in utentiOriginali)
{
Utente.Add(new DettaglioUtenteView(u, s));
}
}
}
} |
using FuncionariosAPIService.Models;
using System;
using System.Linq;
namespace FuncionariosAPIService.Services
{
public class FuncionariosSeguranca
{
public static bool Login(string login, string senha)
{
using (FuncionarioDBContext entities = new FuncionarioDBContext())
{
return entities.Usuarios.Any(user =>
user.Login.Equals(login, StringComparison.OrdinalIgnoreCase)
&& user.Senha == senha);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace alg
{
public static class Extensions
{
public static long ElapsedMilliseconds(Action action, int loopCount = 1)
{
var watch = Stopwatch.StartNew();
for (int i = 0; i < loopCount; i++)
action();
watch.Stop();
return watch.ElapsedMilliseconds;
}
public static bool SameSet<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
if (a == null && b == null) return true;
if (a == null || b == null) return false;
var dict = new Dictionary<T, int>();
foreach (var t in a)
{
if (!dict.ContainsKey(t)) dict.Add(t, 1);
else dict[t]++;
}
foreach (var t in b)
{
if (!dict.ContainsKey(t)) return false;
if (--dict[t] == 0) dict.Remove(t);
}
return dict.Count == 0;
}
public static bool SameSet2<T>(this IEnumerable<IEnumerable<T>> a, IEnumerable<IEnumerable<T>> b)
{
if (a == null && b == null) return true;
if (a == null || b == null) return false;
var al = a.ToList();
var bl = b.ToList();
al.Sort((i, j) => i.Compare(j, Comparer<T>.Default));
bl.Sort((i, j) => i.Compare(j, Comparer<T>.Default));
var comp = Comparer<IEnumerable<T>>.Create((i, j) => i.Compare(j, Comparer<T>.Default));
return al.Compare(bl, comp) == 0;
}
public static bool SameSquare<T>(this T[,] a, T[,] b)
{
if (a == null && b == null) return true;
if (a == null || b == null) return false;
if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1)) return false;
var comparer = Comparer<T>.Default;
var ia = a.GetEnumerator();
var ib = b.GetEnumerator();
ia.Reset();
ib.Reset();
while (ia.MoveNext())
{
if (!ib.MoveNext()) return false;
int c = comparer.Compare((T)ia.Current, (T)ib.Current);
if (c != 0) return false;
}
return ib.MoveNext() ? false : true;
}
public static int Compare<T>(this IEnumerable<T> a, IEnumerable<T> b, IComparer<T> comparer)
{
if (a == null && b == null) return 0;
if (a == null) return -1;
if (b == null) return 1;
using (var ia = a.GetEnumerator())
using (var ib = b.GetEnumerator())
{
while (ia.MoveNext())
{
if (!ib.MoveNext()) return 1;
int c = comparer.Compare(ia.Current, ib.Current);
if (c != 0) return c;
}
return ib.MoveNext() ? -1 : 0;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// instanitiate the Card Prefab, contains all info about a card
namespace SA
{
public class CardInstance : MonoBehaviour, IClikable
{
public void OnClick()
{
}
public void OnHighlight()
{
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ScriptKit
{
public class JsDataView : JsObject
{
internal JsDataView(IntPtr value)
{
this.Value = value;
}
public JsDataView(JsArrayBuffer arrayBuffer) : this(arrayBuffer, 0, (uint)arrayBuffer.Length)
{
}
public JsDataView(JsArrayBuffer jsArrayBuffer, uint byteOffset, uint byteLength)
{
if (jsArrayBuffer == null)
{
throw new ArgumentNullException(nameof(jsArrayBuffer));
}
IntPtr dataView = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsCreateDataView(jsArrayBuffer.Value, byteOffset, byteLength, out dataView);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
this.Value = dataView;
}
private uint length;
private IntPtr buffer;
private Stream stream;
public unsafe Stream Stream
{
get
{
this.EnsureStorage();
if (this.stream == null)
{
this.stream = new UnmanagedMemoryStream((byte*)this.buffer.ToPointer(), this.length);
}
return this.stream;
}
}
private void EnsureStorage()
{
if (this.buffer==IntPtr.Zero)
{
JsErrorCode jsErrorCode = NativeMethods.JsGetDataViewStorage(this.Value, out this.buffer, out length);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stratego
{
class Node
{
public Tuple<int, int> Position { get; set; }
int Alpha { get; set; }
int Beta { get; set; }
private List<Node> childs;
public Node(int v, List<Node> childrens)
{
//Value = v;
childs = childrens;
}
public Node()
{
childs = new List<Node>();
}
public List<Node> getChildrens()
{return childs;}
public void addChild(Node child)
{
childs.Add(child);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SeparatorData : MonoBehaviour
{
void Start()
{
Text txt = GameObject.Find("SeparatorRecordTxt").GetComponent<Text>();
txt.text = "Puntaje obtenido: " + Repository.separatorMaxScore;
}
}
|
using System.Windows.Controls;
namespace ServiceCenter.View.Repair
{
public partial class PageOrderWork : Page
{
public PageOrderWork()
{
InitializeComponent();
}
}
}
|
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed partial class VlcManager
{
[Obsolete("Use GetAudioOutputDeviceList instead")]
public int GetAudioOutputDeviceCount(string outputName)
{
using (var outputNameHandle = Utf8InteropStringConverter.ToUtf8StringHandle(outputName))
{
return myLibraryLoader.GetInteropDelegate<GetAudioOutputDeviceCount>().Invoke(myVlcInstance, outputNameHandle);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FocusWendigo : MonoBehaviour {
public Transform wendigo;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
this.transform.LookAt(wendigo);
}
}
|
using System;
public class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.DayOfWeek);
Console.WriteLine(DateTime.Now.TimeOfDay);
}
} |
using System;
namespace Charity_Campaign
{
class Program
{
static void Main(string[] args)
{
int numberOfDays = int.Parse(Console.ReadLine());
int numberOfBakers = int.Parse(Console.ReadLine());
int numberOfCakesPerDay = int.Parse(Console.ReadLine());
int numberOfWafflesPerDay = int.Parse(Console.ReadLine());
int numberOfPancakesPerDay = int.Parse(Console.ReadLine());
double sumOfMoney = numberOfDays * numberOfBakers * ((numberOfCakesPerDay * 45) + (numberOfPancakesPerDay * 3.20) + (numberOfWafflesPerDay * 5.80));
double sumAfterTax = sumOfMoney - (sumOfMoney / 8);
Console.WriteLine($"{sumAfterTax:f2}");
}
}
}
|
namespace Sentry.Internal;
internal interface ICloneable<out T>
{
T Clone();
}
|
using System;
using System.Threading.Tasks;
namespace CC.Mobile.Services
{
public interface IAdministrationService
{
void EnsureCorrectStartup();
Task RefreshControlData();
Task LoadAppData();
void RemoveAllData();
void DropAllTables();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
namespace CateringWeb.Controllers
{
/// <summary>
/// 站点扩展接口
/// </summary>
public class WebApiController : Controller
{
/// <summary>
/// 附件上传
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult AjaxUpload()
{
HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet);
MD5 md5Hasher = new MD5CryptoServiceProvider();
/*计算指定Stream对象的哈希值*/
byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream);
/*由以连字符分隔的十六进制对构成的String,其中每一对表示value中对应的元素;例如“F-2C-4A”*/
string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", "");
string FileEextension = Path.GetExtension(files[0].FileName);
string uploadDate = DateTime.Now.ToString("yyyyMMdd");
string virtualPath = string.Format("/upload/{0}/{1}{2}", uploadDate, strHashData, FileEextension);
string fullFileName = Server.MapPath(virtualPath);
//创建文件夹,保存文件
string path = Path.GetDirectoryName(fullFileName);
Directory.CreateDirectory(path);
if (!System.IO.File.Exists(fullFileName))
{
files[0].SaveAs(fullFileName);
}
string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\\") - 1);
string fileSize = GetFileSize(files[0].ContentLength);
return Json(new { filename = fileName, filepath =virtualPath, filesize = fileSize }, "text/html", JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 获取文件大小
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
private string GetFileSize(long bytes)
{
long kblength = 1024;
long mbLength = 1024 * 1024;
if (bytes < kblength)
return bytes.ToString() + "B";
if (bytes < mbLength)
return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() + "KB";
else
return decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() + "MB";
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog.Layouts;
namespace HPSM_FTS
{
public class Generator
{
private readonly NLog.ILogger Log;
public Generator(NLog.ILogger logger)
{
this.Log = logger;
}
public DataMain LoadData(string filename, bool filterGroup)
{
this.Log.Trace("Загрузка данных");
var Incendent_table = Task.Run(
() =>
{
var excel = new ExcelUtillite(this.Log);
Dictionary<string, ExcelUtillite.TableIner> table_list
= excel.LoadExcelAllTable(
PathExcel: filename,
column_indexs_check_row: new int[] { 1, 2 },
countemptyrow: 50,
max_count_column: 15,
WorksheetNames: new HashSet<string> { "Лист1" });
List<Incendent> list = new List<Incendent>();
foreach (var table_rasp_ip in table_list)
{
foreach (var item in table_rasp_ip.Value.Row)
{
Incendent i = new Incendent();
i.ENC = item[0].ToString();
i.Opened = (DateTime)item[1];
i.WorkGroup = item[4].ToString();
i.Applicant = item[8].ToString();
i.Closed = item[9] == null ? (DateTime?)null : ((DateTime)item[9]);
string sPriority = item[11] == null ? null : item[11].ToString();
if (string.IsNullOrEmpty(sPriority))
{
i.Priority = EPriority.Обычный;
}
else if (sPriority.ToLower() == "обычный")
{
i.Priority = EPriority.Обычный;
}
else if (sPriority.ToLower() == "важный")
{
i.Priority = EPriority.Важный;
}
else if (sPriority.ToLower() == "высокий")
{
i.Priority = EPriority.Высокий;
}
else if (sPriority.ToLower() == "требуется вмешательство более квалифицированного специалиста")
{
i.Priority = EPriority.Требуется_вмешательство_более_квалифицированного_специалиста;
}
else
i.Priority = EPriority.Обычный;
//throw new Exception(string.Format("Неизвестный тип приоритета = \"{0}\", ИНЦ = {1}", sPriority, i.ENC));
i.ВидРаботы = item.Length <=13 || item[13] == null ? null : item[13].ToString();
i.Описание = item[7].ToString();
i.Решение = item[10] == null ? null : item[10].ToString();
i.Subsystem = item[4].ToString();
if (filterGroup && !(i.Subsystem == "ОДСИПЕАИСТОГПДС" ||
i.Subsystem == "АСВДТО"))
continue;
list.Add(i);
}
}
this.Log.Trace(string.Format("Загружено инцидентов {0}", list.Count));
return list;
}
);
var DicNetName_table = Task.Run(
() =>
{
var list = new Dictionary<string, NetName>();
string FullName = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), Properties.Settings.Default.FileNameDicNetName);
foreach (var itemRow in System.IO.File.ReadAllLines(FullName))
{
if (string.IsNullOrEmpty(itemRow))
continue;
string[] columnvalue = itemRow.Split(';');
if (columnvalue.Length < 6)
continue;
string name = columnvalue[3].Trim();
if (list.ContainsKey(name.ToLower()))
continue;
NetName i = new NetName();
i.PCName = columnvalue[0].Trim();
i.IP = columnvalue[1].Trim();
i.Text1 = columnvalue[2];
i.NameUser = name;
i.Date1 = columnvalue[4];
i.Text1 = columnvalue[5];
list.Add(i.NameUser.ToLower(), i);
}
this.Log.Trace(string.Format("Загружено сетевых устройств {0}", list.Count));
return list;
}
);
var DicContact_table = Task.Run(
() =>
{
var excel = new ExcelUtillite(this.Log);
Dictionary<string, ExcelUtillite.TableIner> table_list = excel.LoadExcelAllTable(
PathExcel: System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), Properties.Settings.Default.FilaNameDicContact),
column_indexs_check_row: new int[] { 1 },
countemptyrow: 1,
max_count_column: 8,
WorksheetNames: new HashSet<string> { "Выгрузка контактов" });
var list = new Dictionary<string, Contact>();
foreach (var table_rasp_ip in table_list)
{
foreach (var item in table_rasp_ip.Value.Row)
{
Contact i = new Contact();
i.Name = item[0].ToString().Trim();
if (!item[1].ToString().Contains("NULL"))
i.Phone = item[1].ToString().Trim();
i.Email = item[2].ToString().Trim();
i.Tite = item[3].ToString().Trim();
if (!item[4].ToString().Contains("NULL"))
i.Address1 = item[4].ToString().Trim();
else
i.Address1 = string.Empty;
if (!item[5].ToString().Contains("NULL"))
i.Address2 = item[5].ToString().Trim();
else
i.Address2 = string.Empty;
i.Dept_Name = item[6].ToString().Trim();
list.Add(i.Name.ToLower(), i);
}
}
this.Log.Trace(string.Format("Загружено контактов {0}", list.Count));
return list;
});
Task.WaitAll(Incendent_table, DicContact_table, DicNetName_table);
return new DataMain()
{
Incendent = Incendent_table.GetAwaiter().GetResult(),
Contactlist = DicContact_table.GetAwaiter().GetResult(),
NetNameList = DicNetName_table.GetAwaiter().GetResult()
};
}
public class Setting
{
public bool GeneratorDistributionIPAddresses { get; set; }
}
private static Random rnd = new Random();
public static int BeginWorkHours = 9;
public static int EndWorkHours = 18;
public DateTime GeneratorTimeEnd(DateTime begin, int minutes_min, int minutes_max)
{
var endday = new DateTime(begin.Year, begin.Month, begin.Day, EndWorkHours, 0, 0);
var toend = endday.Subtract(begin);
int minute_toend = (int)toend.TotalMinutes;
int addminutes = (int)(rnd.Next((toend.TotalMinutes < minutes_min )? (int)toend.TotalMinutes : minutes_min, minute_toend > minutes_max ? minutes_max : minute_toend));
return begin.AddMinutes(addminutes);
}
public DateTime GeneratorTimeBegin(DateTime end, int minutes_min, int minutes_max)
{
var beginday = new DateTime(end.Year, end.Month, end.Day, BeginWorkHours, 0, 0);
var tobegin = end.Subtract(beginday);
int minute_tobegin = (int)tobegin.TotalMinutes;
int addminutes = (int)(rnd.Next((minute_tobegin < minutes_min) ? (int)minute_tobegin : minutes_min, minute_tobegin > minutes_max ? minutes_max : minute_tobegin));
return end.AddMinutes(-addminutes);
}
public DateTime GeneratorDateTimeEnd(DateTime begin, int minutes_min, int minutes_max)
{
DateTime MaxDateTime = begin.AddMinutes(minutes_max);
DateTime MinDateTime = begin.AddMinutes(minutes_min);
if (MaxDateTime.Hour < BeginWorkHours) // Первод на предедушкий день
{
DateTime DateTime_ = MaxDateTime.AddDays(-1);
DateTime_ = new DateTime(MaxDateTime.Year, MaxDateTime.Month, MaxDateTime.Day, EndWorkHours, 0, 0);
var gap = DateTime_.Subtract(MaxDateTime);
minutes_max -= (int)gap.TotalMinutes;
MaxDateTime = DateTime_;
}
if (MaxDateTime.Hour > EndWorkHours) // Первод конец дня
{
DateTime DateTime_ = new DateTime(MaxDateTime.Year, MaxDateTime.Month, MaxDateTime.Day, EndWorkHours, 0, 0);
var gap = MaxDateTime.Subtract(DateTime_);
minutes_max -= (int)gap.TotalMinutes;
MaxDateTime = DateTime_;
}
if (MinDateTime.Hour > EndWorkHours)
{
DateTime DateTime_ = MaxDateTime.AddDays(1);
DateTime_ = new DateTime(MaxDateTime.Year, MaxDateTime.Month, MaxDateTime.Day, EndWorkHours, 0, 0);
var gap = MaxDateTime.Subtract(MaxDateTime);
minutes_min -= (int)gap.TotalMinutes;
MinDateTime = DateTime_;
}
DateTime dtRnd = begin;
do
{
int minute = rnd.Next(minutes_min, minutes_max);
dtRnd = begin.AddMinutes(minute);
}
while (dtRnd.Hour < BeginWorkHours || dtRnd.Hour > EndWorkHours);
//если поподаеть выходные все переносим на понедельник
if (dtRnd.DayOfWeek >= DayOfWeek.Saturday)
dtRnd = dtRnd.AddDays(2);
return dtRnd;
}
public DateTime GeneratorDateTimeBegin(DateTime Closed, int minutes_min, int minutes_max)
{
return Closed.AddMinutes(-27);
//DateTime MaxDateTime = Closed.AddMinutes(minutes_max);
//DateTime MinDateTime = Closed.AddMinutes(minutes_min);
//if (MaxDateTime.Hour < BeginWorkHours) // Первод на предедушкий день
//{
// DateTime DateTime_ = MaxDateTime.AddDays(-1);
// DateTime_ = new DateTime(MaxDateTime.Year, MaxDateTime.Month, MaxDateTime.Day, EndWorkHours, 0, 0);
// var gap = DateTime_.Subtract(MaxDateTime);
// minutes_max -= (int)gap.TotalMinutes;
// MaxDateTime = DateTime_;
//}
//if (MaxDateTime.Hour > EndWorkHours) // Первод конец дня
//{
// DateTime DateTime_ = new DateTime(MaxDateTime.Year, MaxDateTime.Month, MaxDateTime.Day, EndWorkHours, 0, 0);
// var gap = MaxDateTime.Subtract(DateTime_);
// minutes_max -= (int)gap.TotalMinutes;
// MaxDateTime = DateTime_;
//}
//if (MinDateTime.Hour > EndWorkHours)
//{
// DateTime DateTime_ = MaxDateTime.AddDays(1);
// DateTime_ = new DateTime(MaxDateTime.Year, MaxDateTime.Month, MaxDateTime.Day, EndWorkHours, 0, 0);
// var gap = MaxDateTime.Subtract(MaxDateTime);
// minutes_min -= (int)gap.TotalMinutes;
// MinDateTime = DateTime_;
//}
//DateTime dtRnd = begin;
//do
//{
// int minute = rnd.Next(minutes_min, minutes_max);
// dtRnd = begin.AddMinutes(minute);
//}
//while (dtRnd.Hour < BeginWorkHours || dtRnd.Hour > EndWorkHours);
////если поподаеть выходные все переносим на понедельник
//if (dtRnd.DayOfWeek >= DayOfWeek.Saturday)
// dtRnd = dtRnd.AddDays(2);
//return Closed;
}
public DateTime GeneratorClosed(DateTime Opened, EPriority priority)
{
if (priority == EPriority.Обычный)
{
return GeneratorDateTimeEnd(Opened, 1 * 60, 24 * 60);
}
else if (priority == EPriority.Важный)
{
return GeneratorTimeEnd(Opened, 15, (int)(2.5 * 60));
}
else if (priority == EPriority.Высокий)
{
return GeneratorTimeEnd(Opened, 15, 60);
}
else if (priority == EPriority.Требуется_вмешательство_более_квалифицированного_специалиста)
{
return GeneratorDateTimeEnd(Opened, 24 * 60, 48 * 60);
}
else throw new Exception("Приоритет не указан");
}
public DateTime GeneratorOpened(DateTime Closed, EPriority priority)
{
if (priority == EPriority.Обычный)
{
return GeneratorDateTimeBegin(Closed, 1 * 60, 24 * 60);
}
else if (priority == EPriority.Важный)
{
return GeneratorTimeBegin(Closed, 15, (int)(2.5 * 60));
}
else if (priority == EPriority.Высокий)
{
return GeneratorTimeBegin(Closed, 15, 60);
}
else if (priority == EPriority.Требуется_вмешательство_более_квалифицированного_специалиста)
{
return GeneratorDateTimeEnd(Closed, 24 * 60, 48 * 60);
}
else throw new Exception("Приоритет не указан");
}
public bool IsValideClosedOpened(DateTime Opened, DateTime Closed, EPriority priority)
{
if (priority == EPriority.Обычный)
{
int max = (int)(24 * 60);
if (Opened.DayOfWeek == DayOfWeek.Friday)
max += 24 * 2 * 60;
return Closed.Subtract(Opened).TotalMinutes < max;
}
else if (priority == EPriority.Важный)
{
int max = (int)(2.5 * 60);
return Closed.Subtract(Opened).TotalMinutes < max;
}
else if (priority == EPriority.Высокий)
{
int max = 60;
return Closed.Subtract(Opened).TotalMinutes < max;
}
else if (priority == EPriority.Требуется_вмешательство_более_квалифицированного_специалиста)
{
int max = (int)(48 * 60);
if (Opened.DayOfWeek == DayOfWeek.Friday)
max += 24 * 2 * 60;
return Closed.Subtract(Opened).TotalMinutes < max;
}
return false;
}
public List<Report2> Report2(DataMain datalist)
{
List<Report2> res = new List<Report2>();
List<Phase> PhaseList = new List<Phase>();
PhaseList.Add(new Phase(1, new DateTime(2018, 12, 28), new DateTime(2019, 3, 01)));
PhaseList.Add(new Phase(2, new DateTime(2019, 3, 01), new DateTime(2019, 6, 01)));
PhaseList.Add(new Phase(3, new DateTime(2019, 6, 01), new DateTime(2019, 9, 01)));
PhaseList.Add(new Phase(4, new DateTime(2019, 9, 01), new DateTime(2019, 12, 11)));
PhaseList.Add(new Phase(5, new DateTime(2019, 12, 11), new DateTime(2020, 3, 01)));
PhaseList.Add(new Phase(6, new DateTime(2020, 3, 01), new DateTime(2020, 6, 01)));
PhaseList.Add(new Phase(7, new DateTime(2020, 6, 01), new DateTime(2020, 9, 01)));
PhaseList.Add(new Phase(8, new DateTime(2020, 9, 01), new DateTime(2020, 12, 11)));
int i = 1;
foreach (Incendent item in datalist.Incendent)
{
Report2 report2 = new Report2()
{
Applicant = item.Applicant,
Opened = item.Opened,
ENC = item.ENC,
Number = i,
ВидРаботы = item.ВидРаботы,
Описание = item.Описание,
Решение = item.Решение,
Priority = item.Priority
};
i++;
report2.Phase = PhaseList.FirstOrDefault(q => q.Begin <= item.Opened && item.Opened < q.End);
if (!string.IsNullOrEmpty(item.Applicant))
{
if (datalist.Contactlist.ContainsKey(report2.Applicant.ToLower()))
{
var c = datalist.Contactlist[report2.Applicant.ToLower()];
report2.Контакт = string.Format("{0}, {1}", c.Address2, c.Phone);
if (report2.Контакт.StartsWith(","))
report2.Контакт = report2.Контакт.Substring(1);
}
else
Log.Warn(string.Format("Контакт для пользователя {0} не найден", report2.Applicant));
string shortName = item.NameLoginOnly.ToLower();
if (!string.IsNullOrEmpty(shortName) && datalist.NetNameList.ContainsKey(shortName))
{
var c = datalist.NetNameList[shortName];
report2.IPAndName = string.Format("{0}/{1}", c.IP, c.PCName);
}
else
Log.Warn(string.Format("Не найдено сетевое устройство для пользователя {0}", report2.Applicant));
}
if (item.Closed == null)
{
report2.Closed = GeneratorClosed(item.Opened, item.Priority);
Log.Trace(string.Format("Инцидент {0} не закрыт", report2.ENC));
}
else if (!IsValideClosedOpened(item.Opened, item.Closed.Value, item.Priority))
{
Log.Trace(string.Format("Инцидент {0}: превышен норматив времени закрытия", report2.ENC));
report2.Opened = GeneratorOpened(item.Closed.Value, item.Priority);
}
if (report2.Closed == DateTime.MinValue)
report2.Closed = item.Closed.Value;
report2.CustomerRepresentative = item.Subsystem == "АСВДТО" ? "Сутягин А.Н." : "Карпунина Т.Н.";
res.Add(report2);
}
return res;
}
public List<Report3> Report3(DataMain datalist)
{
List<Report3> list = new List<Report3>();
foreach (var item in datalist.Incendent.GroupBy(q => q.ВидРаботы))
{
list.Add(new Report3()
{
ViewWork = item.Key,
IncendentCount = item.Count(),
Prochent = ((double)item.Count()) / datalist.Incendent.Count
});
}
return list;
}
public Report1Result Report1(List<Report2> Incendents)
{
var list = new Report1Result();
foreach (var item in Incendents.GroupBy(q => q.OpenedDateString))
{
string Date = item.Key;
int C = item.Count();
if (list.ContainsKey(Date))
list[Date].OpenedCount += C;
else
list[Date] = new Report1Data() { OpenedCount = C };
}
foreach (var item in Incendents.GroupBy(q => q.ClosedDateString))
{
if (string.IsNullOrEmpty(item.Key))
continue;
string Date = item.Key;
int C = item.Count();
if (list.ContainsKey(Date))
list[Date].ClosedCount += C;
else
list[Date] = new Report1Data() { ClosedCount = C };
}
return list;
}
public DataResult Run(DataMain datalist, Setting setting)
{
this.Log.Trace("Процесс обработки");
try
{
DataResult ret = new DataResult();
ret.Report2 = Report2(datalist);
ret.Report2 = Report2(datalist).OrderBy(i=>i.Opened).ToList();
// перенумерация
int number = 1;
foreach (var item in ret.Report2)
{
item.Number = number;
number++;
}
ret.Report2 = ret.Report2.OrderBy(i => i.Number).ToList();
ret.Report1 = Report1(ret.Report2);
ret.Report3 = Report3(datalist);
this.Log.Trace("Процесс заверщен");
return ret;
}
catch (Exception ex)
{
this.Log.Trace(string.Format("Ошибка: {0}", ex.Message));
throw;
}
}
}
}
|
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace seleniumLib
{
public class WebDriverFactory
{
/* Browsers constants */
public const String CHROME = "chrome";
public const String FIREFOX = "firefox";
public const String SAFARI = "safari";
public const String INTERNET_EXPLORER = "ie";
/* Platform constants */
public const String MAC = "mac";
public const String LINUX = "linux";
public const String WINDOWS = "windows";
public WebDriverFactory()
{
}
public static IWebDriver getInstance(String gridHubUrl, Browser browser, String username, String password)
{
IWebDriver webDriver = null;
DesiredCapabilities capability = new DesiredCapabilities();
String browserName = browser.Name;
capability.IsJavaScriptEnabled = true;
// In case there is no Hub
if (gridHubUrl == null || gridHubUrl.Length == 0)
{
return getInstance(gridHubUrl, browser, username, password);
}
}
}
}
|
using MixErp.Data;
using MixErp.Fonksiyonlar;
using MixErp.Print;
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;
namespace MixErp.Urun
{
public partial class frmUrunAlis : Form
{
// 2. işlem: global alana db bağlantısı ve gerekli olacak property ve field larımızı ekleriz. Word wrap ı unutma :D
MixErpDbEntities db = new MixErpDbEntities();
//3. işlem: Numaralar sınıfında gerekli metodu oluştur.
Numaralar N = new Numaralar();
int secimId = -1;
bool edit = false;
// 9. işlem
int UrnAlisId = -1;
public string[] MyArray { get; set; }
public frmUrunAlis()
{
InitializeComponent();
}
private void frmUrunAlis_Load(object sender, EventArgs e)
{
// 1. işlem: Load event i oluşturulur.
// 4. işlem: Numaralar sınıfında oluşturduğum metodu burada ilgili textbox için çalıştır
txtAlisGrupNo.Text = N.AlisGrupNo();
// 5. işlem: combobox lar için combo adında metot yaz ve bunu generate et.
Combo();
}
private void Combo()
{
// 6. işlem: Cari adları için autocomplate özelliğini açtığımız bir combobox doldurma yöntemi
txtCari.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtCari.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
AutoCompleteStringCollection veri = new AutoCompleteStringCollection();
var lst = db.tblCaris.Select(x => x.CariAdi).Distinct();
foreach (var cari in lst)
{
veri.Add(cari);
txtCari.Items.Add(cari);
}
txtCari.AutoCompleteCustomSource = veri;
// 7. işlem: Ödeme tipi için combobox ı doldur.
txtOdeme.DataSource = db.bOdemeTurleris.ToList();
txtOdeme.ValueMember = "Id";
txtOdeme.DisplayMember = "OdemeTipi";
// 8. işlem:
var srg = db.tblUrunlers.Select(x => x.UrunKodu);
foreach (var k in srg)
{
txtUKod.Items.Add(k);
}
// 10. işlem
int dgv;
dgv = txtUKod.Items.Count;
MyArray = new string[dgv];
for (int i = 0; i < dgv; i++)
{
MyArray[i] = txtUKod.Items[i].ToString();
}
}
// 11. işlem
private void liste_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox txt = e.Control as TextBox;
if (liste.CurrentCell.ColumnIndex==0 && txt!=null)
{
txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
txt.AutoCompleteCustomSource.AddRange(MyArray);
}
else if (liste.CurrentCell.ColumnIndex!=0 && txt!=null)
{
txt.AutoCompleteMode = AutoCompleteMode.None;
}
}
// 12. işlem
private void liste_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
string a = liste.CurrentRow.Cells[0].Value.ToString();
var lst = (from s in db.tblUrunlers
where s.UrunKodu == a
select s).First();
liste.CurrentRow.Cells[1].Value = lst.UrunAciklama;
liste.CurrentRow.Cells[2].Value = lst.bBirim.BirimAdi;
}
// 13. işlem
if (e.ColumnIndex==4)
{
if (liste.CurrentRow.Cells[3].Value!=null )
{
RHesapla();
}
}
if (e.ColumnIndex==3)
{
if (liste.CurrentRow.Cells[4].Value!=null )
{
RHesapla();
}
}
}
private void RHesapla()
{
decimal a, b;
decimal atop = 0;
decimal ktop = 0;
decimal gtop = 0;
if (liste.CurrentRow.Cells[3].Value!=null && liste.CurrentRow.Cells[4].Value!=null)
{
a = Convert.ToDecimal(liste.CurrentRow.Cells[3].Value.ToString());
b = Convert.ToDecimal(liste.CurrentRow.Cells[4].Value.ToString());
liste.CurrentRow.Cells[5].Value = a * b * 0.18M; // double dan decimal e çevirir.
for (int i = 0; i < liste.RowCount-1; i++)
{
atop += (Convert.ToDecimal(liste.Rows[i].Cells[3].Value) * Convert.ToDecimal(liste.Rows[i].Cells[4].Value));
ktop += Convert.ToDecimal(liste.Rows[i].Cells[5].Value);
}
txtAraToplam.Text = atop.ToString();
txtKdvToplam.Text = ktop.ToString();
gtop = atop + ktop;
txtGenelToplam.Text = gtop.ToString();
}
else
{
MessageBox.Show("Adam gibi bir değer gir");
liste.CurrentRow.Cells[3].Value = "";
}
}
void YeniKaydet()
{
var srch = new tblUrunAlisUst();
srch.AlisGrupNo = txtAlisGrupNo.Text;
srch.AraToplam = Convert.ToDecimal(txtAraToplam.Text);
srch.ATarih = Convert.ToDateTime(txtATarih.Text);
srch.FaturaNo = txtFaturaNo.Text;
srch.CariId = db.tblCaris.First(x => x.CariAdi == txtCari.Text).Id;
srch.Vade = Convert.ToInt32(txtVade.Text);
srch.OdemeId = db.bOdemeTurleris.First(x => x.OdemeTipi == txtOdeme.Text).Id;
srch.KdvToplam = Convert.ToDecimal(txtKdvToplam.Text);
srch.GenelToplam= Convert.ToDecimal(txtGenelToplam.Text);
db.tblUrunAlisUsts.Add(srch);
db.SaveChanges();
liste.AllowUserToAddRows = false;
tblUrunAlisAlt[] ualt = new tblUrunAlisAlt[liste.RowCount];
for (int i = 0; i < liste.RowCount; i++)
{
ualt[i] = new tblUrunAlisAlt();
ualt[i].Miktar = Convert.ToInt32(liste.Rows[i].Cells[4].Value.ToString());
ualt[i].AlisGrupNo = txtAlisGrupNo.Text;
ualt[i].BFiyat = Convert.ToDecimal(liste.Rows[i].Cells[3].Value.ToString());
string brm = liste.Rows[i].Cells[2].Value.ToString();
ualt[i].BirimId = db.bBirims.First(x => x.BirimAdi == brm).Id;
string urn = liste.Rows[i].Cells[1].Value.ToString();
ualt[i].UrunId = db.tblUrunlers.First(x => x.UrunAciklama == urn).Id;
ualt[i].AToplam = Convert.ToDecimal(liste.Rows[i].Cells[3].Value) * Convert.ToDecimal(liste.Rows[i].Cells[4].Value);
ualt[i].Kdv = Convert.ToDecimal(liste.Rows[i].Cells[5].Value);
db.tblUrunAlisAlts.Add(ualt[i]);
string uBarkod = liste.Rows[i].Cells[0].Value.ToString() + "/" + liste.Rows[i].Cells[1].Value.ToString();
var sKontrol = db.tblStokDurums.First(x => x.Barkod == uBarkod);
decimal obFiyat;
decimal ETopObFiyat;
decimal YTopObFiyat;
if (sKontrol.OBFiyat==null)
{
obFiyat = 0;
ETopObFiyat = 0;
}
else
{
obFiyat = sKontrol.OBFiyat.Value;
ETopObFiyat = obFiyat * sKontrol.Depo.Value;
}
YTopObFiyat = (Convert.ToDecimal(liste.Rows[i].Cells[3].Value) * Convert.ToInt32(liste.Rows[i].Cells[4].Value));
decimal TopEYFiyat = ETopObFiyat + YTopObFiyat;
int EAdet = sKontrol.Depo.Value;
int YAdet = Convert.ToInt32(liste.Rows[i].Cells[4].Value);
int TopEYAdet = EAdet + YAdet;
decimal SonucBFiyat = TopEYFiyat / TopEYAdet;
sKontrol.Ambar += 0;
sKontrol.Depo += Convert.ToInt32(liste.Rows[i].Cells[4].Value);
sKontrol.Raf += Convert.ToInt32(liste.Rows[i].Cells[4].Value);
sKontrol.OBFiyat = SonucBFiyat;
}
db.SaveChanges();
MessageBox.Show("Başarıyla kaydedildi.");
}
void Guncelle()
{
var srch = db.tblUrunAlisUsts.First(x => x.AlisGrupNo == txtAlisGrupNo.Text);
srch.AlisGrupNo = txtAlisGrupNo.Text;
srch.AraToplam = Convert.ToDecimal(txtAraToplam.Text);
srch.ATarih = Convert.ToDateTime(txtATarih.Text);
srch.FaturaNo = txtFaturaNo.Text;
srch.CariId = db.tblCaris.First(x => x.CariAdi == txtCari.Text).Id;
srch.Vade = Convert.ToInt32(txtVade.Text);
srch.OdemeId = db.bOdemeTurleris.First(x => x.OdemeTipi == txtOdeme.Text).Id;
srch.KdvToplam = Convert.ToDecimal(txtKdvToplam.Text);
db.SaveChanges();
liste.AllowUserToAddRows = false;
tblUrunAlisAlt[] ualt = new tblUrunAlisAlt[liste.RowCount];
for (int i = 0; i < liste.RowCount; i++)
{
var altId = Convert.ToInt32(liste.Rows[i].Cells[6].Value);
ualt[i] = db.tblUrunAlisAlts.First(x => x.AlisGrupNo == txtAlisGrupNo.Text && x.Id==altId);
ualt[i].Miktar = Convert.ToInt32(liste.Rows[i].Cells[4].Value.ToString());
ualt[i].AlisGrupNo = txtAlisGrupNo.Text;
ualt[i].BFiyat = Convert.ToDecimal(liste.Rows[i].Cells[3].Value.ToString());
string brm = liste.Rows[i].Cells[2].Value.ToString();
ualt[i].BirimId = db.bBirims.First(x => x.BirimAdi == brm).Id;
string urn = liste.Rows[i].Cells[1].Value.ToString();
ualt[i].UrunId = db.tblUrunlers.First(x => x.UrunAciklama == urn).Id;
ualt[i].AToplam = Convert.ToDecimal(liste.Rows[i].Cells[3].Value) * Convert.ToDecimal(liste.Rows[i].Cells[4].Value);
ualt[i].Kdv = Convert.ToDecimal(liste.Rows[i].Cells[5].Value);
}
db.SaveChanges();
MessageBox.Show("Başarıyla güncellendi.");
}
private void btnKaydet_Click(object sender, EventArgs e)
{
if (edit && UrnAlisId>0)
{
Guncelle();
}
else if (!edit)
{
YeniKaydet();
}
}
protected override void OnLoad(EventArgs e) // Buraya yazılan kod bir kontrolümün üzerine yazılarak onu değiştirecek.
{
var btnUrunAlisNo = new Button();
btnUrunAlisNo.Size = new Size(25, txtAlisGrupNo.ClientSize.Height + 2);
btnUrunAlisNo.Location = new Point(txtAlisGrupNo.ClientSize.Width - btnUrunAlisNo.Width, -1);
btnUrunAlisNo.Cursor = Cursors.Default;
btnUrunAlisNo.Image = Properties.Resources.arrow_curved_red_right;
btnUrunAlisNo.Anchor = (AnchorStyles.Top | AnchorStyles.Right);
txtAlisGrupNo.Controls.Add(btnUrunAlisNo);
base.OnLoad(e);
btnUrunAlisNo.Click += btnUrunAlisNo_Click;
}
Formlar F = new Formlar();
private void btnUrunAlisNo_Click(object sender, EventArgs e)
{
int id = F.UrunAlisNo(true);
if (id>0)
{
Ac(id);
}
frmAnasayfa.AktarmaInt = -1;
}
private void Ac(int id)
{
edit = true;
UrnAlisId = id;
string ustNo = id.ToString().PadLeft(7, '0');
tblUrunAlisUst ust = db.tblUrunAlisUsts.First(x => x.AlisGrupNo == ustNo);
txtAlisGrupNo.Text = ust.AlisGrupNo;
txtAraToplam.Text = ust.AraToplam.ToString();
txtATarih.Text = ust.ATarih.ToString();
txtCari.Text = ust.tblCari.CariAdi;
txtFaturaNo.Text = ust.FaturaNo;
txtGenelToplam.Text = ust.GenelToplam.ToString();
txtKdvToplam.Text = ust.KdvToplam.ToString();
txtOdeme.Text = ust.bOdemeTurleri.OdemeTipi;
txtVade.Text = ust.Vade.ToString();
liste.Rows.Clear();
liste.AllowUserToAddRows = false;
var alt = (from s in db.tblUrunAlisAlts
where s.AlisGrupNo == ustNo
select s).ToList();
int i = 0;
foreach (var k in alt)
{
liste.Rows.Add();
liste.Rows[i].Cells[0].Value = k.tblUrunler.UrunKodu;
liste.Rows[i].Cells[1].Value = k.tblUrunler.UrunAciklama;
liste.Rows[i].Cells[2].Value = k.bBirim.BirimAdi;
liste.Rows[i].Cells[3].Value = k.BFiyat;
liste.Rows[i].Cells[4].Value = k.Miktar;
liste.Rows[i].Cells[5].Value = k.Kdv;
liste.Rows[i].Cells[6].Value = k.Id;
i++;
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
Yaz();
}
private void Yaz()
{
frmPrint pr = new frmPrint();
pr.GrupNo = txtAlisGrupNo.Text;
pr.HangiListe = "UrunAlis";
pr.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using CommonServiceLocator;
using Microsoft.AppCenter;
using Welic.App.Services.ServicesViewModels;
using Welic.App.Services.ServiceViews;
using Unity;
using Unity.ServiceLocation;
using Welic.App.Services.Navigation;
using Welic.App.Services.Timing;
using Xamarin.Forms;
namespace Welic.App.ViewModels.Base
{
class ViewModelLocator
{
private static UnityContainer _container;
public static readonly BindableProperty AutoWireViewModelProperty =
BindableProperty.CreateAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), default(bool), propertyChanged: OnAutoWireViewModelChanged);
public static bool GetAutoWireViewModel(BindableObject bindable)
{
return (bool)bindable.GetValue(ViewModelLocator.AutoWireViewModelProperty);
}
public static void SetAutoWireViewModel(BindableObject bindable, bool value)
{
bindable.SetValue(ViewModelLocator.AutoWireViewModelProperty, value);
}
public static bool UseMockService { get; set; }
static ViewModelLocator()
{
_container = new UnityContainer();
// View models - by default, TinyIoC will register concrete classes as multi-instance.
_container.RegisterType<AboutViewModel>();
_container.RegisterType<AspectFillLiveViewModel>();
_container.RegisterType<ConfigViewModel>();
_container.RegisterType<CourseDetailViewModel>();
_container.RegisterType<CreateCoursesViewModel>();
_container.RegisterType<CreateEbookViewModel>();
_container.RegisterType<CreateLiveViewModel>();
_container.RegisterType<CreateScheduleViewModel>();
_container.RegisterType<EbookViewModel>();
_container.RegisterType<EditProfileViewModel>();
_container.RegisterType<GaleryViewModel>();
_container.RegisterType<HomeViewModel>();
_container.RegisterType<InicioViewModel>();
_container.RegisterType<ListEBookViewModel>();
_container.RegisterType<ListEventsViewModel>();
_container.RegisterType<ListLiveViewModel>();
_container.RegisterType<ListNewsViewModel>();
_container.RegisterType<ListOfCoursesViewModel>();
_container.RegisterType<ListScheduleViewModel>();
_container.RegisterType<LiveViewModel>();
_container.RegisterType<LoginExternoViewModel>();
_container.RegisterType<LoginViewModel>();
_container.RegisterType<MainViewModel>();
_container.RegisterType<MenuViewModel>();
_container.RegisterType<NewsViewModel>();
_container.RegisterType<RegisterViewModel>();
_container.RegisterType<ScheduleDetailViewModel>();
_container.RegisterType<SearchViewModel>();
// Services - by default, TinyIoC will register interface registrations as singletons.
_container.RegisterType<INavigationService, NavigationService>();
_container.RegisterType<IMessageService, MessageServices>();
_container.RegisterType<IOpenUrlService, OpenUrlService>();
_container.RegisterType<IIdentityService, IdentityService>();
_container.RegisterType<IRequestProvider, RequestProvider>();
_container.RegisterType<IDependencyService, Welic.App.Services.ServiceViews.DependencyService>();
_container.RegisterType<ISettingsService, SettingsService>();
_container.RegisterType<ILocationService, LocationService>();
_container.RegisterType<ITiming, Timing>();
var unityServiceLocator = new UnityServiceLocator(_container);
ServiceLocator.SetLocatorProvider((() => unityServiceLocator));
}
public static void UpdateDependencies(bool useMockServices)
{
// Change injected dependencies
if (useMockServices)
{
UseMockService = true;
}
else
{
UseMockService = false;
}
}
public static void RegisterSingleton<TInterface, T>() where TInterface : class where T : class, TInterface
{
_container.RegisterSingleton<TInterface, T>();
}
public static T Resolve<T>() where T : class
{
try
{
return _container.Resolve<T>();
}
catch (System.Exception e)
{
Console.WriteLine(e);
return null;
}
}
private static void OnAutoWireViewModelChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as Element;
if (view == null)
{
return;
}
var viewType = view.GetType();
var viewName = viewType.FullName.Replace(".Views.", ".ViewModels.");
var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
var viewModelName = string.Format(CultureInfo.InvariantCulture, "{0}Model, {1}", viewName, viewAssemblyName);
var viewModelType = Type.GetType(viewModelName);
if (viewModelType == null)
{
return;
}
var viewModel = _container.Resolve(viewModelType);
view.BindingContext = viewModel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Challan.Models
{
public class Currency
{
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public double Taka { get; set; }
public double Poisa { get; set; }
//navigation
public virtual ChallanPrinciple Challan { get; set; }
}
} |
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.AuditLogs.Factories.Implementation;
using Fingo.Auth.Domain.AuditLogs.Factories.Interfaces;
using Fingo.Auth.Domain.AuditLogs.Implementation;
using Fingo.Auth.Domain.AuditLogs.Interfaces;
using Moq;
using Xunit;
namespace Fingo.Auth.Domain.AuditLogs.Tests.Factories
{
public class GetAllAuditLogFactoryTest
{
[Fact]
public void GetAllAuditLogFactory_Should_Return_Instance_Of_GetAllAuditLog_Given_By_IGetAllAuditLog()
{
//Arrange
var auditLogRepository = new Mock<IAuditLogRepository>();
var userRepositoryMock = new Mock<IUserRepository>();
//Act
IGetAllAuditLogFactory target = new GetAllAuditLogFactory(auditLogRepository.Object ,
userRepositoryMock.Object);
var result = target.Create();
//Assert
Assert.NotNull(result);
Assert.IsType<GetAllAuditLog>(result);
Assert.IsAssignableFrom<IGetAllAuditLog>(result);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class raycastForward : MonoBehaviour {
/*
* https://www.youtube.com/watch?v=6agwCUaMNWI
*/
public GameObject CanvasObject;
public Text text;
// Use this for initialization
void Start () {
PlayerPrefs.SetString("BuildingName","John");
text.text = "";
//CanvasObject.SetActive(false);
}
// Update is called once per frame
void Update () {
RaycastHit hit;
float theDistance;
// This is the debug raycast to make life easier
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position,forward,Color.green);
if (Physics.Raycast(transform.position, (forward), out hit)) {
theDistance = hit.distance;
//print(theDistance + " " + hit.collider.gameObject.name);
if (theDistance < 1.1)
{
CanvasObject.SetActive(true);
//PlayerPrefs.SetString("BuildingName", gameObject.name);
if (hit.collider.gameObject.name == "Hotel")
{
text.text = "Do you want to enter the " + hit.collider.gameObject.name;
print("Do you want to enter the " + hit.collider.gameObject.name);
}
// Interact with object
if (Input.GetKeyDown(KeyCode.UpArrow))
{
print("You are now in the " + hit.collider.gameObject.name);
}
}
else
{
CanvasObject.SetActive(false);
}
}
}
}
|
using Parser.Models;
namespace Parser.Nodes
{
public class VarNode : INode
{
public VarModel Variable { get; set; }
}
} |
using ScheduleService.DTO;
using System.Collections.Generic;
using System.Linq;
namespace ScheduleService.Services.AdvancedSearchStrategy
{
public class TimeHasPriorityStrategy : IAdvancedSearchStrategy
{
private BasicSearchDTO SearchDTO { get; }
private ICollection<string> PotentiallyAvailableDoctors { get; }
public TimeHasPriorityStrategy(BasicSearchDTO searchDTO, ICollection<string> potentiallyAvailableDoctors)
{
SearchDTO = searchDTO;
PotentiallyAvailableDoctors = potentiallyAvailableDoctors;
}
public BasicSearchDTO GetSearchParameters()
{
if (PotentiallyAvailableDoctors.Count > 0)
{
SearchDTO.DoctorJmbg = PotentiallyAvailableDoctors.FirstOrDefault();
PotentiallyAvailableDoctors.Remove(SearchDTO.DoctorJmbg);
return SearchDTO;
}
return null;
}
}
}
|
using UnityEngine;
/// <summary>
/// An instance of background music. Supports
/// fading-in and fading-out.
/// </summary>
public class BackgroundMusic : MonoBehaviour
{
/// <summary>
/// The actual audio to play for the background music.
/// </summary>
public AudioSource Music = null;
/// <summary>
/// The minimum volume for the music. When fading out,
/// the music will fade out to this volume.
/// </summary>
public float MinVolume = 0.0f;
/// <summary>
/// The maximum volume for the music. When fading in,
/// the music will fade in to this volume.
/// </summary>
public float MaxVolume = 1.0f;
/// <summary>
/// How fast the volume increases when fading in.
/// </summary>
public float VolumeIncreasePerSecond = 0.5f;
/// <summary>
/// How fast the volume decreases when fading out.
/// </summary>
public float VolumeDecreasePerSecond = 0.5f;
/// <summary>
/// If the music is currently being faded in.
/// </summary>
private bool m_isFadingIn = false;
/// <summary>
/// If the music is currently being faded out.
/// </summary>
private bool m_isFadingOut = false;
/// <summary>
/// Starts playing the background music.
/// </summary>
public void StartPlaying()
{
// Only start playing the music if it isn't already playing.
// We don't want duplicate instances of the music playing.
if (!Music.isPlaying)
{
Music.Play();
}
}
/// <summary>
/// Stops playing the background music.
/// </summary>
public void StopPlaying()
{
Music.Stop();
}
/// <summary>
/// Starts fading in the background music over time.
/// </summary>
public void StartFadeIn()
{
// Make sure that fading in and out don't interfere
// with each other.
m_isFadingOut = false;
// Even if the music is already fading in, toggle the
// flag indicating that it is fading in to allow it
// to continue to fade in if necessary. Otherwise,
// a scenario could occur where the background music
// stops entirely.
m_isFadingIn = true;
}
/// <summary>
/// Starts fading out the background music over time.
/// </summary>
public void StartFadeOut()
{
// Make sure that fading in and out don't interfere
// with each other.
m_isFadingIn = false;
// Start fading out the music. This flag will
// trigger the update loop to fade out the
// music volume and then ultimately pause
// the music.
m_isFadingOut = true;
}
/// <summary>
/// Fades the music in by increasing its volume.
/// </summary>
private void FadeIn()
{
// CHECK IF THE VOLUME HAS REACHED ITS MAXIMUM LEVEL.
bool maxVolumeReached = (Music.volume >= MaxVolume);
if (maxVolumeReached)
{
// This volume doesn't need to be increased any more.
m_isFadingIn = false;
return;
}
// INCREASE THE VOLUME A BIT BASED ON TIME.
Music.volume += VolumeIncreasePerSecond * Time.deltaTime;
}
/// <summary>
/// Fades the music out by decreasing its volume.
/// </summary>
private void FadeOut()
{
// CHECK IF THE VOLUME HAS REACHED ITS MINIMUM LEVEL.
bool minVolumeReached = (Music.volume <= MinVolume);
if (minVolumeReached)
{
// This volume doesn't need to be decreased any more,
// so go ahead and stop fading out.
m_isFadingOut = false;
return;
}
// DECREASE THE VOLUME A BIT BASED ON TIME.
Music.volume -= VolumeDecreasePerSecond * Time.deltaTime;
}
/// <summary>
/// Updates the volume of the music depending on
/// if playing of the music is fading in or out.
/// </summary>
private void Update()
{
if (m_isFadingIn)
{
FadeIn();
}
else if (m_isFadingOut)
{
FadeOut();
}
}
}
|
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour
{
public static Spawner SpawnerScript;
Hashtable activeCachedObjects;
public ObjectCache []ObjectCaches;
void Awake()
{
// Set the global variable
SpawnerScript = this;
if (GlobalData.GetInstance().gameMode != GameMode.SoloMode) {
return;
}
// Total number of cached objects
int amount = 0;
// Loop through the caches
for (int i = 0; i < ObjectCaches.Length; i++)
{
// Initialize each cache
ObjectCaches[i].Initialize ();
// Count
amount += ObjectCaches[i].cacheSize;
}
// Create a hashtable with the capacity set to the amount of cached objects specified
activeCachedObjects = new Hashtable (amount);
}
public void SpawnNetObj()
{
// if (activeCachedObjects != null) {
// return;
// }
// Total number of cached objects
int amount = 0;
// Loop through the caches
for (int i = 0; i < ObjectCaches.Length; i++)
{
// Initialize each cache
ObjectCaches[i].Initialize ();
// Count
amount += ObjectCaches[i].cacheSize;
}
// Create a hashtable with the capacity set to the amount of cached objects specified
activeCachedObjects = new Hashtable (amount);
}
public static GameObject Spawn(GameObject prefab, Vector3 position, Vector3 forwardVal)
{
ObjectCache cache = null;
// Find the cache for the specified prefab
if(SpawnerScript)
{
for(var i = 0; i < SpawnerScript.ObjectCaches.Length; i++)
{
if(SpawnerScript.ObjectCaches[i].prefab == prefab)
{
cache = SpawnerScript.ObjectCaches[i];
}
}
}
// If there's no cache for this prefab type, just instantiate normally
if(cache == null)
{
float coneAngle = 1.5f;
Quaternion coneRandomRotation = Quaternion.Euler(Random.Range (-coneAngle, coneAngle), Random.Range (-coneAngle, coneAngle), 0);
return (GameObject)Instantiate(prefab, position, coneRandomRotation);
}
// Find the next object in the cache
GameObject obj = cache.GetNextObjectInCache();
// Set the position and rotation of the object
obj.transform.position = position;
obj.transform.forward = forwardVal;
// Set the object to be active
obj.SetActive (true);
SpawnerScript.activeCachedObjects[obj] = true;
return obj;
}
public static void HiddenCacheObj(GameObject prefab)
{
if (prefab == null) {
return;
}
ObjectCache cache = null;
// Find the cache for the specified prefab
if(SpawnerScript)
{
for(var i = 0; i < SpawnerScript.ObjectCaches.Length; i++)
{
if(SpawnerScript.ObjectCaches[i].prefab == prefab)
{
cache = SpawnerScript.ObjectCaches[i];
break;
}
}
}
if (cache != null) {
cache.HiddenAllObj();
}
}
public static void DestroyObj (GameObject objectToDestroy)
{
if(SpawnerScript && SpawnerScript.activeCachedObjects.ContainsKey(objectToDestroy))
{
objectToDestroy.SetActive (false);
SpawnerScript.activeCachedObjects[objectToDestroy] = false;
}
else
{
Destroy(objectToDestroy);
}
}
}
|
using UnityEngine;
using System.Collections;
using System;
public class Library : State<MainController>
{
public override void Configure(MainController owner)
{
base.Configure(owner);
}
public override void GlobalProcess()
{
throw new NotImplementedException();
}
public override void OnEnter()
{
throw new NotImplementedException();
}
public override void OnExit()
{
throw new NotImplementedException();
}
public override void Process()
{
throw new NotImplementedException();
}
}
|
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Bounce.Controls;
using Bounce.Services;
using Plugin.Media;
using Plugin.Media.Abstractions;
using Xamarin.Forms;
namespace Bounce.Pages
{
public class BallsPage : ContentPage
{
private const string TAKE_PHOTO = "Take a photo";
private const string CHOOSE_PHOTO = "Choose a photo";
private const string CANCEL = "Cancel";
private const string BALLS_DIR = "Balls";
private App App { get { return ((App)Application.Current); } }
private string _ballsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), BALLS_DIR);
private ObservableCollection<BallItem> _ballItems = null;
public BallsPage()
{
BindingContext = this;
Title = "Balls";
ToolbarItem cameraTBI = new ToolbarItem {
Icon = "camera"
};
cameraTBI.Clicked += async (object sender, EventArgs e) => {
string choice = await DisplayActionSheet("Photo Option", CANCEL, null, TAKE_PHOTO, CHOOSE_PHOTO);
if ((string.IsNullOrWhiteSpace(choice)) || (choice == CANCEL))
return;
await Task.Delay(TimeSpan.FromSeconds(0.5));
await CrossMedia.Current.Initialize();
MediaFile photo = null;
if (choice == TAKE_PHOTO) {
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) {
await DisplayAlert("Error", "Cannot access camera", "Close");
return;
}
photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { RotateImage = false });
} else {
if (!CrossMedia.Current.IsPickPhotoSupported) {
await DisplayAlert("Error", "Cannot access photo library", "Close");
return;
}
photo = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions { RotateImage = false });
}
if (photo == null)
return;
byte[] imgData;
using (MemoryStream ms = new MemoryStream()) {
await photo.GetStream().CopyToAsync(ms);
imgData = ms.ToArray();
}
IImageProcessor imageProcessor = null;
#if __ANDROID__
imageProcessor = new Bounce.Droid.Services.DroidImageProcessor();
#else
imageProcessor = new Bounce.iOS.Services.iOSImageProcessor();
#endif
imgData = await imageProcessor.NormalizeAsync(imgData, 0.8f);
imgData = await imageProcessor.ResizeAsync(imgData, 500, 500, 0.8f);
Console.WriteLine(_ballsDir);
Directory.CreateDirectory(_ballsDir);
string ballFilename = Path.Combine(_ballsDir, Guid.NewGuid().ToString());
using (FileStream fs = new FileStream(ballFilename, FileMode.CreateNew)) {
await fs.WriteAsync(imgData, 0, imgData.Length);
}
_ballItems.Add(new BallItem { Filename = ballFilename });
BallEditPage bep = new BallEditPage(ballFilename);
bep.BallImageUpdated += HandleBallImageUpdated;
await Navigation.PushAsync(bep);
};
ToolbarItems.Add(cameraTBI);
BackgroundColor = AppStyle.Balls.BACKGROUND_COLOR;
_ballItems = new ObservableCollection<BallItem>();
_ballItems.Add(new BallItem { IsSelected = string.IsNullOrWhiteSpace(App.BallFilename) });
Directory.CreateDirectory(_ballsDir);
foreach (string ballFile in Directory.GetFiles(_ballsDir)) {
string ballFilename = Path.Combine(_ballsDir, ballFile);
_ballItems.Add(new BallItem { Filename = ballFilename, IsSelected = App.BallFilename == ballFilename });
}
DataTemplate it = new DataTemplate(typeof(BallItemCell));
ListView listV = new ListView {
BackgroundColor = AppStyle.Balls.LIST_BACKGROUND_COLOR,
ItemsSource = _ballItems,
ItemTemplate = it,
RowHeight = AppStyle.Balls.LIST_ITEM_HEIGHT
};
listV.ItemTapped += (object sender, ItemTappedEventArgs e) => {
BallItem selItem = (BallItem)e.Item;
if (!selItem.IsSelected) {
App.BallFilename = selItem.Filename;
foreach (BallItem bi in _ballItems) {
if (bi.IsSelected) {
bi.IsSelected = false;
break;
}
}
selItem.IsSelected = true;
}
listV.SelectedItem = null;
App.SetDetailPage(MenuItemType.Play);
};
Content = listV;
}
private void HandleBallImageUpdated(object sender, string ballFilename)
{
//Find ball item that matches ballFilename
foreach (BallItem bi in _ballItems) {
if (bi.Filename == ballFilename) {
//Force an update by calling filename setter
bi.Filename = ballFilename;
break;
}
}
}
}
public class BallItem : INotifyPropertyChanged
{
private string _filename = null;
public string Filename {
get { return (_filename); }
set {
_filename = value;
OnPropertyChanged();
}
}
private bool _isSelected = false;
public bool IsSelected {
get { return (_isSelected); }
set {
_isSelected = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using System;
using System.Web.Mvc;
using DevExpress.XtraScheduler;
using DevExpress.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class SchedulerController: DemoController {
public ActionResult Reminders() {
return DemoView("Reminders", SchedulerDataHelper.EditableDataObject);
}
public ActionResult RemindersPartial() {
if (Request["CreateAppointment"] != null && bool.Parse(Request["CreateAppointment"]))
AddNewAppointmentWithReminder();
return PartialView("RemindersPartial", SchedulerDataHelper.EditableDataObject);
}
public ActionResult RemindersPartialEditAppointment() {
try {
SchedulerDataHelper.UpdateEditableDataObject();
}
catch (Exception e) {
ViewData["SchedulerErrorText"] = e.Message;
}
return PartialView("RemindersPartial", SchedulerDataHelper.EditableDataObject);
}
void AddNewAppointmentWithReminder() {
EditableSchedule schedule = CreateAppointmentWithReminders();
try {
CarsDataProvider.InsertSchedule<EditableSchedule>(schedule);
}
catch (Exception e) {
ViewData["SchedulerErrorText"] = e.Message;
}
}
EditableSchedule CreateAppointmentWithReminders() {
Appointment appointment = new Appointment(AppointmentType.Normal);
appointment.Start = DateTime.Now + TimeSpan.FromMinutes(5) + TimeSpan.FromSeconds(5);
appointment.Duration = TimeSpan.FromHours(2);
appointment.Subject = "Appointment with Reminder";
appointment.HasReminder = true;
appointment.Reminder.TimeBeforeStart = TimeSpan.FromMinutes(5);
appointment.ResourceId = Resource.Empty;
appointment.StatusId = (int)AppointmentStatusType.Busy;
appointment.LabelId = 1;
return SchedulerExtension.ConvertAppointment<EditableSchedule>(appointment, SchedulerDemoHelper.DefaultAppointmentStorage);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
using Guard;
namespace Panel
{
public partial class Validation : Form
{
/*
* CONSTRUCTOR
*/
public Validation()
{
InitializeComponent();
}
//DECLARATIONS
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
//CHECK_REGISTRY
private void doProjects()
{
RegistryKey keyCheck = null;
try
{
keyCheck = Registry.CurrentUser.OpenSubKey(@"Software\NEET\Projects");
}
catch (Exception) { keyCheck = null; }
if (keyCheck != null)
return;
else
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\NEET\Projects");
}
}
private string regUser()
{
string user = null;
try
{
user = Registry.GetValue(@"HKEY_CURRENT_USER\Software\NEET\Profile", "User", Microsoft.Win32.RegistryValueKind.String).ToString();
}
catch (Exception) { user = "null_user"; }
return user;
}
//INITIALIZE_MAIN_THREAD
private void Validation_Load(object sender, EventArgs e)
{
//REGISTRY_VARS
doProjects();
string user = regUser();
if (user != "null_user")
Username.Text = user;
//TOOLTIP
toolTip1.SetToolTip(Username, "Username Field");
toolTip1.SetToolTip(Password, "Pass Phrase Field");
toolTip1.SetToolTip(Login, "Log Into Panel Portal");
toolTip1.SetToolTip(Exit_Button, "Exit Panel Form");
toolTip1.SetToolTip(Minimize, "Minimize Panel Form");
//BEGIN_FADE
Fade.RunWorkerAsync();
}
//DRAGGING
private void Drag(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void bar_MouseDown(object sender, MouseEventArgs e)
{
Drag(e);
}
//FADE_THREAD_CONTROL
private void Fade_DoWork(object sender, DoWorkEventArgs e)
{
while (this.Opacity != 100)
{
this.Opacity += 0.03;
Thread.Sleep(10);
}
}
//DRAW_BORDERS
private void Validation_Paint(object sender, PaintEventArgs e)
{
//FORM_BORDER
Color colorBorder = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(34)))));
Rectangle rect = new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1);
e.Graphics.DrawRectangle(new Pen(new SolidBrush(colorBorder), 3), rect);
//INNER_BORDER
InBorder(e);
}
//INNER_BORDER
private void InBorder(PaintEventArgs e)
{
GraphicsPath gP = new GraphicsPath();
Rectangle R = new Rectangle(Main.Location, Main.Size);
R.Inflate(1, 1);
gP.AddRectangle(R);
float Falloff = (R.Height + R.Width) / 10;
float Vdiff = Falloff / R.Height;
float Hdiff = Falloff / R.Width;
PathGradientBrush PGBrush = new PathGradientBrush(gP);
PGBrush.CenterColor = Color.FromArgb(187,187,187);
PGBrush.SurroundColors = new Color[] { Color.FromArgb(187,187,187) };
PGBrush.SetSigmaBellShape(1);
PGBrush.FocusScales = new PointF(1.5F - Hdiff, 1.5F - Vdiff);
e.Graphics.FillRectangle(PGBrush, R);
}
//EXIT_MINIMIZE
private void Exit_Tick(object sender, EventArgs e)
{
this.Exit.Enabled = false;
while (this.Opacity != 0)
{
this.Opacity -= 0.03;
Thread.Sleep(20);
}
try
{
Application.Exit();
}
catch (Exception) { }
}
private void Exit_Button_Click(object sender, EventArgs e)
{
if ((MessageBox.Show("Would You Like To Exit The Panel?", "Panel . Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) == DialogResult.Yes)
Exit.Enabled = true;
}
private void Minimize_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
//EXIT_CHECK
private void Validation_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
Application.Exit();
}
catch (Exception) { }
}
//LOGO_LINK_CLICK
private void Logo_Click(object sender, EventArgs e)
{
Process.Start("http://forum.neetgroup.net");
}
//USER_PASSWORD_FIELDS
private void Username_Click(object sender, EventArgs e)
{
if (Username.Text.Equals("Username"))
Username.Text = "";
}
private void Password_Click(object sender, EventArgs e)
{
if (Password.Text.Equals("Password"))
Password.Text = "";
}
//GUARD_SERVER_LOGIN
private void saveUser(string user)
{
RegistryKey keyCheck = null;
try
{
keyCheck = Registry.CurrentUser.OpenSubKey(@"Software\NEET\Profile");
}
catch (Exception) { keyCheck = null; }
if (keyCheck != null) {
keyCheck.Close();
try
{
Registry.SetValue(@"HKEY_CURRENT_USER\Software\NEET\Profile", "User", user, Microsoft.Win32.RegistryValueKind.String);
}
catch (Exception) { }
}
else
{
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\NEET\Profile");
key.Close();
Registry.SetValue(@"HKEY_CURRENT_USER\Software\NEET\Profile", "User", user, Microsoft.Win32.RegistryValueKind.String);
}
catch (Exception) { }
}
}
private void doLogin() {
string user = Username.Text;
string phrase = Password.Text;
if (user.Length >= 3)
{
Program._User = new User (user, phrase);
if (!string.IsNullOrEmpty(Program._User.Profile.username))
{
MessageBox.Show("Guard Login Successful", "Panel . Dialog", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
saveUser(user);
Home home = new Home();
home.Show();
this.Hide();
return;
}
}
else
MessageBox.Show("Invalid Username Length", "Panel . Dialog", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void CheckEnter(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
doLogin();
}
}
private void Login_Click(object sender, EventArgs e)
{
doLogin();
}
//MISC_PANEL_ACTIONS
private void Shop_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if ((MessageBox.Show("Proceed To Guard Shop?", "Panel . Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) == DialogResult.Yes)
{
try
{
Process.Start("http://forum.neetgroup.net");
}
catch (Exception) { }
}
else
MessageBox.Show("Operation Cancelled", "Panel . Dialog", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
private void Register_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if ((MessageBox.Show("Proceed To Guard Registration?", "Panel . Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) == DialogResult.Yes)
{
try
{
Process.Start("http://guard.neetgroup.net/?app=register");
}
catch (Exception) { }
}
else
MessageBox.Show("Operation Cancelled", "Panel . Dialog", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace CacheSqlXmlService.SqlManager
{
[XmlRoot(ElementName ="dataCommandFiles")]
public class DataCommandFileList
{
public class DataCommandFile
{
[XmlAttribute("name")]
public string FileName
{
get;
set;
}
}
[XmlElement("file")]
public DataCommandFileList.DataCommandFile[] FileList
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Dojodachi.Models;
namespace Dojodachi.Controllers
{
public class DojodachiController : Controller
{
private void setDachiSession(Dachi dachi = null)
{
if (dachi == null)
{
dachi = new Dachi();
HttpContext.Session.SetString("newGame", "true");
}
HttpContext.Session.SetInt32("happiness", dachi.Happiness);
HttpContext.Session.SetInt32("fullness", dachi.Fullness);
HttpContext.Session.SetInt32("energy", dachi.Energy);
HttpContext.Session.SetInt32("meals", dachi.Meals);
}
private Dachi getDachiFromSession()
{
return new Dachi
(
HttpContext.Session.GetInt32("happiness"),
HttpContext.Session.GetInt32("fullness"),
HttpContext.Session.GetInt32("energy"),
HttpContext.Session.GetInt32("meals")
);
}
[HttpGet("")]
public IActionResult Index()
{
if (HttpContext.Session.GetString("newGame") == null)
{
setDachiSession();
}
return View(getDachiFromSession());
}
[HttpGet("game/{gameType}")]
public IActionResult Play(string gameType)
{
Dachi currDachi = getDachiFromSession();
TempData["message"] = currDachi.Play(gameType);
setDachiSession(currDachi);
return RedirectToAction("Index");
}
[HttpGet("restart")]
public IActionResult Restart()
{
HttpContext.Session.Clear();
return RedirectToAction("Index");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GM : MonoBehaviour {
public CapsuleCollider m_Collider;
private float col_scale;
public static float vertVel = 0;
public static int coinTotal = 0;
public static int bananaTotal = 0;
public static int watermelonTotal = 0;
public static float timeTotal = 0;
public float waittoload = 0;
public static float zScenePos = 4;
public static float zVelAdj = 1;
public static string lvlCompStatus = "";
public Transform bbNoPit;
public Transform bbPitMid;
public Transform Coin;
public Transform obstObj;
public Transform rock01;
public Transform rock02;
public Transform capsuleObj;
public Transform blockTreePath;
public Terrain terrain;
public Transform Avocado;
public Transform Banana;
public Transform Burger;
public Transform Chips_Bag;
public Transform Coconut;
public Transform Donut;
public Transform Fries;
public Transform HotDog;
public Transform Mushroom;
public Transform Onion;
public Transform Pepper;
public Transform Pineapple;
public Transform Pizza;
public Transform Tacos;
public Transform Tomato;
public Transform Watermelon;
public Transform Wine_Bottle;
public Transform Log01;
public int randNum;
public int randNumPath;
public int totalCollectibles;
public int coinLTotal;
public int coinRTotal;
public int bananaLTotal;
public int bananaRTotal;
public int watermelonLTotal;
public int watermelonRTotal;
public Transform player;
private List<Transform> activeTiles ;
private float safeZone = 15f;
// Use this for initialization
void Start () {
activeTiles = new List<Transform>();
col_scale = PlayerPrefs.GetFloat("sensivityCollectibles");
m_Collider.height = col_scale/40;
m_Collider.radius = col_scale/40;
totalCollectibles = 0;
coinLTotal = 0;
coinRTotal = 0;
bananaLTotal = 0;
bananaRTotal = 0;
watermelonLTotal = 0;
watermelonRTotal = 0;
if (PlayerPrefs.HasKey("Coin")) {
totalCollectibles += PlayerPrefs.GetInt("Coin");
coinLTotal += PlayerPrefs.GetInt("Coin");
}
if (PlayerPrefs.HasKey("CoinR")) {
totalCollectibles += PlayerPrefs.GetInt("CoinR");
coinRTotal += PlayerPrefs.GetInt("CoinR");
}
if (PlayerPrefs.HasKey("Banana")) {
totalCollectibles += PlayerPrefs.GetInt("Banana");
bananaLTotal = PlayerPrefs.GetInt("Banana") ;
}
if (PlayerPrefs.HasKey("BananaR")) {
totalCollectibles += PlayerPrefs.GetInt("BananaR");
bananaRTotal = PlayerPrefs.GetInt("BananaR") ;
}
if (PlayerPrefs.HasKey("Watermelon")) {
totalCollectibles += PlayerPrefs.GetInt("Watermelon");
watermelonLTotal = PlayerPrefs.GetInt("Watermelon") ;
}
if (PlayerPrefs.HasKey("WatermelonR")) {
totalCollectibles += PlayerPrefs.GetInt("WatermelonR");
watermelonRTotal = PlayerPrefs.GetInt("WatermelonR") ;
}
if (PlayerPrefs.HasKey("Heart"))
totalCollectibles += PlayerPrefs.GetInt("Heart");
if (PlayerPrefs.HasKey("HeartR"))
totalCollectibles += PlayerPrefs.GetInt("HeartR");
zScenePos = 4;
Debug.Log(totalCollectibles);
}
// Update is called once per frame
void Update () {
timeTotal += Time.deltaTime;
float difference = zScenePos - player.position.z;
if (difference < 100)
{
randNum = Random.Range(0, 100); //likelihood of event to happen ex. if 1<x<5 do this if 5<x<6 do this.
randNumPath = Random.Range(0, 5);
if (randNum < 10 && randNum > 5) {
if (PlayerPrefs.HasKey("Coin") && coinLTotal != 0) {
totalCollectibles = totalCollectibles - 1;
coinLTotal = coinLTotal -1 ;
Instantiate(Coin, new Vector3(-1, 1, zScenePos), Coin.rotation);
}
}
if (randNum < 5 ) {
if (PlayerPrefs.HasKey("CoinR") && coinRTotal != 0) {
totalCollectibles = totalCollectibles - 1;
coinRTotal = coinRTotal -1 ;
Instantiate(Coin, new Vector3(1, 1, zScenePos), Coin.rotation);
}
}
if (randNum >10 && randNum <13)
{
Instantiate(Log01, new Vector3(-1, 1, zScenePos), Log01.rotation);
}
if (randNum > 13 && randNum < 23) {
Instantiate(rock02, new Vector3(1, 1, zScenePos), rock02.rotation);
}
if (randNum >23 && randNum < 33)
{
if (PlayerPrefs.HasKey("Banana") && bananaLTotal != 0) {
totalCollectibles = totalCollectibles - 1;
bananaLTotal = bananaLTotal -1 ;
Instantiate(Banana, new Vector3(-1, 1, zScenePos), Banana.rotation);
}
}
if (randNum >33 && randNum < 43)
{
if (PlayerPrefs.HasKey("BananaR") && bananaRTotal != 0) {
totalCollectibles = totalCollectibles - 1;
bananaRTotal = bananaRTotal -1 ;
Instantiate(Banana, new Vector3(1, 1, zScenePos), Banana.rotation);
}
}
if (randNum >45 && randNum < 63)
{
if (PlayerPrefs.HasKey("Watermelon") && watermelonLTotal != 0) {
totalCollectibles = totalCollectibles - 1;
watermelonLTotal = watermelonLTotal -1 ;
Instantiate(Watermelon, new Vector3(-1, 1, zScenePos), Watermelon.rotation);
}
}
if (randNum >63 && randNum < 73)
{
if (PlayerPrefs.HasKey("WatermelonR") && watermelonRTotal != 0) {
totalCollectibles = totalCollectibles - 1;
watermelonRTotal = watermelonRTotal -1 ;
Instantiate(Watermelon, new Vector3(1, 1, zScenePos), Watermelon.rotation);
}
}
if (randNum > 75 && randNum < 80 )
{
Instantiate(rock01, new Vector3(0, 1, zScenePos), rock01.rotation);
}
if (randNum >80 && randNum <90)
{
Instantiate(Log01, new Vector3(1, 1, zScenePos), Log01.rotation);
}
if (randNum > 90 && randNum < 100) {
Instantiate(rock02, new Vector3(-1, 1, zScenePos), rock02.rotation);
}
if (randNumPath < 4){
Transform tile = Instantiate(blockTreePath, new Vector3(0, 0, zScenePos), blockTreePath.rotation);
activeTiles.Add(tile);
} else {
Transform tile = Instantiate(bbPitMid, new Vector3(0, 0, zScenePos), bbPitMid.rotation);
activeTiles.Add(tile);
}
if (player.position.z > safeZone){
DeleteTile();
}
zScenePos += 12;
}
if (lvlCompStatus == "Fail") {
waittoload += Time.deltaTime;
}
if (waittoload > 5) {
Debug.Log("LevelComp accessed");
SceneManager.LoadScene("LevelComp");
}
}
private void DeleteTile (){
Destroy (activeTiles [0].gameObject);
activeTiles.RemoveAt(0);
}
}
|
namespace TaskMaster.Models
{
/// <summary>
/// Information about page.
/// </summary>
public class PageInfo
{
#region Public Constructors
/// <summary>
/// Creates page info object.
/// </summary>
public PageInfo() { }
/// <summary>
/// Creates page info object.
/// </summary>
/// <param name="pageNumber">Number of page.</param>
/// <param name="elementsOnPage">Count of elements on page.</param>
public PageInfo(int pageNumber, int elementsOnPage)
{
PageNumber = pageNumber;
ElementsOnPage = elementsOnPage;
}
#endregion Public Constructors
#region Public Properties
/// <summary>
/// Count of elements of page.
/// </summary>
public int ElementsOnPage { get; set; } = 20;
/// <summary>
/// Page number.
/// </summary>
public int PageNumber { get; set; } = 1;
#endregion Public Properties
#region Public Methods
/// <summary>
/// Returns count of pages.
/// </summary>
/// <param name="elementsCount">Count of elements.</param>
/// <returns>Count of pages.</returns>
public int GetPagesCount(int elementsCount)
{
return elementsCount / ElementsOnPage + (elementsCount % ElementsOnPage > 0 ? 1 : 0);
}
#endregion Public Methods
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NNSharp.DataTypes;
using NNSharp.SequentialBased.SequentialLayers;
using static NNSharp.DataTypes.Data2D;
using NNSharp.IO;
using NNSharp.Models;
namespace UnitTests
{
[TestClass]
public class TestAvgPool2D
{
[TestMethod]
public void Test_AvgPool2D_Execute()
{
// Initialize data.
Data2D data = new Data2D(3, 3, 2, 1);
data[0, 0, 0, 0] = 2;
data[1, 0, 0, 0] = 1;
data[2, 0, 0, 0] = 1;
data[0, 1, 0, 0] = 1;
data[1, 1, 0, 0] = 4;
data[2, 1, 0, 0] = 2;
data[0, 2, 0, 0] = 1;
data[1, 2, 0, 0] = 2;
data[2, 2, 0, 0] = 0;
data[0, 0, 1, 0] = 3;
data[1, 0, 1, 0] = 6;
data[2, 0, 1, 0] = 8;
data[0, 1, 1, 0] = 5;
data[1, 1, 1, 0] = 2;
data[2, 1, 1, 0] = 4;
data[0, 2, 1, 0] = 1;
data[1, 2, 1, 0] = 4;
data[2, 2, 1, 0] = 2;
AvgPool2DLayer pool = new AvgPool2DLayer(0, 0, 1, 1, 2, 2);
pool.SetInput(data);
pool.Execute();
Data2D output = pool.GetOutput() as Data2D;
// Checking sizes
Dimension dim = output.GetDimension();
Assert.AreEqual(dim.b, 1);
Assert.AreEqual(dim.c, 2);
Assert.AreEqual(dim.h, 2);
Assert.AreEqual(dim.w, 2);
// Checking calculation
Assert.AreEqual(output[0, 0, 0, 0], 2.0, 0.0000001);
Assert.AreEqual(output[1, 0, 0, 0], 2.0, 0.0000001);
Assert.AreEqual(output[0, 1, 0, 0], 2.0, 0.0000001);
Assert.AreEqual(output[1, 1, 0, 0], 2.0, 0.0000001);
Assert.AreEqual(output[0, 0, 1, 0], 4.0, 0.0000001);
Assert.AreEqual(output[1, 0, 1, 0], 5.0, 0.0000001);
Assert.AreEqual(output[0, 1, 1, 0], 3.0, 0.0000001);
Assert.AreEqual(output[1, 1, 1, 0], 3.0, 0.0000001);
}
[TestMethod]
[ExpectedException(typeof(System.Exception))]
public void Test_AvgPool2D_Null_Input()
{
Data2D data = null;
AvgPool2DLayer pool = new AvgPool2DLayer(1, 1, 1, 1, 2, 2);
pool.SetInput(data);
}
[TestMethod]
[ExpectedException(typeof(System.Exception))]
public void Test_AvgPool2D_DifferentData_Input()
{
DataArray data = new DataArray(5);
AvgPool2DLayer pool = new AvgPool2DLayer(1, 1, 1, 1, 2, 2);
pool.SetInput(data);
}
[TestMethod]
public void Test_AvgPool2D_1_KerasModel()
{
string path = @"tests\test_avgpool_2D_1_model.json";
var reader = new ReaderKerasModel(path);
SequentialModel model = reader.GetSequentialExecutor();
Data2D inp = new Data2D(4, 5, 2, 1);
inp[0, 0, 0, 0] = 0;
inp[0, 0, 1, 0] = 1;
inp[0, 1, 0, 0] = 2;
inp[0, 1, 1, 0] = 1;
inp[0, 2, 0, 0] = 0;
inp[0, 2, 1, 0] = 0;
inp[0, 3, 0, 0] = 2;
inp[0, 3, 1, 0] = 1;
inp[0, 4, 0, 0] = 2;
inp[0, 4, 1, 0] = 1;
inp[1, 0, 0, 0] = 0;
inp[1, 0, 1, 0] = -1;
inp[1, 1, 0, 0] = 1;
inp[1, 1, 1, 0] = -2;
inp[1, 2, 0, 0] = 3;
inp[1, 2, 1, 0] = 1;
inp[1, 3, 0, 0] = 2;
inp[1, 3, 1, 0] = 0;
inp[1, 4, 0, 0] = 2;
inp[1, 4, 1, 0] = -3;
inp[2, 0, 0, 0] = 1;
inp[2, 0, 1, 0] = 2;
inp[2, 1, 0, 0] = -2;
inp[2, 1, 1, 0] = 0;
inp[2, 2, 0, 0] = 3;
inp[2, 2, 1, 0] = -3;
inp[2, 3, 0, 0] = 2;
inp[2, 3, 1, 0] = 1;
inp[2, 4, 0, 0] = 2;
inp[2, 4, 1, 0] = 0;
inp[3, 0, 0, 0] = 1;
inp[3, 0, 1, 0] = 2;
inp[3, 1, 0, 0] = 0;
inp[3, 1, 1, 0] = -2;
inp[3, 2, 0, 0] = 3;
inp[3, 2, 1, 0] = 1;
inp[3, 3, 0, 0] = 2;
inp[3, 3, 1, 0] = 3;
inp[3, 4, 0, 0] = -3;
inp[3, 4, 1, 0] = 1;
Data2D ou = model.ExecuteNetwork(inp) as Data2D;
Assert.AreEqual(ou.GetDimension().c, 2);
Assert.AreEqual(ou.GetDimension().w, 2);
Assert.AreEqual(ou.GetDimension().h, 2);
Assert.AreEqual(ou[0, 0, 0, 0], 1.1666666269302368, 0.0001);
Assert.AreEqual(ou[0, 0, 1, 0], 0.0833333358168602, 0.0001);
Assert.AreEqual(ou[0, 1, 0, 0], 1.5833333730697632, 0.0001);
Assert.AreEqual(ou[0, 1, 1, 0], -0.25, 0.0001);
Assert.AreEqual(ou[1, 0, 0, 0], 1.3333333730697632, 0.0001);
Assert.AreEqual(ou[1, 0, 1, 0], 0.1666666716337204, 0.0001);
Assert.AreEqual(ou[1, 1, 0, 0], 1.25, 0.0001);
Assert.AreEqual(ou[1, 1, 1, 0], -0.25, 0.0001);
}
[TestMethod]
public void Test_AvgPool2D_2_KerasModel()
{
string path = @"tests\test_avgpool_2D_2_model.json";
var reader = new ReaderKerasModel(path);
SequentialModel model = reader.GetSequentialExecutor();
Data2D inp = new Data2D(4, 5, 2, 1);
inp[0, 0, 0, 0] = 0;
inp[0, 0, 1, 0] = 1;
inp[0, 1, 0, 0] = 2;
inp[0, 1, 1, 0] = 1;
inp[0, 2, 0, 0] = 0;
inp[0, 2, 1, 0] = 0;
inp[0, 3, 0, 0] = 2;
inp[0, 3, 1, 0] = 1;
inp[0, 4, 0, 0] = 2;
inp[0, 4, 1, 0] = 1;
inp[1, 0, 0, 0] = 0;
inp[1, 0, 1, 0] = -1;
inp[1, 1, 0, 0] = 1;
inp[1, 1, 1, 0] = -2;
inp[1, 2, 0, 0] = 3;
inp[1, 2, 1, 0] = 1;
inp[1, 3, 0, 0] = 2;
inp[1, 3, 1, 0] = 0;
inp[1, 4, 0, 0] = 2;
inp[1, 4, 1, 0] = -3;
inp[2, 0, 0, 0] = 1;
inp[2, 0, 1, 0] = 2;
inp[2, 1, 0, 0] = -2;
inp[2, 1, 1, 0] = 0;
inp[2, 2, 0, 0] = 3;
inp[2, 2, 1, 0] = -3;
inp[2, 3, 0, 0] = 2;
inp[2, 3, 1, 0] = 1;
inp[2, 4, 0, 0] = 2;
inp[2, 4, 1, 0] = 0;
inp[3, 0, 0, 0] = 1;
inp[3, 0, 1, 0] = 2;
inp[3, 1, 0, 0] = 0;
inp[3, 1, 1, 0] = -2;
inp[3, 2, 0, 0] = 3;
inp[3, 2, 1, 0] = 1;
inp[3, 3, 0, 0] = 2;
inp[3, 3, 1, 0] = 3;
inp[3, 4, 0, 0] = -3;
inp[3, 4, 1, 0] = 1;
Data2D ou = model.ExecuteNetwork(inp) as Data2D;
Assert.AreEqual(ou.GetDimension().c, 2);
Assert.AreEqual(ou.GetDimension().w, 2);
Assert.AreEqual(ou.GetDimension().h, 2);
Assert.AreEqual(ou[0, 0, 0, 0], 1.1666666269302368, 0.0001);
Assert.AreEqual(ou[0, 0, 1, 0], 0.0833333358168602, 0.0001);
Assert.AreEqual(ou[0, 1, 0, 0], 1.5833333730697632, 0.0001);
Assert.AreEqual(ou[0, 1, 1, 0], -0.25, 0.0001);
Assert.AreEqual(ou[1, 0, 0, 0], 1.3333333730697632, 0.0001);
Assert.AreEqual(ou[1, 0, 1, 0], 0.1666666716337204, 0.0001);
Assert.AreEqual(ou[1, 1, 0, 0], 1.25, 0.0001);
Assert.AreEqual(ou[1, 1, 1, 0], -0.25, 0.0001);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootData
{
public readonly GameObject gunObject;
public readonly EquippedGun gunScript;
public readonly bool useRecoil;
public readonly Vector2 centrePoint;
private readonly Camera fpsCamera;
public ShootData(GameObject gunObject, EquippedGun gunScript, bool useRecoil, Vector2 centrePoint, Camera fpsCamera)
{
this.gunObject = gunObject;
this.gunScript = gunScript;
this.useRecoil = useRecoil;
this.centrePoint = centrePoint;
this.fpsCamera = fpsCamera;
}
public void ShootStuff(Vector2 pointToFire)
{
var goalPoint = Vector3.zero;
Ray ray = fpsCamera.ScreenPointToRay(pointToFire);
RaycastHit[] hits = Physics.RaycastAll(ray, 100f);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.red, 100f);
if (hits.Length != 0)
{
goalPoint = hits[hits.Length - 1].point;
}
else
{
// Get a point somehow... god knows how.
}
int notPlayerLayer = ~(1 << LayerMask.NameToLayer("Player"));
Vector3 startPoint = fpsCamera.transform.position; // Figure out a way to set startPoint as gun muzzle
Vector3 bulletDir = (goalPoint - startPoint).normalized;
RaycastHit[] thiccCast = Physics.SphereCastAll(startPoint, 0.1f, bulletDir, 100f, notPlayerLayer);
// Debug.DrawRay(startPoint, bulletDir * 1000, Color.green, 100f);
foreach (RaycastHit hitP in thiccCast)
{
var decal = GameObject.CreatePrimitive(PrimitiveType.Sphere);
decal.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
decal.transform.position = hitP.point;
decal.gameObject.layer = 8;
}
}
} |
using OBS_Net.Entities.Model;
using OBS_Net.Entities.Tables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OBS_Net.BL.LessonForStudentManager
{
public interface ILessonForStudentManager
{
IQueryable<LessonForStudent> GetAll();
LessonForStudent Create(LessonForStudent model);
LessonForStudentModel GetCreateModel();
}
}
|
using System.IO;
using System.Linq;
using Cradiator.Config;
using NUnit.Framework;
using Shouldly;
namespace Cradiator.Tests.Config
{
[TestFixture]
public class ViewConfigReader_Tests
{
ViewSettingsParser _parser;
const string XML = "<configuration>" +
"<views>" +
@"<view url=""http://url1"" " +
@"build-agent-username=""foogo"" " +
@"build-agent-password=""Bargo"" " +
@"skin=""Grid"" " +
@"project-regex=""v5.*"" " +
@"category-regex="".*"" " +
@"server-regex="".*"" " +
@"name=""Scoring"" " +
@"showOnlyBroken=""false"" " +
@"showServerName=""false"" " +
@"showOutOfDate=""false"" " +
@"outOfDateDifferenceInMinutes=""0"" />" +
"</views>" +
"</configuration>";
[SetUp]
public void SetUp()
{
_parser = new ViewSettingsParser(new StringReader(XML));
}
[Test]
public void can_read_view_from_xml()
{
var views = _parser.ParseXml();
views.Count().ShouldBe(1);
var view1 = views.First();
view1.URL.ShouldBe("http://url1");
view1.BuildAgentUsername.ShouldBe("foogo");
view1.BuildAgentPassword.ShouldBe("Bargo");
view1.SkinName.ShouldBe("Grid");
view1.ProjectNameRegEx.ShouldBe("v5.*");
view1.CategoryRegEx.ShouldBe(".*");
}
[Test]
public void can_read_then_write_modified_view_to_xml()
{
var views = _parser.ParseXml();
var xmlModified = _parser.CreateUpdatedXml(new ViewSettings
{
URL = "http://new",
BuildAgentUsername = "go",
BuildAgentPassword = "foo",
ProjectNameRegEx = "[a-z]",
CategoryRegEx = "[1-9]",
SkinName = "StackPhoto",
ServerNameRegEx = "",
OutOfDateDifferenceInMinutes = 1,
ShowOnlyBroken = true,
ShowOutOfDate = true,
ShowServerName = true,
ViewName = "foobar"
});
_parser = new ViewSettingsParser(new StringReader(xmlModified));
views = _parser.ParseXml();
var view1 = views.First();
view1.URL.ShouldBe("http://new");
view1.BuildAgentUsername.ShouldBe("go");
view1.BuildAgentPassword.ShouldBe("foo");
view1.SkinName.ShouldBe("StackPhoto");
view1.ProjectNameRegEx.ShouldBe("[a-z]");
view1.CategoryRegEx.ShouldBe("[1-9]");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Fluent;
namespace Sparda.Contracts
{
public interface IFluentMetadataSource
{
List<MappingConfiguration> MappingConfigurations { get; }
void Validate(ValidationMode mode);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace İntProg.ViewModel
{
public class UrunGorselModel
{
public string urunKodu { get; set; }
public string gorselData { get; set; }
public string gorselUzanti { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FinalProject_0._0
{
class Variables
{
public static bool keepAspectRatio = false;
public static bool enlargeSmallerImages = false;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnterSceneController : Controller
{
public override void Execute(object data)
{
ScenesArgs e = data as ScenesArgs;
switch (e.M_SceneIndex)
{
case 1:
Game.M_Instance.M_Sound.PlayBG(Consts.S_BgJieMian);
MVC.RegisterView(GameObject.Find("Canvas").GetComponentInChildren<UIMainMenu>());
break;
case 2:
Game.M_Instance.M_Sound.PlayBG(Consts.S_BgJieMian);
MVC.RegisterView(GameObject.Find("Canvas").GetComponent<UIShop>());
break;
case 3:
Game.M_Instance.M_Sound.PlayBG(Consts.S_BgJieMian);
MVC.RegisterView(GameObject.Find("Canvas").transform.Find("UIBuyTools").GetComponent<UIBuyTools>());
break;
case 4:
Game.M_Instance.M_Sound.PlayBG(Consts.S_BgZhanDou);
GameObject player = GameObject.FindWithTag(Tag.Tag_Player);
MVC.RegisterView(player.GetComponent<PlayerMove>());
MVC.RegisterView(player.GetComponent<PlayerAnim>());
Transform canvas = GameObject.Find("Canvas").transform;
MVC.RegisterView(canvas.Find("UIBoard").GetComponent<UIBoard>());
MVC.RegisterView(canvas.Find("UIPause").GetComponent<UIPause>());
MVC.RegisterView(canvas.Find("UIResume").GetComponent<UIResume>());
MVC.RegisterView(canvas.Find("UIDead").GetComponent<UIDead>());
MVC.RegisterView(canvas.Find("UIFinalScore").GetComponent<UIFinalScore>());
Game.M_Instance.M_GM.M_IsPause = false;
Game.M_Instance.M_GM.M_IsPlay = true;
break;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BadBullet_Damage : Bullet // 나쁜 캐릭터들이 대상에 데미지를 주는 총알 공격 // player에 한정
{
public new string type = "bad_bullet_damage";
public override void AffectObject(GameObject target) // AffectingObject의 함수를 오버라이딩 // 대상에 영향을 주는 코드
{
base.AffectObject(target);
//if(target.tag == "player")
target.GetComponent<PlayerControl>().hp -= dmg; // 데미지 주고
target.GetComponent<PlayerControl>().CheckHp(); // 상태확인함
}
}
|
using System;
using System.Runtime.Serialization;
namespace EddiCompanionAppService.Exceptions
{
/// <summary>Exceptions thrown due to illegal service state</summary>
[Serializable]
public class EliteDangerousCompanionAppIllegalStateException : EliteDangerousCompanionAppException
{
public EliteDangerousCompanionAppIllegalStateException() { }
public EliteDangerousCompanionAppIllegalStateException(string message) : base(message) { }
public EliteDangerousCompanionAppIllegalStateException(string message, Exception innerException) : base(message, innerException)
{ }
protected EliteDangerousCompanionAppIllegalStateException(SerializationInfo info, StreamingContext context) : base(info, context)
{ }
}
}
|
using System;
using UnityEngine;
namespace zm.Util
{
public class Timer : MonoBehaviour
{
#region MonoBehaviour Methods
private void Update()
{
if (!started) { return; }
TimeLeft -= Time.deltaTime;
if (TimeLeft <= 0)
{
// If timer reached 0, stop it and trigger onFinished
onFinished();
StopTicking();
}
}
#endregion MonoBehaviour Methods
#region Public Methods
public void StartTicking(float time, Action callback)
{
TimeLeft = time;
onFinished = callback;
started = true;
}
public void StopTicking()
{
started = false;
TimeLeft = 0;
onFinished = null;
}
#endregion Public Methods
#region Fields and Properties
/// <summary>
/// Time left until timer finishes it's counting.
/// </summary>
public float TimeLeft { get; private set; }
/// <summary>
/// Flag indicating if timer started.
/// </summary>
private bool started;
/// <summary>
/// Action that will be triggered if timer counts down to 0.
/// </summary>
private Action onFinished;
#endregion Fields and Properties
}
} |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
namespace Dojo_Survey
{
public class HomeController : Controller
{
[HttpGet]
[Route("")]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("success")]
public IActionResult Success(string your_name, string dojo_location, string favorite_language, string comment)
{
ViewBag.your_name = your_name;
ViewBag.dojo_location = dojo_location;
ViewBag.favorite_language = favorite_language;
ViewBag.comment = comment;
return View();
}
}
} |
using System.Drawing;
using System.Windows.Forms;
namespace Painter.WinForms.Tools.DrawingTools
{
public abstract class ToolsBase
{
// Tools for the drawing on the pictureBox
protected Pen Pen { get; set; }
protected Point? Point { get; set; }
/// <summary>
/// Unique instrument name, initial in constructor
/// </summary>
public string Name { get; set; }
protected void CreateImage()
{
if (PictureBox.Image != null) return;
var bmp = new Bitmap(PictureBox.Width, PictureBox.Height);
using (var g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
}
PictureBox.Image = bmp;
}
/// <summary>
/// Current <see cref="PictureBox"/>
/// </summary>
public PictureBox PictureBox { get; set; }
/// <summary>
/// Mouse move event
/// </summary>
/// <param name="e">Mouse event parameters</param>
public abstract void MouseMove(MouseEventArgs e);
/// <summary>
/// Mouse up event
/// </summary>
/// <param name="e">Mouse event parameters</param>
public virtual void MouseUp(MouseEventArgs e)
{
using (var g = Graphics.FromImage(PictureBox.Image))
{
if (Point != null) g.DrawLine(Pen, Point.Value.X, Point.Value.Y, e.X, e.Y);
}
Point = null;
}
/// <summary>
/// Mouse down event
/// </summary>
/// <param name="e">Mouse event parameters</param>
/// <param name="borderColor">Color for the border figure</param>
/// <param name="backgroundColor">Back color for the figure</param>
public virtual void MouseDown(MouseEventArgs e, Color borderColor, Color? backgroundColor = null)
{
Point = new Point(e.X, e.Y);
Pen = new Pen(borderColor, 2);
MouseMove(e);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
/// <summary>
/// Summary description for TaskManager
/// </summary>
public class TaskManager
{
SqlConnection con;
public TaskManager()
{
con = new SqlConnection(@"Data Source=MOHAMMAD\MOHAMMAD;Initial Catalog=Solution;Integrated Security=True;");
}
public class QC
{
public int id, paid, pid, isy, isn;
public string qu, yn;
}
public class pr
{
public int id;
public string pr_, ca;
}
/// <summary>
/// /////////////////////////////NEW PROBLEM PROCESS///////////////////////////////////////////
/// </summary>
/// <returns></returns>
public List<string> getCats()
{
List<string> retVal = new List<string>();
string command = "SELECT * FROM [Category] ";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
retVal.Add(reader.GetString(1));
reader.Close();
con.Close();
return retVal;
}
public bool newCat(string cat)
{
try
{
string command = "INSERT INTO [Category] (Category) VALUES('" + cat + "')";
SqlCommand com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
return false;
}
return true;
}
public bool newProblem(string cat,string problem)
{
try
{
string command = "INSERT INTO [PROBLEMS] (Problem,Category) VALUES('"+problem+"','" + cat + "')";
SqlCommand com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
public int getProblemId(string problem)
{
int retVal=0;
string command = "SELECT ID FROM [PROBLEMS] WHERE CONVERT(VARCHAR, Problem) ='" + problem + "'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
retVal = reader.GetInt32(0);
reader.Close();
con.Close();
return retVal;
}
public List<pr> getProblems()
{
List<pr> retVal = new List<pr>();
string command = "SELECT * FROM [PROBLEMS] ";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
{
pr t = new pr();
t.id = reader.GetInt32(0);
t.pr_ = reader.GetString(1);
t.ca = reader.GetString(2);
retVal.Add(t);
}
reader.Close();
con.Close();
return retVal;
}
//////////////////////////////////END OF NEW PROBLEM////////////////////////////////////////////////////
/////////////////////////////////First Question/////////////////////////////////////////////////////
public string getProblem(int id)
{
string retVal = "";
string command = "SELECT Problem FROM [PROBLEMS] WHERE ID='" + id + "'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
if (reader.Read())
retVal = reader.GetString(0);
reader.Close();
con.Close();
return retVal;
}
public bool newQuestion(int paId,int pId,string qu,int ys,int ns,string yn)
{
try
{
string command = "INSERT INTO [Y_Qu] (Parent_ID,Problem_ID,Question,Is_Y_Sol,Is_N_Sol,Y_N) VALUES('" + paId + "','" + pId + "','"+qu+"','"+ys+"','"+ns+"','"+yn+"')";
SqlCommand com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
public int getFQID(string qu)
{
int retVal = 0;
string command = "SELECT ID FROM [Y_Qu] WHERE CONVERT(VARCHAR, Question) ='" + qu + "'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
retVal = reader.GetInt32(0);
reader.Close();
con.Close();
return retVal;
}
public void requestProblem(string problem)
{
string command = "INSERT INTO [Request] (Problem) VALUES('" + problem + "')";
SqlCommand com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
public List<string> getRequests()
{
List<string> retVal = new List<string>();
string command = "SELECT Problem FROM [Request]";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
retVal.Add(reader.GetString(0));
reader.Close();
con.Close();
return retVal;
}
public string getQu(int id)
{
string retVal = "";
string command = "SELECT Question FROM [Y_Qu] WHERE ID='" + id + "'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
if (reader.Read())
retVal = reader.GetString(0);
reader.Close();
con.Close();
return retVal;
}
public QC getQus(int pId,int paId,string yn)
{
QC QU = new QC();
string command = "SELECT * FROM [Y_Qu] WHERE Problem_ID ='" + pId + "' AND Parent_ID='"+paId+"' AND Y_N='"+yn+"'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
if (reader.Read())
{
QU.id = reader.GetInt32(0);
QU.paid = reader.GetInt32(1);
QU.pid = reader.GetInt32(2);
QU.qu = reader.GetString(3);
QU.isy = reader.GetInt32(4);
QU.isn = reader.GetInt32(5);
QU.yn = reader.GetString(6);
}
reader.Close();
con.Close();
return QU;
}
public List<string> getSol(int paId,string yn)
{
List<string> retVal = new List<string>();
string command = "SELECT * FROM [Solutions] WHERE Parent_ID ='" + paId + "' AND YN='" + yn + "'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
if (reader.Read())
{
retVal.Add(reader.GetString(2));
retVal.Add(reader.GetString(3));
retVal.Add(reader.GetString(4));
retVal.Add(reader.GetString(5));
retVal.Add(reader.GetString(6));
retVal.Add(reader.GetString(7));
}
reader.Close();
con.Close();
return retVal;
}
public List<QC> getQuestions(int pId)
{
List<QC> allQU = new List<QC>();
string command = "SELECT * FROM [Y_Qu] WHERE Problem_ID ='" + pId + "'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
{
QC QU = new QC();
QU.id = reader.GetInt32(0);
QU.paid = reader.GetInt32(1);
QU.pid = reader.GetInt32(2);
QU.qu = reader.GetString(3);
QU.isy = reader.GetInt32(4);
QU.isn = reader.GetInt32(5);
QU.yn = reader.GetString(6);
allQU.Add(QU);
}
reader.Close();
con.Close();
List<int> sPaId = new List<int>();
command = "SELECT Parent_ID FROM [Solutions]";
com = new SqlCommand(command, con);
con.Open();
reader = com.ExecuteReader();
while (reader.Read())
{
sPaId.Add(reader.GetInt32(0));
}
reader.Close();
con.Close();
int nextQuestionID = -1;
foreach(QC temp in allQU)
{
bool haveNext = false;
for (int i = 0; i < allQU.Count; i++)
{
if (temp.id == allQU[i].paid)
{
haveNext = true;
break;
}
}
if (!haveNext)
{
foreach (int t in sPaId)
{
if (temp.id == t)
{
haveNext = true;
break;
}
}
if (!haveNext)
nextQuestionID = temp.id;
}
}
int nextQuestionParentID = -1;
foreach (QC temp in allQU)
{
if (temp.id == nextQuestionID)
{
nextQuestionParentID = temp.paid;
break;
}
}
List<QC> retVal = new List<QC>();
foreach (QC temp in allQU)
{
if (temp.paid == nextQuestionParentID)
{
retVal.Add(temp);
}
}
return retVal;
}
///////
public bool Login(string userName,string pass)
{
bool retVal = false;
string command = "SELECT * FROM [User] WHERE UN ='" + userName + "' AND PASS='"+pass+"'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
if (reader.Read())
retVal = true;
con.Close();
return retVal;
}
public bool CreateAccount(string userName,string pass)
{
bool retVal = true;
string command = "INSERT INTO [User] (UN,PASS) VALUES('"+userName+"','"+pass+"')";
SqlCommand com = new SqlCommand(command, con);
con.Open();
try
{
com.ExecuteNonQuery();
}
catch(Exception)
{
retVal = false;
}
con.Close();
return retVal;
}
public bool editProblem(int pid, string question)
{
bool retVal = false;
int id = 0;
string command = "SELECT ID FROM [Y_Qu] WHERE Problem_ID='" + pid + "' AND Question LIKE '%" + question + "%'";
SqlCommand com = new SqlCommand(command, con);
SqlDataReader reader;
con.Open();
reader = com.ExecuteReader();
if (reader.Read())
id=reader.GetInt32(0);
con.Close();
if (id != 0)
{
retVal = true;
command = "DELETE FROM [Y_Qu] WHERE Problem_ID='" + pid + "' AND Parent_ID>='" + id + "'";
com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
command = "DELETE FROM [Y_Qu] WHERE Problem_ID='" + pid + "' AND ID='" + id + "'";
com = new SqlCommand(command, con);
com.ExecuteNonQuery();
con.Close();
}
return retVal;
}
public void deleteProblem(int pId)
{
string command = "DELETE FROM [PROBLEMS] WHERE ID='" + pId + "'";
SqlCommand com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
command = "DELETE FROM [Y_Qu] WHERE Problem_ID='" + pId + "'";
com = new SqlCommand(command, con);
com.ExecuteNonQuery();
con.Close();
}
public bool insertSolution(int paId,string s1,string s2,string s3,string s4,string s5,string s6,string yn)
{
if (s1 == null)
s1 = "";
if (s2 == null)
s2 = "";
if (s3 == null)
s3 = "";
if (s4 == null)
s4 = "";
if (s5 == null)
s5 = "";
if (s6 == null)
s6 = "";
try
{
string command = "INSERT INTO [Solutions] (Parent_ID,S1,S2,S3,S4,S5,S6,YN) VALUES('" + paId + "','" + s1 + "','" + s2 + "','" + s3 + "','" + s4 + "','" + s5 + "','"+s6+"','"+yn+"')";
SqlCommand com = new SqlCommand(command, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
} |
// RayProfiler
// https://github.com/Bugfire
using UnityEngine;
using UnityEngine.Assertions;
#if UNITY_5_5_OR_NEWER
using UnityEngine.Profiling;
#endif
namespace RayStorm
{
#if UNITY_5_5_OR_NEWER
[DefaultExecutionOrder (int.MaxValue - 2)]
#endif
sealed public class RayProfilerToCanvas : MonoBehaviour
{
#region Inspector Settings Values
[SerializeField]
RayProfiler _Profiler;
[SerializeField]
RayCanvas _Canvas;
#endregion
struct Log
{
public int WaitForEndOfFrame;
public int FrameEnd;
public bool GC;
}
Log[] _Log = new Log[60];
int _curLog = 0;
System.Diagnostics.Stopwatch _stopWatch = new System.Diagnostics.Stopwatch ();
float _lastAvgFPS = -1;
int _lastAvgFPSCounter = 0;
#region Unity Messages
void Awake ()
{
Assert.IsNotNull (_Profiler, "_Profiler is not defined on " + RayDebugUtils.GetObjectName (this));
Assert.IsNotNull (_Canvas, "_Canvas is not defined on " + RayDebugUtils.GetObjectName (this));
}
void Update ()
{
const int barWidth = 320;
const int barHeight = 16;
const int lineWidth = 2;
var ticks = _Profiler.LastTicks;
var targetFps = (int)Application.targetFrameRate;
if (targetFps <= 0) {
targetFps = 60;
}
var totalTicks = 10000000 / targetFps;
var ticksUnit = totalTicks / (float)(barWidth - lineWidth * 2);
_Canvas.Clear ();
_Canvas.FillRect (0, 0, _Canvas.Width, _Canvas.Height, new Color (0, 0, 0, 0.5f));
_Canvas.FillRect (0, 0, barWidth, barHeight, Color.white);
const int sy = lineWidth;
const int ey = barHeight - lineWidth;
_Canvas.FillRect (lineWidth, sy, barWidth - lineWidth, ey, Color.black);
var pos = lineWidth;
var ammount = 0;
_curLog++;
if (_curLog >= _Log.Length) {
_curLog = 0;
}
// FixedUpdate
ammount = (int)(ticks.FixedUpdate / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.yellow);
pos += ammount;
// Physics
ammount = (int)(ticks.Physics / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.green);
pos += ammount;
// WaitForFixedUpdate
ammount = (int)(ticks.WaitForFixedUpdate / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.cyan);
pos += ammount;
// Update
ammount = (int)(ticks.Update / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.blue);
pos += ammount;
// YieldAndAnimation
ammount = (int)(ticks.YieldAndAnimation / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.magenta);
pos += ammount;
// LateUpdate
ammount = (int)(ticks.LateUpdate / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.grey);
pos += ammount;
// Render
ammount = (int)(ticks.Render / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.red);
pos += ammount;
// WaitForEndOfFrame
ammount = (int)(ticks.WaitForEndOfFrame / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, Color.white);
pos += ammount;
_Log [_curLog].WaitForEndOfFrame = pos;
// FrameEnd
ammount = (int)(ticks.FrameEnd / ticksUnit);
_Canvas.FillRect (pos, sy, pos + ammount, ey, new Color (1, 1, 1, 0.5f));
pos += ammount;
_Log [_curLog].FrameEnd = pos;
_Log [_curLog].GC = ticks.GCCount != 0;
for (var i = 0; i < _Log.Length; i++) {
int index = _curLog - i;
if (index < 0) {
index += _Log.Length;
}
_Canvas.FillRect (
0, barHeight + i * 2, _Log [index].WaitForEndOfFrame, barHeight + i * 2 + 2,
_Log [index].GC ? new Color (1f, 1, 0.5f, 1) : new Color (0.5f, 1, 0.5f, 0.7f));
_Canvas.FillRect (
_Log [index].WaitForEndOfFrame, barHeight + i * 2, _Log [index].FrameEnd, barHeight + i * 2 + 2,
_Log [index].GC ? new Color (1f, 0.5f, 0.5f, 1) : new Color (1f, 1f, 1f, 0.5f));
}
//
var fps = Time.unscaledDeltaTime != 0 ? 1 / Time.unscaledDeltaTime : 0;
var restartStopWatch = false;
_lastAvgFPSCounter++;
if (_lastAvgFPS < 0) {
_lastAvgFPS = fps;
restartStopWatch = true;
} else if (_stopWatch.ElapsedMilliseconds > 1000 && _lastAvgFPSCounter > 10) {
_lastAvgFPS = _lastAvgFPSCounter * 1000.0f / _stopWatch.ElapsedMilliseconds;
restartStopWatch = true;
}
if (restartStopWatch == true) {
_lastAvgFPSCounter = 0;
_stopWatch.Stop ();
_stopWatch.Reset ();
_stopWatch.Start ();
}
_Canvas.SetTextPosition (8, barHeight);
_Canvas.AddText ("FPS:");
_Canvas.AddText (fps, 3, 2);
_Canvas.AddText (" AVG.FPS:");
_Canvas.AddText (_lastAvgFPS, 3, 2);
#if UNITY_5_6_OR_NEWER
if (UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong () >= 1024) {
_Canvas.AddText ("\nVM: ");
_Canvas.AddText ((int)Profiler.GetMonoUsedSizeLong () / 1024, 6);
_Canvas.AddText ("/");
_Canvas.AddText ((int)Profiler.GetMonoHeapSizeLong () / 1024, 6);
}
if (UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong () >= 1024) {
_Canvas.AddText ("\nTotal:");
_Canvas.AddText ((int)Profiler.GetTotalAllocatedMemoryLong () / 1024, 6);
_Canvas.AddText ("/");
_Canvas.AddText ((int)Profiler.GetTotalReservedMemoryLong () / 1024, 6);
}
#else
if (Profiler.GetMonoUsedSize () >= 1024) {
_Canvas.AddText ("\nVM: ");
_Canvas.AddText ((int)Profiler.GetMonoUsedSize () / 1024, 6);
_Canvas.AddText ("/");
_Canvas.AddText ((int)Profiler.GetMonoHeapSize () / 1024, 6);
}
if (Profiler.GetTotalAllocatedMemory () >= 1024) {
_Canvas.AddText ("\nTotal:");
_Canvas.AddText ((int)Profiler.GetTotalAllocatedMemory () / 1024, 6);
_Canvas.AddText ("/");
_Canvas.AddText ((int)Profiler.GetTotalReservedMemory () / 1024, 6);
}
#endif
}
#endregion
}
} |
using GraphicalEditor.DTO;
using GraphicalEditor.Models;
using GraphicalEditor.DTO;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GraphicalEditor.Service
{
public class DoctorService : GenericHTTPService
{
public List<SpecialtyDTO> GetAllSpecialties()
{
return (List<SpecialtyDTO>)HTTPGetRequest<SpecialtyDTO>("doctor/specialties");
}
public DoctorDTO GetDoctorByJmbg(string jmbg)
{
return (DoctorDTO)HTTPGetSingleItemRequest<DoctorDTO>("doctor/" + jmbg);
}
public List<DoctorDTO> GetDoctorsBySpecialty(int specialtyId)
{
return (List<DoctorDTO>)HTTPGetRequest<DoctorDTO>("doctor/doctors-by-specialty/ " + specialtyId);
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Project371
{
/// <summary>
/// Describe the basic look of an object
/// </summary>
class Material
{
/// <summary>
/// The texture of the object
/// </summary>
public Texture2D texture;
/// <summary>
/// The color applied to the object
/// </summary>
public Vector3 color;
/// <summary>
/// The specular power for lighting
/// </summary>
public float SpecularPower;
public Material()
{
color = new Vector3(1, 1, 1);
texture = null;
SpecularPower = 500.0f;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.