text stringlengths 13 6.01M |
|---|
using PWA_Maesai.Models;
using PWA_Maesai.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using System.Web.Mvc;
namespace PWA_Maesai.API
{
public class AnnounceController : ApiController
{
private MaesaiEntities db = new MaesaiEntities();
private AnnounceRepo AnnounceRepo;
public AnnounceController()
{
this.AnnounceRepo = new AnnounceRepo(new MaesaiEntities());
}
public async Task<IHttpActionResult> Get()
{
try
{
var list = await AnnounceRepo.Get().FirstOrDefaultAsync();
return this.Ok(list);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return this.NotFound();
}
}
public class AnnounceViewModel
{
public bool AnnounceActive { get; set; }
public string AnnounceText { get; set; }
public string AnnounceTime { get; set; }
public int ID { get; set; }
}
public IHttpActionResult Post(AnnounceViewModel data)
{
var announceModel = new Announce();
announceModel.ID = data.ID;
announceModel.AnnounceText = data.AnnounceText;
announceModel.AnnounceActive = data.AnnounceActive;
announceModel.AnnounceTime = DateTime.ParseExact(data.AnnounceTime,"dd-MM-yyyy HH:mm", new CultureInfo("en-US"));
var status = AnnounceRepo.Set(announceModel);
if (status == false)
return this.NotFound();
else
return this.Ok();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using FluentValidation;
namespace ZooApp.Application.Animal.Queries.GetAnimalWithPagination
{
public class GetAnimalWithPaginationQueryValidator : AbstractValidator<GetAnimalWithPaginationQuery>
{
public GetAnimalWithPaginationQueryValidator()
{
//RuleFor(x => x.PageNumber)
// .GreaterThanOrEqualTo(1).WithMessage("PageNumber at least greater than or equal to 1.");
//RuleFor(x => x.PageSize)
// .GreaterThanOrEqualTo(1).WithMessage("PageSize at least greater than or equal to 1.");
}
}
}
|
using UnityEngine;
using Zenject;
namespace GFG
{
[CreateAssetMenu(fileName = "GameSettingsInstaller", menuName = "Installers/GameSettingsInstaller")]
public class GameSettingsInstaller : ScriptableObjectInstaller<GameSettingsInstaller>
{
public GameManager.Settings Settings;
public override void InstallBindings()
{
Container.BindInstance(Settings);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Sugar : MonoBehaviour {
public Vector3 Direction;
public float Speed;
public GameObject ParticulaCafé;
public GameObject ParticulaPrato;
// Use this for initialization
void Start () {
Direction.Normalize(); // equivalente a fazer a Direção = Direção.normalized;
}
// Update is called once per frame
void Update () {
transform.position += Direction * Speed * Time.deltaTime;
//if (transform.position.x <= -10.0)
//{
//transform.position = new Vector3( 10, transform.position.y, transform.position.z );
//} else if (transform.position.x >= 10.0)
//{
//transform.position = new Vector3( -10, transform.position.y, transform.position.z );
//}
}
void OnCollisionEnter2D( Collision2D colisor ) {
bool colisãoInvalida = false;
Vector2 normal = colisor.contacts[0].normal;
Xicara xicara = colisor.transform.GetComponent<Xicara>();
Parede parede = colisor.transform.GetComponent<Parede>();
if (xicara != null) { // Se existir o componente Xicara no gameObject com o qual o açúcar colidiu.
if (normal != Vector2.up) {
//colisãoInvalida = true;
} else {
//starta gotas de café
Vector3 posParCoffe = new Vector3(colisor.transform.position.x, colisor.transform.position.y + 1, colisor.transform.position.z);
ParticulaCafé.transform.position = posParCoffe;
ParticleSystem componenteParticulas = ParticulaCafé.GetComponent<ParticleSystem>();
componenteParticulas.Play();
}
} else if (parede != null) {
if (normal == Vector2.up) {
colisãoInvalida = true;
}
} else {
colisãoInvalida = false;
Destroy( colisor.gameObject ); //destroy prato
GerenciadorDoGame.numeroDeBlocosDestruidos++;
//starta particula do prato
Vector3 posParPrato = new Vector3(colisor.transform.position.x + 1, colisor.transform.position.y, colisor.transform.position.z);
ParticulaPrato.transform.position = posParPrato;
ParticleSystem componenteParticulas = ParticulaPrato.GetComponent<ParticleSystem>();
componenteParticulas.Play();
}
if ( !colisãoInvalida ) {
Direction = Vector2.Reflect( Direction, normal );
Direction.Normalize();
} else {
GerenciadorDoGame.instance.FinalizaGame();
//GerenciadorDoGame.loadLevel("Fase 1");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SpaceShip.Models.SpaceCraftSystems
{
interface IModule
{
string GetModuleInfo();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SnakeGame
{
public class ConsoleRenderer : IRenderer
{
public ConsoleColor Color { get; set; }
public IDictionary<string, ConsoleColor> Colors { get; set; }
public ConsoleRenderer()
{
Colors = new Dictionary<string, ConsoleColor>();
Type type = typeof(ConsoleColor);
foreach (var name in Enum.GetNames(type))
{
this.Colors.Add(name, (ConsoleColor)Enum.Parse(type, name));
}
}
private void DetectColor(string color)
{
foreach (KeyValuePair<string,ConsoleColor> pair in this.Colors)
{
if (pair.Key == color)
{
this.Color = pair.Value;
break;
}
}
}
public void DrawAt(Position position, string color)
{
DetectColor(color);
Console.SetCursorPosition(position.X, position.Y);
Console.BackgroundColor = this.Color;
Console.Write(' ');
Console.BackgroundColor = ConsoleColor.Black;
}
public void WriteAtWithColor(Position position, string tcolor, string text, string bcolor)
{
DetectColor(tcolor);
Console.SetCursorPosition(position.X, position.Y);
Console.ForegroundColor = this.Color;
DetectColor(bcolor);
Console.BackgroundColor = this.Color;
Console.Write(text);
Console.ForegroundColor = ConsoleColor.Green;
Console.BackgroundColor = ConsoleColor.Black;
}
public List<string> ListOfColorNames()
{
List<string> colors = new List<string>();
foreach(KeyValuePair<string, ConsoleColor> color in this.Colors)
{
colors.Add(color.Key);
}
return colors;
}
}
} |
using System;
using Xamarin.Forms;
namespace tryfsharpforms
{
public class App : Application
{
public static int ScreenWidth;
public static int ScreenHeight;
public App ()
{
// The root page of your application
MainPage = new NavigationPage (new HomePage ()){
BarBackgroundColor = MyColors.WetAsphalt,
BarTextColor = MyColors.Clouds,
};
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
|
using System.ComponentModel;
using Webcorp.unite;
namespace Webcorp.Model.Quotation{
public class VitesseDecoupeLaserInitializer : IEntityProviderInitializable<VitesseDecoupeLaser, string>{
public void InitializeProvider(EntityProvider<VitesseDecoupeLaser, string> entityProvider)
{
entityProvider.Register(new VitesseDecoupeLaser(){Code=215,GroupeMatiere=MaterialGroup.P,Epaisseur=1,Gaz=GazDecoupe.Oxygene,GrandeVitesse=8650*Velocity.MillimetrePerMinute,PetiteVitesse=7100*Velocity.MillimetrePerMinute});
entityProvider.Register(new VitesseDecoupeLaser(){Code=215,GroupeMatiere=MaterialGroup.P,Epaisseur=1.5,Gaz=GazDecoupe.Oxygene,GrandeVitesse=7400*Velocity.MillimetrePerMinute,PetiteVitesse=6100*Velocity.MillimetrePerMinute});
}
}
}
|
using System;
public class Program
{
public static void Main()
{
var inputNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < inputNumber / 2; i++)
{
Console.WriteLine("{0}x{1}x{0}", new string(' ', i), new string(' ', inputNumber - (2 + i * 2)));
}
Console.WriteLine("{0}x{0}", new string(' ', inputNumber / 2));
for (int i = inputNumber / 2; i > 0; i--)
{
Console.WriteLine("{0}x{1}x{0}", new string(' ', i - 1), new string(' ', inputNumber - 2 * i));
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Timers;
using Foundation;
using UIKit;
namespace ChuckNorris
{
public partial class MainViewController : UIViewController
{
private bool OverwriteNotAllowed = false;
public List<Chuck> mainList;
public LoadingOverlay loadPop;
private bool initialization = true;
public Timer refreshTimer;
public MainViewController() : base("MainViewController", null)
{
Title = "Chuck Norris Facts";
refreshTimer = new Timer(10000);
refreshTimer.Elapsed += async (sender, e) =>
{
// This function will pause the timer to avoid any overlap
refreshTimer.Stop();
Console.WriteLine("10 Seconds Elapsed. Refreshing List.");
List<Chuck> tempList = await WebServices.Instance.GetAChuck();
if (tempList == null)
{
// Service Call Failed
// DO NOTHING
// We can live without this extra refresh
// It will refresh automatically in 10 seconds anyways
}
else // Update List without alerting user
{
InvokeOnMainThread(() =>
{
// If the local list is being modified, do not modify until next refresh
if (!OverwriteNotAllowed)
{
mainList = tempList;
QuoteTable.Source = new TableSource(mainList, this);
QuoteTable.ReloadData();
UpdateTableViewContents();
}
else
{
Console.WriteLine("Local file was being updated.");
}
});
}
refreshTimer.Start();
};
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Add Navbar + and keep it disabled until data is loaded
UIBarButtonItem addButton = new UIBarButtonItem(UIBarButtonSystemItem.Add, AddQuote);
NavigationItem.RightBarButtonItem = addButton;
NavigationItem.RightBarButtonItem.Enabled = false;
// Hide the Table View and No Data Label
QuoteTable.Hidden = true;
NoDataLabel.Hidden = true;
}
public void ChuckUpdated(object sender, AddEditViewController.ChuckArgs args)
{
// To decrease wait time for an add/edit, I have local storage update after the server is hit
refreshTimer.Stop();
OverwriteNotAllowed = true;
Console.WriteLine("Chuck Updated. Callback to main.");
if (args.IsNew)
{
if (mainList.Exists(x => x.Id == (args.UpdatedChuck.Id)))
{
// Do Nothing
Console.WriteLine("List was already updated with latest value.");
}
else
{
mainList.Add(args.UpdatedChuck);
Console.WriteLine("Added Chuck to local storage.");
}
}
else // Update Existing
{
var localChuck = mainList.Find(x => x.Id == (args.UpdatedChuck.Id));
if (localChuck != null)
{
localChuck.ChuckQuote = args.UpdatedChuck.ChuckQuote;
localChuck.QuoteDate = args.UpdatedChuck.QuoteDate;
localChuck.EnteredBy = args.UpdatedChuck.EnteredBy;
Console.WriteLine("Updated Local Storage Chuck");
}
else
{
// Do Nothing
Console.WriteLine("Failed to update local storage chuck.");
}
}
QuoteTable.Source = new TableSource(mainList, this);
QuoteTable.ReloadData();
UpdateTableViewContents();
OverwriteNotAllowed = false;
refreshTimer.Start();
}
public void SubscribeToAddEditVC(AddEditViewController VC)
{
//Subscribe to New Chuck Facts being added
VC.ChuckUpdated += ChuckUpdated;
}
public void AddQuote(object sender, EventArgs e)
{
AddEditViewController newVC = new AddEditViewController();
SubscribeToAddEditVC(newVC);
NavigationController.PushViewController(newVC, true);
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Show the loading overlay on the UI thread using the correct orientation sizing
if (initialization)
{ // Getting the initial list is the most important. Lock UI until this completes
var bounds = UIScreen.MainScreen.Bounds;
loadPop = new LoadingOverlay(bounds, "Loading Chuck Norris Facts...");
View.Add(loadPop);
NavigationItem.RightBarButtonItem.Enabled = false;
GetAllChucks();
initialization = false;
// The App will refresh every 10 seconds from here on out
refreshTimer.Start();
}
}
#region Display Utilities
public void DisplayChuckTable(){
NoDataLabel.Hidden = true;
QuoteTable.Hidden = false;
}
public void DisplayNoChuckMessage(){
NoDataLabel.Hidden = false;
QuoteTable.Hidden = true;
}
public void UpdateTableViewContents(){
if (mainList.Count == 0){DisplayNoChuckMessage();}
else{DisplayChuckTable();}
}
#endregion
async void GetAllChucks()
{
List<Chuck> chucks = null;
while (chucks == null)
{
// This will return null if it fails
chucks = await WebServices.Instance.GetAChuck();
if (chucks == null)
{
Console.WriteLine("Service failed. Retrying.");
}
}
mainList = chucks;
QuoteTable.Source = new TableSource(mainList, this);
QuoteTable.ReloadData();
UpdateTableViewContents();
InvokeOnMainThread(() =>
{
loadPop.Hide();
NavigationItem.RightBarButtonItem.Enabled = true;
});
return;
}
}
#region TableView Source
public class TableSource : UITableViewSource
{
MainViewController vc;
private List<Chuck> quoteList;
private bool deleting = false;
public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath)
{
if (deleting){return false;}
else{return true;}
}
public override async void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
{
switch (editingStyle)
{
case UITableViewCellEditingStyle.Delete:
// prevent other deletes
deleting = true;
// don't allow updates
vc.refreshTimer.Stop();
// simulate deletion immediately
var id = quoteList[indexPath.Row].Id;
quoteList.RemoveAt(indexPath.Row);
tableView.BeginUpdates();
tableView.DeleteRows(new NSIndexPath[] {indexPath}, UITableViewRowAnimation.Fade);
string footerString = "0 Facts";
if (quoteList.Count == 1) { footerString = quoteList.Count.ToString() + " Fact"; }
else if (quoteList.Count == 0) { vc.DisplayNoChuckMessage(); }
else { footerString = quoteList.Count.ToString() + " Facts"; }
tableView.GetFooterView(0).TextLabel.Text = footerString;
tableView.EndUpdates();
await WebServices.Instance.DeleteAChuck(id);
// once it is actually deleted - go back to allowing refreshing and deleting
deleting = false;
vc.refreshTimer.Start();
break;
case UITableViewCellEditingStyle.None:
break;
}
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
AddEditViewController detailsVC = new AddEditViewController(quoteList, indexPath.Row);
vc.SubscribeToAddEditVC(detailsVC);
vc.NavigationController.PushViewController(detailsVC, false);
}
public TableSource(List<Chuck> chucksIn, MainViewController vc_in)
{
quoteList = chucksIn;
vc = vc_in;
}
public override nint NumberOfSections(UITableView tableView)
{
return 1; // just facts
}
public override string TitleForFooter(UITableView tableView, nint section)
{
if (quoteList.Count == 1)
{
return quoteList.Count.ToString() + " Fact";
}
else
{
return quoteList.Count.ToString() + " Facts";
}
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell;
// try to get a reusable cell
cell = tableView.DequeueReusableCell("ChuckStyle");
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Subtitle, "ChuckStyle");
}
cell.TextLabel.Text = quoteList[indexPath.Row].ChuckQuote;
cell.DetailTextLabel.Text = "By: " + quoteList[indexPath.Row].EnteredBy;
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return quoteList.Count;
}
}
#endregion
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExperianOfficeArrangement.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
using System.Windows.Input;
namespace ExperianOfficeArrangement.ViewModels.Tests
{
[TestClass]
public class NavigationViewModelBaseTests
{
private class TestNavigationViewModel : NavigationViewModelBase
{
public void SetCanTransition(bool value)
{
this.CanTransition = value;
}
public void SetNextState(IStateViewModel state)
{
this.nextState = state;
}
public override IStateViewModel GetNextState()
{
return this.nextState;
}
private IStateViewModel nextState;
}
[TestClass]
public class CanTransitionTests
{
[TestMethod]
public void ShouldEnableNavigationCommand()
{
TestNavigationViewModel test = new TestNavigationViewModel();
bool canNavigate = false;
test.NavigateForwardCommand.CanExecuteChanged += (s, e) => canNavigate = test.NavigateForwardCommand.CanExecute(null);
test.PropertyChanged += (s, e) => Assert.AreEqual(PropertyName.Get<TestNavigationViewModel>(vm => vm.CanTransition), e.PropertyName);
test.SetCanTransition(true);
Assert.IsTrue(canNavigate);
}
}
[TestClass]
public class NavigateCommandTests
{
[TestMethod]
public void ShouldSetParentState()
{
TestNavigationViewModel test = new TestNavigationViewModel();
Mock<IStateViewModel> mockState = new Mock<IStateViewModel>();
Mock<IStateContext> parentMock = new Mock<IStateContext>();
parentMock.Setup(x => x.SetStateCommand).Returns(new Mock<ICommand>().SetupAllProperties().Object);
test.SetNextState(mockState.Object);
test.Parent = parentMock.Object;
test.SetCanTransition(true);
Assert.AreEqual(mockState.Object, test.GetNextState());
test.NavigateForwardCommand.Execute(null);
}
}
}
} |
using System;
namespace RealEstate.BusinessObjects
{
public class Banner
{
#region ***** Fields & Properties *****
private int _BannerID;
public int BannerID
{
get
{
return _BannerID;
}
set
{
_BannerID = value;
}
}
private string _BannerType;
public string BannerType
{
get
{
return _BannerType;
}
set
{
_BannerType = value;
}
}
private string _Size;
public string Size
{
get
{
return _Size;
}
set
{
_Size = value;
}
}
private string _Description;
public string Description
{
get
{
return _Description;
}
set
{
_Description = value;
}
}
private string _Images;
public string Images
{
get
{
return _Images;
}
set
{
_Images = value;
}
}
#endregion
#region ***** Init Methods *****
public Banner()
{
}
public Banner(int bannerid)
{
this.BannerID = bannerid;
}
public Banner(int bannerid, string bannertype, string size, string description, string images)
{
this.BannerID = bannerid;
this.BannerType = bannertype;
this.Size = size;
this.Description = description;
this.Images = images;
}
#endregion
}
}
|
namespace ZeroFormatter.Internal
{
internal static class SR
{
public const string InvalidOperation_EnumFailedVersion = "InvalidOperation_EnumFailedVersion";
public const string InvalidOperation_EnumOpCantHappen = "InvalidOperation_EnumOpCantHappen";
public const string ArgumentOutOfRange_Index = "ArgumentOutOfRange_Index";
public const string Argument_InvalidArrayType = "Argument_InvalidArrayType";
public const string NotSupported_ValueCollectionSet = "NotSupported_ValueCollectionSet";
public const string Arg_RankMultiDimNotSupported = "Arg_RankMultiDimNotSupported";
public const string Arg_ArrayPlusOffTooSmall = "Arg_ArrayPlusOffTooSmall";
public const string Arg_NonZeroLowerBound = "Arg_NonZeroLowerBound";
public const string NotSupported_KeyCollectionSet = "NotSupported_KeyCollectionSet";
public const string Arg_WrongType = "Arg_WrongType";
public const string ArgumentOutOfRange_NeedNonNegNum = "ArgumentOutOfRange_NeedNonNegNum";
public const string Arg_HTCapacityOverflow = "Arg_HTCapacityOverflow";
public const string Argument_AddingDuplicate = "Argument_AddingDuplicate";
public static string Format(string f, params object[] args)
{
return string.Format(f, args);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Trigger script for fail condition for Circuit 5
public class C5failcon : MonoBehaviour
{
public EndTriggerFront trigger;
public void OnTriggerStay(Collider other)
{
trigger.settrigfail1 = true;
trigger.settrigfail2 = true;
}
public void OnTriggerExit(Collider other)
{
trigger.settrigfail1 = false;
trigger.settrigfail2 = false;
}
}
|
#region namespace
using static Sitecore.Configuration.Settings;
#endregion
namespace EMAAR.ECM.Foundation.SitecoreExtensions.Settings
{
/// <summary>
/// This class provides the common setting for Banner projects
/// </summary>
public static class SitecoreSettings
{
/// <summary>
/// Getting Root View location for controller to load view
/// Physical location of the view path for the action method
/// ~/Views/Feature/ECM/
/// </summary>
public static string ViewPath { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.FeatureViewPath");
/// <summary>
/// Getting Home page search icon image url from Sitecore settings based on Site
/// /Site Settings/Site Specific Images/Home/HomePageSearch
/// </summary>
public static string HomePageSearch { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.HomePageSearch");
/// <summary>
/// Getting Home page Close icon image url from Sitecore settings based on Site
/// /Site Settings/Site Specific Images/Home/HomePageClose
/// </summary>
public static string HomePageClose { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.HomePageClose");
/// <summary>
/// Getting Content page search icon image url from Sitecore settings based on Site
/// /Site Settings/Site Specific Images/Content/ContentPageSearch
/// </summary>
public static string ContentPageSearch { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.ContentPageSearch");
/// <summary>
/// Getting Content page Close icon image url from Sitecore settings based on Site
/// /Site Settings/Site Specific Images/Content/ContentPageClose
/// </summary>
public static string ContentPageClose { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.ContentPageClose");
/// <summary>
/// Getting Header item path /Site Content/Navigation/Header
/// </summary>
public static string NavigationHeaderPath { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.NavigationHeaderPath");
/// <summary>
/// Getting footer item path Site Content/Navigation/Footer
/// </summary>
public static string NavigationFooterPath { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.NavigationFooterPath");
/// <summary>
/// Getting Image location path "Assets/Project/ECM/images/"
/// </summary>
public static string ImageLocatation { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.ImageLocation");
/// <summary>
/// Getting Image location path "~/Assets/Project/ECM/images/icon/"
/// </summary>
public static string IconRootPath { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.IconRootPath");
/// <summary>
/// Getting date format
/// </summary>
public static string DateFormat { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.DateFormat");
/// <summary>
/// NewsThumnailPixel
/// </summary>
public static string NewsThumnailPixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.NewsThumnailPixel");
/// <summary>
/// DownloadThumnailPixel
/// </summary>
public static string DownloadThumnailPixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.DownloadThumnailPixel");
/// <summary>
/// AlbumThumnailPixel
/// </summary>
public static string AlbumThumnailPixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.AlbumThumnailPixel");
/// <summary>
/// HeroImage image pixel
/// </summary>
public static string HeroImagepixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.HeroImagepixel");
/// <summary>
/// HomePageCarousel image pixel
/// </summary>
public static string HomePageCarouselpixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.HomePageCarouselpixel");
/// <summary>
/// ImageText image pixel
/// </summary>
public static string ImageTextpixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.ImageTextpixel");
/// <summary>
/// Parallax image pixel
/// </summary>
public static string Parallaxpixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.Parallaxpixel");
/// <summary>
/// ContentPageBannerpixel image pixel
/// </summary>
public static string ContentPageBannerpixel { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.ContentPageBannerpixel");
/// <summary>
/// RelatedPages image pixel
/// </summary>
public static string RelatedPages { get; set; } = GetSetting("EMAAR.ECM.Foundation.SitecoreExtensions.RelatedPages");
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using zoologico.Interfaces;
using zoologico.Models;
namespace zoologico {
class Program {
static void Main (string[] args) {
Console.Clear ();
var codigo = 0;
var encerrouPrograma = false;
#region foreach puxar dicionario
do
{
Console.Clear(); /*Limpar o console */
#region Area do menu
string menuBar = "********************=================================********************";
System.Console.WriteLine (menuBar);
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.ForegroundColor = ConsoleColor.Black;
System.Console.WriteLine ("| Bem vindo ao ZooCyber - Seu ZooLógico digital |");
Console.ResetColor ();
System.Console.WriteLine (menuBar);
System.Console.WriteLine ();
System.Console.WriteLine($"{"", 2}Temos os seguintes animais disponiveis para você: ");
System.Console.WriteLine();/* Pular linha */
#endregion
foreach (var item in Arca.listaanimais.Values)
{
System.Console.WriteLine($"{"", 5} 00{++codigo}. {item.GetType().Name}"); /*"{" ", 5} - Está apenas dando espaço na linha, {++codigo} - Está iniciando a contagem dos itens */
}
System.Console.WriteLine(); /* Pular linha */
System.Console.Write($"{"", 2}Insira o codigo do animal desejado: ");
try
{
codigo = 0;
var opcaoUsuario = int.Parse(Console.ReadLine());
var animal = Arca.listaanimais[opcaoUsuario];
System.Console.WriteLine(); /*Pular linha */
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.ForegroundColor = ConsoleColor.Black;
ClassificarAnimais(animal);
Console.ResetColor();
System.Console.WriteLine();/*Pular linha */
}
catch(Exception e)
{
System.Console.Write("Insira um codigo valido!!! Aperte enter para tentar novamente.");
Console.ReadLine();
}
}while(!encerrouPrograma);
System.Console.WriteLine();
#endregion
}
public static void ClassificarAnimais (Animais animais)
{
var classe = animais.GetType();
var @interface = classe.GetInterfaces().FirstOrDefault();
if((typeof(IAereo)).Equals(@interface))
{
System.Console.WriteLine($"Animal escolhido: {classe.Name}, este vai para a Gaiola!");
}
else if((typeof(IAquatico)).Equals(@interface))
{
System.Console.WriteLine($"Animal escolhido: {classe.Name}, este vai para a Piscina");
}
else if((typeof(IBranquiado)).Equals(@interface))
{
System.Console.WriteLine($"Animal escolhido: {classe.Name}, este vai para o Aquario!");
}
else if((typeof(IEscalador)).Equals(@interface))
{
System.Console.WriteLine($"Animal escolhido: {classe.Name}, este vai para a Casa na árvore!");
}
else if((typeof(IQuinofilo)).Equals(@interface))
{
System.Console.WriteLine($"Animal escolhido: {classe.Name}, este vai para a Piscina Gelada!");
}
else if((typeof(ITerrestre)).Equals(@interface))
{
System.Console.WriteLine($"Animal escolhido: {classe.Name}, este vai para o Pasto ou Caverna de Pedra!");
}
Console.ReadLine();
}
}
} |
using FastSQL.API.ViewModels;
using FastSQL.Core;
using FastSQL.Sync.Core;
using FastSQL.Sync.Core.Enums;
using FastSQL.Sync.Core.Indexer;
using FastSQL.Sync.Core.Models;
using FastSQL.Sync.Core.Puller;
using FastSQL.Sync.Core.Pusher;
using FastSQL.Sync.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
namespace FastSQL.API.Controllers
{
[Route("api/[controller]")]
public class AttributesController: Controller
{
public ResolverFactory ResolverFactory { get; set; }
private readonly IEnumerable<IProcessor> processors;
private readonly IEnumerable<IAttributePuller> pullers;
private readonly IEnumerable<IAttributeIndexer> indexers;
private readonly IEnumerable<IAttributePusher> pushers;
private readonly DbTransaction transaction;
private readonly JsonSerializer serializer;
public AttributesController(
IEnumerable<IProcessor> processors,
IEnumerable<IAttributePuller> pullers,
IEnumerable<IAttributeIndexer> indexers,
IEnumerable<IAttributePusher> pushers,
DbTransaction transaction,
JsonSerializer serializer)
{
this.processors = processors;
this.pullers = pullers;
this.indexers = indexers;
this.pushers = pushers;
this.transaction = transaction;
this.serializer = serializer;
}
[HttpPost]
public IActionResult Create([FromBody] CreateAttributeViewModel model)
{
AttributeRepository attributeRepository = null;
try
{
attributeRepository = ResolverFactory.Resolve<AttributeRepository>();
var result = attributeRepository.Create(new
{
model.Name,
model.Description,
model.SourceConnectionId,
model.DestinationConnectionId,
model.EntityId,
model.SourceProcessorId,
model.DestinationProcessorId,
State = 0
});
if (model.Options != null && model.Options.Count() > 0)
{
attributeRepository.LinkOptions(result, model.Options);
}
transaction.Commit();
return Ok(result);
}
catch
{
transaction.Rollback();
throw;
}
finally
{
attributeRepository?.Dispose();
}
}
[HttpPut("{id}/options")]
public IActionResult UpdateOptions(string id, [FromBody] IEnumerable<OptionItem> options)
{
AttributeRepository attributeRepository = null;
try
{
attributeRepository = ResolverFactory.Resolve<AttributeRepository>();
if (options != null && options.Count() > 0)
{
attributeRepository.LinkOptions(id, options);
}
transaction.Commit();
return Ok(id);
}
catch
{
transaction.Rollback();
throw;
}
finally
{
attributeRepository?.Dispose();
}
}
[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody] CreateAttributeViewModel model)
{
AttributeRepository attributeRepository = null;
try
{
attributeRepository = ResolverFactory.Resolve<AttributeRepository>();
var attributeModel = attributeRepository.GetById(id);
var state = attributeModel.State;
if (model.Enabled)
{
state = (state | EntityState.Disabled) ^ EntityState.Disabled;
}
else
{
state = state | EntityState.Disabled;
}
var result = attributeRepository.Update(id, new
{
model.Name,
model.Description,
model.SourceConnectionId,
model.DestinationConnectionId,
model.EntityId,
model.SourceProcessorId,
model.DestinationProcessorId,
State = state
});
if (model.Options != null && model.Options.Count() > 0)
{
attributeRepository.LinkOptions(id, model.Options);
}
transaction.Commit();
return Ok(result);
}
catch
{
transaction.Rollback();
throw;
}
finally
{
attributeRepository?.Dispose();
}
}
private IEnumerable<OptionItem> GetPullerTemplateOptions(EntityModel e, AttributeModel a)
{
using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>())
{
if (string.IsNullOrWhiteSpace(a.SourceConnectionId.ToString()) || a.SourceConnectionId == Guid.Empty)
{
return new List<OptionItem>();
}
var conn = connectionRepository.GetById(a.SourceConnectionId.ToString());
var puller = pullers.FirstOrDefault(p => p.IsImplemented(a.SourceProcessorId, e.SourceProcessorId, conn.ProviderId));
return puller?.Options ?? new List<OptionItem>();
}
}
private IEnumerable<OptionItem> GetIndexerTemplateOptions(EntityModel e, AttributeModel a)
{
var indexer = indexers.FirstOrDefault(i => i.IsImplemented(a.SourceConnectionId.ToString(), e.SourceConnectionId.ToString(), a.SourceProcessorId));
return indexer?.Options ?? new List<OptionItem>();
}
private IEnumerable<OptionItem> GetPusherTemplateOptions(EntityModel e, AttributeModel a)
{
using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>())
{
if (string.IsNullOrWhiteSpace(a.DestinationConnectionId.ToString()) || a.DestinationConnectionId == Guid.Empty)
{
return new List<OptionItem>();
}
var conn = connectionRepository.GetById(a.DestinationConnectionId.ToString());
var pusher = pushers.FirstOrDefault(p => p.IsImplemented(a.DestinationProcessorId, e.DestinationProcessorId, conn.ProviderId));
return pusher?.Options ?? new List<OptionItem>();
}
}
[HttpPost("options/template")]
public IActionResult GetOptions([FromBody] AttributeTemplateOptionRequestViewModel model)
{
using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>())
using (var entityRepository = ResolverFactory.Resolve<EntityRepository>())
{
var entityModel = entityRepository.GetById(model.EntityId);
ConnectionModel sourceConnection = null;
ConnectionModel destinationConnection = null;
IAttributePuller puller = null;
IAttributePusher pusher = null;
IIndexer indexer;
if (!string.IsNullOrWhiteSpace(model.SourceConnectionId))
{
sourceConnection = connectionRepository.GetById(model.SourceConnectionId);
puller = pullers.FirstOrDefault(p => p.IsImplemented(model.SourceProcessorId, entityModel.SourceProcessorId, sourceConnection.ProviderId));
}
if (!string.IsNullOrWhiteSpace(model.DestinationConnectionId))
{
destinationConnection = connectionRepository.GetById(model.DestinationConnectionId);
pusher = pushers.FirstOrDefault(p => p.IsImplemented(model.DestinationProcessorId, entityModel.DestinationProcessorId, destinationConnection.ProviderId));
}
indexer = indexers.FirstOrDefault(i => i.IsImplemented(model.SourceConnectionId, entityModel.SourceConnectionId.ToString(), model.SourceProcessorId));
return Ok(new
{
Puller = puller?.Options ?? new List<OptionItem>(),
Indexer = indexer?.Options ?? new List<OptionItem>(),
Pusher = pusher?.Options ?? new List<OptionItem>(),
});
}
}
[HttpPost("{id}/options/template")]
public IActionResult GetOptions(Guid id, [FromBody] AttributeTemplateOptionRequestViewModel model)
{
using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>())
using (var entityRepository = ResolverFactory.Resolve<EntityRepository>())
using (var attributeRepository = ResolverFactory.Resolve<AttributeRepository>())
{
var attribute = attributeRepository.GetById(id.ToString());
var entityModel = entityRepository.GetById(model.EntityId);
var options = attributeRepository.LoadOptions(id.ToString());
var instanceOptions = options.Select(o => new OptionItem
{
Name = o.Key,
Value = o.Value
}).ToList();
ConnectionModel sourceConnection = null;
ConnectionModel destinationConnection = null;
IAttributePuller puller = null;
IAttributePusher pusher = null;
IIndexer indexer;
if (!string.IsNullOrWhiteSpace(model.SourceConnectionId))
{
sourceConnection = connectionRepository.GetById(model.SourceConnectionId);
puller = pullers.FirstOrDefault(p => p.IsImplemented(model.SourceProcessorId, entityModel.SourceProcessorId, sourceConnection.ProviderId));
puller.SetOptions(instanceOptions);
}
if (!string.IsNullOrWhiteSpace(model.DestinationConnectionId))
{
destinationConnection = connectionRepository.GetById(model.DestinationConnectionId);
pusher = pushers.FirstOrDefault(p => p.IsImplemented(model.DestinationProcessorId, entityModel.DestinationProcessorId, destinationConnection.ProviderId));
pusher.SetOptions(instanceOptions);
}
indexer = indexers.FirstOrDefault(i => i.IsImplemented(model.SourceConnectionId, entityModel.SourceConnectionId.ToString(), model.SourceProcessorId));
indexer?.SetOptions(instanceOptions);
return Ok(new
{
Puller = puller?.Options ?? new List<OptionItem>(),
Indexer = indexer?.Options ?? new List<OptionItem>(),
Pusher = pusher?.Options ?? new List<OptionItem>(),
});
}
}
[HttpGet("{id}")]
public IActionResult GetById(string id)
{
using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>())
using (var entityRepository = ResolverFactory.Resolve<EntityRepository>())
using (var attributeRepository = ResolverFactory.Resolve<AttributeRepository>())
{
var a = attributeRepository.GetById(id);
var entity = entityRepository.GetById(a.EntityId.ToString());
var options = attributeRepository.LoadOptions(a.Id.ToString());
var jEntity = JObject.FromObject(a, serializer);
var templateOpts = new List<OptionItem>();
templateOpts.AddRange(GetPullerTemplateOptions(entity, a));
templateOpts.AddRange(GetPusherTemplateOptions(entity, a));
templateOpts.AddRange(GetIndexerTemplateOptions(entity, a));
var destConnection = connectionRepository.GetById(a.DestinationConnectionId.ToString());
var cOptions = options.Where(o => o.EntityId == a.Id.ToString() && o.EntityType == EntityType.Attribute);
var optionItems = new List<OptionItem>();
foreach (var po in templateOpts)
{
var o = cOptions.FirstOrDefault(oo => oo.Key == po.Name);
if (o != null)
{
po.Value = o.Value;
}
optionItems.Add(po);
}
jEntity.Add("options", JArray.FromObject(optionItems, serializer));
return Ok(jEntity);
}
}
[HttpGet]
public IActionResult Get()
{
using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>())
using (var entityRepository = ResolverFactory.Resolve<EntityRepository>())
using (var attributeRepository = ResolverFactory.Resolve<AttributeRepository>())
{
var attributes = attributeRepository.GetAll();
var entities = entityRepository.GetByIds(attributes.Select(a => a.EntityId.ToString()));
var options = attributeRepository.LoadOptions(attributes.Select(c => c.Id.ToString()));
return Ok(attributes.Select(a =>
{
var jEntity = JObject.FromObject(a, serializer);
var entity = entities.FirstOrDefault(e => e.Id == a.EntityId);
var templateOpts = new List<OptionItem>();
templateOpts.AddRange(GetPullerTemplateOptions(entity, a));
templateOpts.AddRange(GetPusherTemplateOptions(entity, a));
templateOpts.AddRange(GetIndexerTemplateOptions(entity, a));
var destConnection = connectionRepository.GetById(a.DestinationConnectionId.ToString());
var cOptions = options.Where(o => o.EntityId == a.Id.ToString() && o.EntityType == EntityType.Attribute);
var optionItems = new List<OptionItem>();
foreach (var po in templateOpts)
{
var o = cOptions.FirstOrDefault(oo => oo.Key == po.Name);
if (o != null)
{
po.Value = o.Value;
}
optionItems.Add(po);
}
jEntity.Add("options", JArray.FromObject(optionItems, serializer));
return jEntity;
}));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using Bosdyn.Api;
using Grpc.Core;
using Grpc.Core.Logging;
using SpotServer.services;
namespace SpotServer
{
internal class Program
{
private const int Port = 443;
public static void Main(string[] args)
{
GrpcEnvironment.SetLogger(new ConsoleLogger());
Server server = new Server
{
Services =
{
AuthService.BindService(new SpotAuthService()),
RobotIdService.BindService(new SpotRobotIdService()),
DirectoryService.BindService(new SpotDirectoryService()),
TimeSyncService.BindService(new SpotTimeSyncService()),
EstopService.BindService(new SpotEstopService()),
LeaseService.BindService(new SpotLeaseService()),
PowerService.BindService(new SpotPowerService()),
RobotStateService.BindService(new SpotRobotStateService()),
RobotCommandService.BindService(new SpotRobotCommandService()),
ImageService.BindService(new SpotImageService())
},
Ports = { new ServerPort(
"0.0.0.0",
Port,
new SslServerCredentials(
new List<KeyCertificatePair>() {
new KeyCertificatePair(
File.ReadAllText(@"server.crt"),
File.ReadAllText(@"server.key")
)},
File.ReadAllText(@"ca.crt"),
false
)
)},
};
server.Start();
Console.WriteLine("Virtual spot 001 is active on port " + Port);
Console.WriteLine("Press any key to shutdown");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class DirectorTecnico : Persona
{
private int aniosExperiencia;
/// <summary>
/// Constructor Director Tectino
/// <param name="nombre"></param>
/// <param name="apellido"></param>
/// <param name="edad"></param>
/// <param name="dni"></param>
/// <param name="aniosExperiencia"></param>
/// </summary>
public DirectorTecnico(string nombre, string apellido, int edad, int dni, int aniosExperiencia)
:base(nombre,apellido,edad,dni)
{
this.AniosExperiencia = aniosExperiencia;
}
/// <summary>
/// Devuelve el Anios de Experiencia
/// </summary>
public int AniosExperiencia
{
get
{
return this.aniosExperiencia;
}
set
{
if (value >= 0)
{
this.aniosExperiencia = value;
}
else
{
this.aniosExperiencia = 0;
}
}
}
/// <summary>
/// Muestra los campos de Director Tecnico
/// </summary>
public override string Mostrar()
{
StringBuilder datos = new StringBuilder();
return datos.AppendFormat("{0}, {1}\tEdad: {2}\tDNI: {3}\t Anios de Experiencia: {4}", this.Apellido, this.Nombre, this.Edad, this.Dni,this.AniosExperiencia).ToString();
}
/// <summary>
/// Valida Aptitud
/// </summary>
public override bool ValidarAptitud()
{
if (this.AniosExperiencia >= 2 && this.Edad < 65)
{
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using SiscomSoft.Models;
using SiscomSoft.Comun;
using SiscomSoft.Controller;
namespace SiscomSoft_Desktop.Views
{
public partial class FrmCustomCliente : Form
{
#region VARIABLES
public static int PKCLIENTE;
public String ImagenString { get; set; }
public Bitmap ImagenBitmap { get; set; }
public Boolean SaveOrCreate = false;
#endregion
#region FUNCIONES
/// <summary>
/// Funcion encargada de cargar los clientes en el dgvAllClientes
/// </summary>
private void cargarClientes()
{
dgvAllClientes.DataSource = ManejoCliente.Buscar(txtBuscar.Text, 1);
}
/// <summary>
/// Funcion encargada de asignar los valores la variable local nCliente a los controles correspondientes
/// </summary>
private void ActualizarCliente()
{
Cliente nCliente = ManejoCliente.getById(PKCLIENTE); // Se llama a la funcion getById de ManejoCliente, se le da la variable statica PKCLIENTE y el resultado se le asigna a nCliente
// Se valida que las propiedades de la variable nCliente no esten vacias
if (nCliente.sRfc != null)
{
txtUpdateRFC.Text = nCliente.sRfc; // Se asigna el valor de sRfc a txtUpdateRFC
}
if (nCliente.sRazonSocial != null)
{
txtUpdateRazonSocial.Text = nCliente.sRazonSocial;
}
if (nCliente.iPersona != 0)
{
txtUpdatePersona.Text = nCliente.iPersona.ToString();
}
if (nCliente.sCurp != null)
{
txtUpdateCURP.Text = nCliente.sCurp;
}
txtUpdateNombre.Text = nCliente.sNombre;
if (nCliente.sPais != null)
{
txtUpdatePais.Text = nCliente.sPais;
}
if (nCliente.iCodPostal != 0)
{
txtUpdateCP.Text = nCliente.iCodPostal.ToString();
}
if (nCliente.sEstado != null)
{
txtUpdateEstado.Text = nCliente.sEstado;
}
if (nCliente.sLocalidad != null)
{
txtUpdateLocalidad.Text = nCliente.sLocalidad;
}
if (nCliente.sMunicipio != null)
{
txtUpdateMunicipio.Text = nCliente.sMunicipio;
}
txtUpdateColonia.Text = nCliente.sColonia;
txtUpdateCalle.Text = nCliente.sCalle;
txtUpdateNumExterior.Text = nCliente.iNumExterior.ToString();
txtUpdateNumInterior.Text = nCliente.iNumInterior.ToString();
txtUpdateReferencia.Text = nCliente.sReferencia;
if (nCliente.sTelFijo != null)
{
txtUpdateTelFijo.Text = nCliente.sTelFijo;
}
txtUpdateTelMovil.Text = nCliente.sTelMovil;
if (nCliente.sReferencia != null)
{
txtUpdateReferencia.Text = nCliente.sReferencia;
}
if (nCliente.iTipoCliente == 1)
{
cmbUpdateTipoCliente.SelectedIndex = 0;
}
else
{
cmbUpdateTipoCliente.SelectedIndex = 1;
}
if (nCliente.sNumCuenta != null)
{
txtUpdateNumCuenta.Text = nCliente.sNumCuenta;
}
#region status
// Se valida el iStatus y se incializa el cmbUpdateStatus segun la validacion
if (nCliente.iStatus == 1)
{
cmbUpdateStatus.SelectedIndex = 0;
}
else if (nCliente.iStatus == 2)
{
cmbUpdateStatus.SelectedIndex = 1;
}
else if (nCliente.iStatus == 3)
{
cmbUpdateStatus.SelectedIndex = 2;
}
else if (nCliente.iStatus == 4)
{
cmbUpdateStatus.SelectedIndex = 3;
}
#endregion
if (nCliente.sTipoPago != null)
{
#region tipo pago
// Se valida el sTipoPago y se incializa el cmbUpdateTipoPago segun la validacion
if (nCliente.sTipoPago == "1")
{
cmbUpdateTipoPago.SelectedIndex = 0;
}
else if (nCliente.sTipoPago == "2")
{
cmbUpdateTipoPago.SelectedIndex = 1;
}
else if (nCliente.sTipoPago == "3")
{
cmbUpdateTipoPago.SelectedIndex = 2;
}
else if (nCliente.sTipoPago == "4")
{
cmbUpdateTipoPago.SelectedIndex = 3;
}
else if (nCliente.sTipoPago == "5")
{
cmbUpdateTipoPago.SelectedIndex = 4;
}
else if (nCliente.sTipoPago == "6")
{
cmbUpdateTipoPago.SelectedIndex = 5;
}
else if (nCliente.sTipoPago == "7")
{
cmbUpdateTipoPago.SelectedIndex = 6;
}
else if (nCliente.sTipoPago == "8")
{
cmbUpdateTipoPago.SelectedIndex = 7;
}
else if (nCliente.sTipoPago == "9")
{
cmbUpdateTipoPago.SelectedIndex = 8;
}
else if (nCliente.sTipoPago == "10")
{
cmbUpdateTipoPago.SelectedIndex = 9;
}
else if (nCliente.sTipoPago == "11")
{
cmbUpdateTipoPago.SelectedIndex = 10;
}
else if (nCliente.sTipoPago == "12")
{
cmbUpdateTipoPago.SelectedIndex = 11;
}
else if (nCliente.sTipoPago == "13")
{
cmbUpdateTipoPago.SelectedIndex = 12;
}
else if (nCliente.sTipoPago == "14")
{
cmbUpdateTipoPago.SelectedIndex = 13;
}
else if (nCliente.sTipoPago == "15")
{
cmbUpdateTipoPago.SelectedIndex = 14;
}
else if (nCliente.sTipoPago == "16")
{
cmbUpdateTipoPago.SelectedIndex = 15;
}
else if (nCliente.sTipoPago == "17")
{
cmbUpdateTipoPago.SelectedIndex = 16;
}
else if (nCliente.sTipoPago == "18")
{
cmbUpdateTipoPago.SelectedIndex = 17;
}
else if (nCliente.sTipoPago == "19")
{
cmbUpdateTipoPago.SelectedIndex = 18;
}
else if (nCliente.sTipoPago == "20")
{
cmbUpdateTipoPago.SelectedIndex = 19;
}
#endregion
}
if (nCliente.sCorreo != null)
{
txtUpdateCorreo.Text = nCliente.sCorreo;
}
if (nCliente.sConPago != null)
{
txtUpdateCondicionesPago.Text = nCliente.sConPago;
}
if (nCliente.sLogo == null)
{
pcbUpdateFoto.Image = null;
}
else
{
pcbUpdateFoto.Image = ToolImagen.Base64StringToBitmap(nCliente.sLogo);
}
}
#endregion
#region MAIN
public FrmCustomCliente()
{
InitializeComponent();
dgvAllClientes.AutoGenerateColumns = false;
}
private void FrmCustomCliente_Load(object sender, EventArgs e)
{
timer1.Start(); // Se inicialisa el timer1
cargarClientes(); // Se llama a la funcion cargarClientes()
}
private void txtBuscar_TextChanged(object sender, EventArgs e)
{
cargarClientes(); // Se llama a la funcion cargarClientes() cada vez que se cambie el texto del txtBuscar
}
#endregion
#region ALL CLIENTES
private void btnSeleccionarCliente_Click(object sender, EventArgs e)
{
if (dgvAllClientes.RowCount >= 1) // Se valida que la candidad de filas en el dgvAllClientes sea igual a 1 o mayor
{
Cliente nCliente = ManejoCliente.getById(Convert.ToInt32(dgvAllClientes.CurrentRow.Cells[0].Value)); // Se llama a la funcion getById de ManejoCliente dandole el valor de la columna 0 del dgvAllClientes y el resultado se asigna a la variable nCliente
FrmDetalleVentasOneToOne.mCliente = nCliente; // Se asigna nCliente a la variable statica mCliente
FrmDetalleVentasOneToOne v = new FrmDetalleVentasOneToOne(); // Se instancia la ventana FrmDetalleVentasOneToOne
this.Close(); // Se cierra la ventana actual
v.ShowDialog(); // Se abre la ventana FrmDetalleVentasOneToOne
}
}
private void btnNuevoCliente_Click(object sender, EventArgs e)
{
pnlAllClientes.Visible = false; // Se cambia la propiedad visible del pnlAllClientes a false para no ser mostrado en la vista
pnlEditCliente.Visible = false; // Se cambia la propiedad visible del pnlEditCliente a false para no ser mostrado en la vista
gbCreateAccount.Visible = false; // Se cambia la propiedad visible del gbCreateAccount a false para no ser mostrado en la vista
pnlNewCliente.Visible = true; // Se cambia la propiedad visible del pnlNewCliente a false para no ser mostrado en la vista
gpbSaveCliente.Visible = true; // Se cambia la propiedad visible del gpbSaveCliente a false para no ser mostrado en la vista
txtAddNombre.Focus(); // Se inicia la propiedad focus del txtAddNombre
}
private void btnCancelarCustomClient_Click(object sender, EventArgs e)
{
this.Close(); // Se cierra la ventana actual
FrmDetalleVentasOneToOne v = new Views.FrmDetalleVentasOneToOne(); // Se instancia la ventana FrmDetalleVentasOneToOne
v.ShowDialog(); // Se abre la ventana FrmDetalleVentasOneToOne
}
private void btnEditarCliente_Click(object sender, EventArgs e)
{
if (dgvAllClientes.RowCount >= 1) // Se valida que las filas de el dgvAllClientes sea 1 o mayor
{
PKCLIENTE = Convert.ToInt32(dgvAllClientes.CurrentRow.Cells[0].Value); // Se le asigna el valor de la columna 0 combertida a entero, a la variable statica PKCLIENTE
// Se borra el texto de todos los textBox
txtUpdateRFC.Clear();
txtUpdateRazonSocial.Clear();
txtUpdatePersona.Clear();
txtUpdateCURP.Clear();
txtUpdateNombre.Clear();
txtUpdatePais.Clear();
txtUpdateCP.Clear();
txtUpdateEstado.Clear();
txtUpdateMunicipio.Clear();
txtUpdateLocalidad.Clear();
txtUpdateColonia.Clear();
txtUpdateCalle.Clear();
txtUpdateNumInterior.Clear();
txtUpdateNumExterior.Clear();
txtUpdateTelFijo.Clear();
txtUpdateTelMovil.Clear();
txtUpdateCorreo.Clear();
txtUpdateNumCuenta.Clear();
txtUpdateCondicionesPago.Clear();
txtUpdateReferencia.Clear();
pcbUpdateFoto.Image = null;
ActualizarCliente();
pnlAllClientes.Visible = false;
pnlEditCliente.Visible = true;
txtUpdateRFC.Focus();
}
}
#endregion
#region NEW CLIENTE
private void txtNomCliente_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear(); // Se borran los valores asignados a ErrorProvider cuando el texto cambia
}
private void txtColonia_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear(); // Se borran los valores asignados a ErrorProvider cuando el texto cambia
}
private void txtCalle_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear(); // Se borran los valores asignados a ErrorProvider cuando el texto cambia
}
private void txtNoExterior_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear(); // Se borran los valores asignados a ErrorProvider cuando el texto cambia
}
private void txtNoInterior_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear(); // Se borran los valores asignados a ErrorProvider cuando el texto cambia
}
private void txtTelMovil_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear(); // Se borran los valores asignados a ErrorProvider cuando el texto cambia
}
private void btnGuardar_Click(object sender, EventArgs e)
{
if (SaveOrCreate != true) // Se valida que la variable SaveOrCrete no sea false
{
// Se valida que los textBox esten vacios
if (this.txtAddNombre.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddNombre, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddNombre, "Campo necesario");
this.txtAddNombre.Focus();
}
else if (this.txtAddColonia.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddColonia, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddColonia, "Campo necesario");
this.txtAddColonia.Focus();
}
else if (this.txtAddCalle.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddCalle, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddCalle, "Campo necesario");
this.txtAddCalle.Focus();
}
else if (this.txtAddNoExterior.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddNoExterior, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddNoExterior, "Campo necesario");
this.txtAddNoExterior.Focus();
}
else if (this.txtAddTelMovil.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddTelMovil, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddTelMovil, "Campo necesario");
this.txtAddTelMovil.Focus();
}
else
{
Cliente nCliente = new Cliente();
nCliente.sNombre = txtAddNombre.Text;
nCliente.sColonia = txtAddColonia.Text;
nCliente.sCalle = txtAddCalle.Text;
if (txtAddNumInterir.Text == "")
{
nCliente.iNumInterior = 0;
}else
{
nCliente.iNumInterior = Convert.ToInt32(txtAddNoInterior.Text);
}
nCliente.iNumExterior = Convert.ToInt32(txtAddNoExterior.Text);
nCliente.sTelMovil = txtAddTelMovil.Text;
ManejoCliente.RegistrarNuevoCliente(nCliente);
MessageBox.Show("¡Cliente Guardado!");
txtAddNombre.Clear();
txtAddColonia.Clear();
txtAddCalle.Clear();
txtAddNoInterior.Clear();
txtAddNoExterior.Clear();
txtAddTelMovil.Clear();
cargarClientes();
gpbSaveCliente.Visible = false;
pnlNewCliente.Visible = false;
pnlNewCliente.Visible = false;
pnlAllClientes.Visible = true;
}
}
else
{
if (this.txtAddRFC.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddRFC, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddRFC, "Campo necesario");
this.txtAddRFC.Focus();
}
else if (this.txtAddRazonSocial.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddRazonSocial, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddRazonSocial, "Campo necesario");
this.txtAddRazonSocial.Focus();
}
else if (this.txtAddPersona.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddPersona, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddPersona, "Campo necesario");
this.txtAddPersona.Focus();
}
else if (this.txtAddCurp.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddCurp, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddCurp, "Campo necesario");
this.txtAddCurp.Focus();
}
else if (this.txtAddNom.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddNom, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddNom, "Campo necesario");
this.txtAddNom.Focus();
}
else if (this.txtAddPais.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddPais, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddPais, "Campo necesario");
this.txtAddPais.Focus();
}
else if (this.txtCodigoPosAddCli.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtCodigoPosAddCli, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtCodigoPosAddCli, "Campo necesario");
this.txtCodigoPosAddCli.Focus();
}
else if (this.txtAddEstado.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddEstado, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddEstado, "Campo necesario");
this.txtAddEstado.Focus();
}
else if (this.txtAddMunicipio.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddMunicipio, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddMunicipio, "Campo necesario");
this.txtAddMunicipio.Focus();
}
else if (this.txtAddCol.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddCol, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddCol, "Campo necesario");
this.txtAddCol.Focus();
}
else if (this.txtAddCall.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddCall, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddCall, "Campo necesario");
this.txtAddCall.Focus();
}
else if (this.txtAddLocalidad.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddLocalidad, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddLocalidad, "Campo necesario");
this.txtAddLocalidad.Focus();
}
else if (this.txtAddNumExterior.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddNumExterior, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddNumExterior, "Campo necesario");
this.txtAddNumExterior.Focus();
}
else if (this.txtAddTelMov.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddTelMov, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddTelMov, "Campo necesario");
this.txtAddTelMov.Focus();
}
else if (this.txtAddTelFijo.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddTelFijo, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddTelFijo, "Campo necesario");
this.txtAddTelFijo.Focus();
}
else if (this.cmbStatus.Text == "Seleccione Una Opcion")
{
this.ErrorProvider.SetIconAlignment(this.cmbStatus, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.cmbStatus, "Favor de Seleccionar una Opcion");
this.cmbStatus.Focus();
}
else if (this.txtAddNoCuenta.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddNoCuenta, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddNoCuenta, "Campo necesario");
this.txtAddNoCuenta.Focus();
}
else if (this.cmbAddTipoCliente.Text == "Seleccione Una Opcion")
{
this.ErrorProvider.SetIconAlignment(this.cmbAddTipoCliente, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.cmbAddTipoCliente, "Favor de Seleccionar Una Opcion");
this.cmbAddTipoCliente.Focus();
}
else if (this.cmbAddMetodoPago.Text == "Seleccione Una Opcion")
{
this.ErrorProvider.SetIconAlignment(this.cmbAddMetodoPago, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.cmbAddMetodoPago, "Favor de Seleccionar una opcion");
this.cmbAddMetodoPago.Focus();
}
else if (this.txtAddCorreo.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddCorreo, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddCorreo, "Campo necesario");
this.txtAddCorreo.Focus();
}
else if (this.txtAddCondicionPago.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddCondicionPago, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddCondicionPago, "Campo necesario");
this.txtAddCondicionPago.Focus();
}
else if (this.txtAddReferencia.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtAddReferencia, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtAddReferencia, "Campo necesario");
this.txtAddReferencia.Focus();
}
else
{
Cliente nCliente = new Cliente();
nCliente.sRfc = txtAddRFC.Text;
nCliente.sRazonSocial = txtAddRazonSocial.Text;
if (txtAddPersona.Text != "")
{
nCliente.iPersona = Convert.ToInt32(txtAddPersona.Text);
}else
{
nCliente.iPersona = 0;
}
nCliente.sCurp = txtAddCurp.Text;
nCliente.sNombre = txtAddNom.Text;
nCliente.sPais = txtAddPais.Text;
if (txtCodigoPosAddCli.Text != "")
{
nCliente.iCodPostal = Convert.ToInt32(txtCodigoPosAddCli.Text);
}
else
{
nCliente.iCodPostal = 0;
}
nCliente.sEstado = txtAddEstado.Text;
nCliente.sMunicipio = txtAddMunicipio.Text;
nCliente.sLocalidad = txtAddLocalidad.Text;
nCliente.sColonia = txtAddCol.Text;
nCliente.sCalle = txtAddCall.Text;
nCliente.sReferencia = txtAddReferencia.Text;
nCliente.iNumExterior = Convert.ToInt32(txtAddNumExterior.Text);
if (txtAddNumInterir.Text != "")
{
nCliente.iNumInterior = Convert.ToInt32(txtAddNumInterir.Text);
}else
{
nCliente.iNumInterior = 0;
}
nCliente.sTelFijo = txtAddTelFijo.Text;
nCliente.sTelMovil = txtAddTelMov.Text;
nCliente.sCorreo = txtAddCorreo.Text;
if (cmbStatus.SelectedIndex == 0)
{
nCliente.iStatus = 1;
}
else if (cmbStatus.SelectedIndex == 1)
{
nCliente.iStatus = 2;
}
else if (cmbStatus.SelectedIndex == 2)
{
nCliente.iStatus = 3;
}
else if (cmbStatus.SelectedIndex == 3)
{
nCliente.iStatus = 4;
}
if (this.cmbAddTipoCliente.SelectedIndex == 0)
{
nCliente.sTipoPago = "1";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 1)
{
nCliente.sTipoPago = "2";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 2)
{
nCliente.sTipoPago = "3";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 3)
{
nCliente.sTipoPago = "4";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 4)
{
nCliente.sTipoPago = "5";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 5)
{
nCliente.sTipoPago = "6";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 6)
{
nCliente.sTipoPago = "7";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 7)
{
nCliente.sTipoPago = "8";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 8)
{
nCliente.sTipoPago = "9";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 9)
{
nCliente.sTipoPago = "10";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 10)
{
nCliente.sTipoPago = "11";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 11)
{
nCliente.sTipoPago = "12";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 12)
{
nCliente.sTipoPago = "13";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 13)
{
nCliente.sTipoPago = "14";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 14)
{
nCliente.sTipoPago = "15";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 15)
{
nCliente.sTipoPago = "16";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 16)
{
nCliente.sTipoPago = "17";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 17)
{
nCliente.sTipoPago = "18";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 18)
{
nCliente.sTipoPago = "19";
}
else if (this.cmbAddTipoCliente.SelectedIndex == 19)
{
nCliente.sTipoPago = "20";
}
nCliente.sNumCuenta = txtAddNoCuenta.Text;
nCliente.sConPago = txtAddCondicionPago.Text;
if (cmbAddTipoCliente.SelectedIndex == 0)
{
nCliente.iTipoCliente = 1;
}
else if (cmbAddTipoCliente.SelectedIndex == 1)
{
nCliente.iTipoCliente = 2;
}
nCliente.sLogo = ImagenString;
ManejoCliente.RegistrarNuevoCliente(nCliente);
MessageBox.Show("¡Cliente Registrado!");
txtAddRFC.Clear();
txtAddRazonSocial.Clear();
txtAddPersona.Clear();
txtAddCurp.Clear();
txtAddNom.Clear();
txtAddPais.Clear();
txtCodigoPosAddCli.Clear();
txtAddEstado.Clear();
txtAddMunicipio.Clear();
txtAddLocalidad.Clear();
txtAddCol.Clear();
txtAddCall.Clear();
txtAddNumInterir.Clear();
txtAddNumExterior.Clear();
txtAddTelFijo.Clear();
txtAddTelMov.Clear();
txtAddCorreo.Clear();
txtAddNoCuenta.Clear();
txtAddCondicionPago.Clear();
pcbFoto.Image = null;
cargarClientes();
pnlNewCliente.Visible = false;
pnlAllClientes.Visible = true;
}
}
}
private void btnCreateCliente_Click(object sender, EventArgs e)
{
if (SaveOrCreate == false)
{
pnlEditCliente.Visible = false;
gpbSaveCliente.Visible = false;
pnlNewCliente.Visible = true;
gbCreateAccount.Visible = true;
SaveOrCreate = true;
txtAddRFC.Focus();
btnCreateCliente.Text = "Cliente Nuevo";
}
else
{
pnlEditCliente.Visible = false;
gbCreateAccount.Visible = false;
pnlNewCliente.Visible = true;
gpbSaveCliente.Visible = true;
SaveOrCreate = false;
txtAddNombre.Focus();
btnCreateCliente.Text = "Crear Cuenta";
}
}
private void btnCerrar_Click(object sender, EventArgs e)
{
pnlNewCliente.Visible = false;
gpbSaveCliente.Visible = false;
gbCreateAccount.Visible = false;
pnlAllClientes.Visible = true;
txtAddNombre.Clear();
txtAddColonia.Clear();
txtAddCalle.Clear();
txtAddNoInterior.Clear();
txtAddNoExterior.Clear();
txtAddTelMovil.Clear();
txtAddRFC.Clear();
txtAddRazonSocial.Clear();
txtAddPersona.Clear();
txtAddCurp.Clear();
txtAddNom.Clear();
txtAddPais.Clear();
txtCodigoPosAddCli.Clear();
txtAddEstado.Clear();
txtAddMunicipio.Clear();
txtAddLocalidad.Clear();
txtAddCol.Clear();
txtAddCall.Clear();
txtAddNumInterir.Clear();
txtAddNumExterior.Clear();
txtAddTelFijo.Clear();
txtAddTelMov.Clear();
txtAddCorreo.Clear();
txtAddNoCuenta.Clear();
txtAddCondicionPago.Clear();
pcbFoto.Image = null;
}
#endregion
#region CREATE ACCOUNT
private void txtAddRFC_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddRazonSocial_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddPersona_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddCurp_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddNom_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddPais_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtCodigoPosAddCli_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddEstado_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddMunicipio_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddCol_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddCall_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddLocalidad_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddNumExterior_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddNumInterir_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddTelMov_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddTelFijo_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddNoCuenta_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddCorreo_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtAddCondicionPago_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void btnExaminar_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog BuscarImagen = new OpenFileDialog();
BuscarImagen.Filter = "Archivos de Imagen|*.jpg;*.png;*gif;*.bmp";
//Aquí incluiremos los filtros que queramos.
BuscarImagen.FileName = "";
BuscarImagen.Title = "Seleccione una imagen";
if (BuscarImagen.ShowDialog() == DialogResult.OK)
{
string logo = BuscarImagen.FileName;
pcbFoto.ImageLocation = logo;
ImagenBitmap = new System.Drawing.Bitmap(logo);
ImagenString = ToolImagen.ToBase64String(ImagenBitmap, ImageFormat.Jpeg);
pcbFoto.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show("El archivo seleccionado no es un tipo de imagen válido" + ex.Message);
}
}
#endregion
#region UPDATE ACCOUNT
private void btnExaminarUpdateCli_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog BuscarImagen = new OpenFileDialog();
BuscarImagen.Filter = "Archivos de Imagen|*.jpg;*.png;*gif;*.bmp";
//Aquí incluiremos los filtros que queramos.
BuscarImagen.FileName = "";
BuscarImagen.Title = "Seleccione una imagen";
if (BuscarImagen.ShowDialog() == DialogResult.OK)
{
string logo = BuscarImagen.FileName;
pcbUpdateFoto.ImageLocation = logo;
ImagenBitmap = new System.Drawing.Bitmap(logo);
ImagenString = ToolImagen.ToBase64String(ImagenBitmap, ImageFormat.Jpeg);
pcbUpdateFoto.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show("El archivo seleccionado no es un tipo de imagen válido" + ex.Message);
}
}
private void txtUpdateNombre_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtUpdateColonia_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtUpdateCalle_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtUpdateNumExterior_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void txtUpdateTelMovil_TextChanged(object sender, EventArgs e)
{
ErrorProvider.Clear();
}
private void btnActualizar_Click(object sender, EventArgs e)
{
if (this.txtUpdateNombre.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtUpdateNombre, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtUpdateNombre, "Campo necesario");
this.txtUpdateNombre.Focus();
}
else if (this.txtUpdateColonia.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtUpdateColonia, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtUpdateColonia, "Campo necesario");
this.txtUpdateColonia.Focus();
}
else if (this.txtUpdateCalle.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtUpdateCalle, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtUpdateCalle, "Campo necesario");
this.txtUpdateCalle.Focus();
}
else if (this.txtUpdateNumExterior.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtUpdateNumExterior, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtUpdateNumExterior, "Campo necesario");
this.txtUpdateNumExterior.Focus();
}
else if (this.txtUpdateTelMovil.Text == "")
{
this.ErrorProvider.SetIconAlignment(this.txtUpdateTelMovil, ErrorIconAlignment.MiddleRight);
this.ErrorProvider.SetError(this.txtUpdateTelMovil, "Campo necesario");
this.txtUpdateTelMovil.Focus();
}
else
{
Cliente nCliente = new Cliente();
nCliente.idCliente = PKCLIENTE;
nCliente.sRfc = txtUpdateRFC.Text;
nCliente.sRazonSocial = txtUpdateRazonSocial.Text;
if (txtUpdatePersona.Text != "")
{
nCliente.iPersona = Convert.ToInt32(txtUpdatePersona.Text);
}
else
{
nCliente.iPersona = 0;
}
nCliente.sCurp = txtUpdateCURP.Text;
nCliente.sNombre = txtUpdateNombre.Text;
nCliente.sPais = txtUpdatePais.Text;
if (txtUpdateCP.Text != "")
{
nCliente.iCodPostal = Convert.ToInt32(txtUpdateCP.Text);
}else
{
nCliente.iCodPostal = 0;
}
nCliente.sColonia = txtUpdateColonia.Text;
nCliente.sEstado = txtUpdateEstado.Text;
nCliente.sMunicipio = txtUpdateMunicipio.Text;
nCliente.sLocalidad = txtUpdateLocalidad.Text;
nCliente.sCalle = txtUpdateCalle.Text;
nCliente.iNumExterior = Convert.ToInt32(txtUpdateNumExterior.Text);
if (txtUpdateNumInterior.Text != "")
{
nCliente.iNumInterior = Convert.ToInt32(txtUpdateNumInterior.Text);
}else
{
nCliente.iNumInterior = 0;
}
nCliente.sTelFijo = txtUpdateTelFijo.Text;
nCliente.sTelMovil = txtUpdateTelMovil.Text;
nCliente.sCorreo = txtUpdateCorreo.Text;
nCliente.sReferencia = txtUpdateReferencia.Text;
nCliente.sNumCuenta = txtUpdateNumCuenta.Text;
nCliente.sConPago = txtUpdateCondicionesPago.Text;
#region tipo pago
if (this.cmbUpdateTipoPago.SelectedIndex == 0)
{
nCliente.sTipoPago = "1";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 1)
{
nCliente.sTipoPago = "2";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 2)
{
nCliente.sTipoPago = "3";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 3)
{
nCliente.sTipoPago = "4";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 4)
{
nCliente.sTipoPago = "5";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 5)
{
nCliente.sTipoPago = "6";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 6)
{
nCliente.sTipoPago = "7";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 7)
{
nCliente.sTipoPago = "8";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 8)
{
nCliente.sTipoPago = "9";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 9)
{
nCliente.sTipoPago = "10";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 10)
{
nCliente.sTipoPago = "11";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 11)
{
nCliente.sTipoPago = "12";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 12)
{
nCliente.sTipoPago = "13";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 13)
{
nCliente.sTipoPago = "14";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 14)
{
nCliente.sTipoPago = "15";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 15)
{
nCliente.sTipoPago = "16";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 16)
{
nCliente.sTipoPago = "17";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 17)
{
nCliente.sTipoPago = "18";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 18)
{
nCliente.sTipoPago = "19";
}
else if (this.cmbUpdateTipoPago.SelectedIndex == 19)
{
nCliente.sTipoPago = "20";
}
#endregion
#region Status
if (cmbUpdateStatus.SelectedIndex == 0)
{
nCliente.iStatus = 1;
}
else if (cmbUpdateStatus.SelectedIndex == 1)
{
nCliente.iStatus = 2;
}
else if (cmbUpdateStatus.SelectedIndex == 2)
{
nCliente.iStatus = 3;
}
else if (cmbUpdateStatus.SelectedIndex == 3)
{
nCliente.iStatus = 4;
}
#endregion
nCliente.sLogo = ImagenString;
ManejoCliente.Modificar(nCliente);
MessageBox.Show("¡Cliente Actualizado!");
cargarClientes();
txtUpdateRFC.Clear();
txtUpdateRazonSocial.Clear();
txtUpdatePersona.Clear();
txtUpdateCURP.Clear();
txtUpdateNombre.Clear();
txtUpdatePais.Clear();
txtUpdateCP.Clear();
txtUpdateEstado.Clear();
txtUpdateMunicipio.Clear();
txtUpdateLocalidad.Clear();
txtUpdateColonia.Clear();
txtUpdateCalle.Clear();
txtUpdateNumInterior.Clear();
txtUpdateNumExterior.Clear();
txtUpdateTelFijo.Clear();
txtUpdateTelMovil.Clear();
txtUpdateCorreo.Clear();
txtUpdateNumCuenta.Clear();
txtUpdateCondicionesPago.Clear();
txtUpdateReferencia.Clear();
pcbUpdateFoto.Image = null;
pnlEditCliente.Visible = false;
pnlAllClientes.Visible = true;
}
}
private void btnCancelar_Click(object sender, EventArgs e)
{
PKCLIENTE = 0;
txtUpdateRFC.Clear();
txtUpdateRazonSocial.Clear();
txtUpdatePersona.Clear();
txtUpdateCURP.Clear();
txtUpdateNombre.Clear();
txtUpdatePais.Clear();
txtUpdateCP.Clear();
txtUpdateEstado.Clear();
txtUpdateMunicipio.Clear();
txtUpdateLocalidad.Clear();
txtUpdateColonia.Clear();
txtUpdateCalle.Clear();
txtUpdateNumInterior.Clear();
txtUpdateNumExterior.Clear();
txtUpdateTelFijo.Clear();
txtUpdateTelMovil.Clear();
txtUpdateCorreo.Clear();
txtUpdateNumCuenta.Clear();
txtUpdateCondicionesPago.Clear();
txtUpdateReferencia.Clear();
pcbUpdateFoto.Image = null;
pnlEditCliente.Visible = false;
pnlAllClientes.Visible = true;
}
#endregion
private void timer1_Tick(object sender, EventArgs e)
{
lblFecha.Text = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
}
}
}
|
using System;
using TechTalk.SpecFlow;
using NUnit.Framework;
namespace Feature
{
[Binding]
public class ViewTVGuideSteps
{
[Given(@"I Have selected channel (.*)")]
public void GivenIHaveSelectedAChannel(string chName)
{
ScenarioContext.Current.Set<string>(chName);
}
[When(@"I have selected a date (.*) days from today")]
public void WhenIHaveSelectedTodaysDate(int days)
{
string chName = ScenarioContext.Current.Get<string>();
BEO.Channel ch = new BEO.Channel(chName, DateTime.Now.AddDays(days));
ScenarioContext.Current.Set<BEO.Channel>(ch);
}
[Then(@"the result should be a list of between (.*) and (.*) programs")]
public void ThenTheResultShouldBeAListOfProgramsOnTheScreen(int fromSize, int toSize)
{
BEO.Channel ch = ScenarioContext.Current.Get<BEO.Channel>();
Assert.IsTrue(ch.Programs.Count > fromSize && ch.Programs.Count < toSize);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BrighterFutures.Models
{
public class UserAccount : BaseModel
{
[Required]
//[MinLength(6)]
//[MaxLength(30)]
//[RegularExpression(@"/^[a-zA-Z0-9_\.]+$/", "The username can only consist of alphabetical, number, dot and underscore")]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public List<Challenge_User> Challenages { get; set; }
public int PointsTotal { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name ="Facebook ID")]
public string FacebookAccount { get; set; }
[Display(Name = "PNC User ID")]
public string PncAccountNumber { get; set; }
}
}
|
using System.IO;
using UnityEditor;
using UnityEngine;
public class CreateAssetBundles
{
[MenuItem("Stencil/Build Asset Bundles")]
static void BuildAllAssetBundles()
{
const string dir = "AssetBundles";
var ios = $"{dir}/ios";
if (!Directory.Exists(ios)) Directory.CreateDirectory(ios);
var manifest = BuildPipeline.BuildAssetBundles(ios, BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.iOS);
Debug.Log($"iOS Bundle - {manifest.GetAssetBundleHash("stencilcrosspromo")}");
var android = $"{dir}/android";
if (!Directory.Exists(android)) Directory.CreateDirectory(android);
manifest = BuildPipeline.BuildAssetBundles(android, BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.Android);
Debug.Log($"Android Bundle - {manifest.GetAssetBundleHash("stencilcrosspromo")}");
}
} |
using Lfs.Web.Api.Filters;
using Ninject.Modules;
using Ninject.Web.WebApi.FilterBindingSyntax;
using System.Web.Http.Filters;
namespace Lfs.Web.Api.NinjectModules
{
public class FiltersModule : NinjectModule
{
public override void Load()
{
Bind<IExceptionFilter>().To<ExceptionFilter>().InSingletonScope();
this.BindHttpFilter<ExceptionFilter>(FilterScope.Global);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DAL;
using BUS;
using ControlLocalizer;
namespace GUI
{
public partial class f_themkiemke : Form
{
KetNoiDBDataContext db = new KetNoiDBDataContext();
t_gia sp = new t_gia();
public f_themkiemke()
{
InitializeComponent();
// This line of code is generated by Data Source Configuration Wizard
txtid.Properties.DataSource = new DAL.KetNoiDBDataContext().sanphams;
txtten.ReadOnly = true;
txtdvt.ReadOnly = true;
}
private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.Close();
}
private void btnluu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (txtid.Text == "" || txtten.Text == "" || txtkiemke.Text == "" || txtdvt.Text == "")
{
Lotus.MsgBox.ShowWarningDialog("Thông tin chưa đầy đủ - Vui lòng kiểm tra lại!");
}
else
{
{
sp.suakiemke(txtid.Text + "_" + Biencucbo.donvi, Biencucbo.donvi, txtid.Text.Trim(), float.Parse(txtkiemke.Text));
this.Close();
}
}
}
//load
private void f_themsanpham_Load(object sender, EventArgs e)
{
LanguageHelper.Translate(this);
LanguageHelper.Translate(barManager1);
this.Text = LanguageHelper.TranslateMsgString("." + Name + "_title", "Số Lượng Kiểm Kê").ToString();
changeFont.Translate(this);
changeFont.Translate(barManager1);
txtid.ReadOnly = true;
txtten.ReadOnly = true;
txtdvt.ReadOnly = true;
var lst = new DAL.KetNoiDBDataContext().r_giasps;
var thucthi = (from k in lst select k).Single(t => t.idsp == Biencucbo.ma && t.iddv == Biencucbo.donvi);
txtid.Text = thucthi.idsp;
//txtkiemke.Text = thucthi.kiemke.ToString();
}
private void txtid_EditValueChanged(object sender, EventArgs e)
{
try
{
var lst = (from a in db.sanphams select a).Single(t => t.id == txtid.Text);
txtten.Text = lst.tensp;
txtdvt.Text = lst.dvt;
}
catch
{
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KPI.Model.helpers;
namespace KPI.Model.DAO
{
public class KPIDAO
{
KPIDbContext _dbContext = null;
public KPIDAO()
{
this._dbContext = new KPIDbContext();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_dbContext.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using ApiRest2.Models;
using ApiRest2.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ApiRest2.Controllers
{
public class DoctorController : ApiController
{
//objeto de lectura para acceder al repositorio
static readonly IDoctor c = new RDoctor();
//Metodo Post
public HttpResponseMessage Post(Doctor item)
{
item = c.Post(item);
if (item == null)
{
//Construyendo respuesta del servidor
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Los datos del doctor no pueden ser nulos");
}
return Request.CreateResponse(HttpStatusCode.Created, item);
}
//Metodo Get
public HttpResponseMessage GetAll()
{
var items = c.GetAll();
if (items.Count()==0)
{
//Construyendo respuesta del servidor
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay registros de doctor");
}
return Request.CreateResponse(HttpStatusCode.OK, items);
}
//Metodo GetById
public HttpResponseMessage GetById(int id)
{
Doctor items = c.GetById(id);
if (items == null)
{
//Construyendo respuesta del servidor
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay ningun doctor con el id " + id);
}
return Request.CreateResponse(HttpStatusCode.OK, items);
}
////Metodo GetByName
//public HttpResponseMessage GetByName(string name)
//{
// ClienteT items = c.GetByName(name);
// if (items == null)
// {
// //Construyendo respuesta del servidor
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay ningun cliente con el nombre "+name);
// }
// return Request.CreateResponse(HttpStatusCode.OK, items);
//}
//Metodo Delete
public HttpResponseMessage Delete(int id)
{
var item = c.GetById(id);
if (item == null)
{
//Construyendo respuesta del servidor
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay ningun doctor con el id " + id + " para eliminar");
}
c.Delete(id);
return Request.CreateResponse(HttpStatusCode.OK, "El registro ha sido eliminado");
}
//Metodo Put
public HttpResponseMessage Put(int id, Doctor cliente)
{
var item = c.GetById(id);
if (item == null)
{
//Construyendo respuesta del servidor
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay ningun doctor con el id " + id + " para actualizar");
}
var isPut = c.Put(id, cliente);
if (!isPut)
{
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "No ha sido posible la actualizacion");
}
return Request.CreateResponse(HttpStatusCode.OK, "El registro ha sido actualizado");
}
}
}
|
using BaseClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BackTracking
{
public class HamiltonianCycle
{
/*http://www.geeksforgeeks.org/backtracking-set-7-hamiltonian-cycle/
* Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once.
* A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an
* edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. Determine
* whether a given graph contains Hamiltonian Cycle or not. If it contains, then print the path.
* Following are the input and output of the required function.
*/
public bool FindHamiltonCycle<T>(GraphAdjacence<T> input)
{
if (input == null || input.Nodes == null || input.Nodes.Count == 0) return false;
HashSet<T> tracker = new HashSet<T>();
// Here I set the start point. if start point can be random I can
// have a loop here start at each vertex.
tracker.Add(input.Nodes[0].Key);
return Runner(input, tracker, input.Nodes[0]);
}
private bool Runner<T>(GraphAdjacence<T> graph, HashSet<T> tracker, GraphNode<T> root)
{
if (graph.Nodes.Count == tracker.Count)
{
return true;
}
foreach (KeyValuePair<GraphNode<T>, int> pair in root.Neiborghs)
{
if (!tracker.Contains(pair.Key.Key))
{
tracker.Add(pair.Key.Key);
if (Runner(graph, tracker, pair.Key))
{
return true;
}
else
{
tracker.Remove(pair.Key.Key);
}
}
}
return false;
}
}
}
|
using Yeasca.Metier;
using Yeasca.Mongo;
namespace Yeasca.Requete
{
public class AdminEstCreeRequete : Requete<IAdminEstCreeMessage>
{
public override ReponseRequete exécuter(IAdminEstCreeMessage message)
{
IEntrepotUtilisateur entrepot = EntrepotMongo.fabriquerEntrepot<IEntrepotUtilisateur>();
Utilisateur admin = entrepot.récupérerLAdministrateur();
return ReponseRequete.générerUnSuccès(admin != null);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Ecommerce.Entity
{
[Table("OrderDetails")]
public class OrderDetail : IBaseModel
{
[Key]
public Guid OrderDetailId { get; set; }
public Guid OrderId { get; set; }
public Guid ProductId { get; set; }
public int Quantity { get; set; }
public double UnitPrice { get; set; }
public double TotalPrice { get; set; }
public virtual Product Product { get; set; }
}
} |
using System.Collections.Concurrent;
using System.IO;
using Nancy.ViewEngines.Razor;
namespace Nancy.Markdown.Blog
{
public static class HtmlHelperExtensions
{
private static readonly ConcurrentDictionary<int, IHtmlString> Cache = new ConcurrentDictionary<int, IHtmlString>();
private static IHtmlString Html(string text, string baseUri)
{
var md = new MarkdownDeep.Markdown {ExtraMode = true, UrlBaseLocation = baseUri};
var html = md.Transform(text);
return new NonEncodedHtmlString(html);
}
public static IHtmlString Markdown<TModel>(this HtmlHelpers<TModel> helpers, string text, string baseUri = null)
{
var hash = (text + (baseUri ?? string.Empty)).GetHashCode();
return Cache.GetOrAdd(hash, h => Html(text, baseUri));
}
public static IHtmlString MarkdownLoad<TModel>(this HtmlHelpers<TModel> helpers, string path, string baseUri = null)
{
return helpers.Markdown(File.ReadAllText(path), baseUri);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace GetData
{
public partial class CC1: Form
{
DataTable table=new DataTable();
List<DataRow> DataList=new List<DataRow>();
public CC1()
{
InitializeComponent();
}
public void InitTable()
{
table = new DataTable("MarketDataTable");
table.Columns.Add("日付", typeof(string));
table.Columns.Add("終値", typeof(string));
dataGridView1.DataSource = table;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// Datetime dt1=dateTimePicker1.Value.Year.ToString("yyyy/MM/dd");
String StartDate = "";
String EndDate = "";
string time = "1965.1.5 1:0:0";
DateTime bottom = new DateTime();
bottom = DateTime.Parse(time);
StartDate=(-157453200 + 24*60*60*Convert.ToInt32(dateTimePicker1.Value.Subtract(bottom).TotalDays)).ToString();
EndDate= (-157453200 + 24*60*60*Convert.ToInt32(dateTimePicker2.Value.Subtract(bottom).TotalDays)).ToString();
InitTable();
string result = "";
HtmlWeb web = new HtmlWeb();//*
var doc = web.Load("https://finance.yahoo.com/quote/%5EN225/history?period1="+StartDate+"&period2="+EndDate+"&interval=1d&filter=history&frequency=1d");
var Date_Nodes = doc.DocumentNode.SelectNodes("//section/div[2]//table/tbody//tr//td[1]");
var Close_Nodes = doc.DocumentNode.SelectNodes("//section/div[2]//table/tbody//tr//td[5]");
if (Date_Nodes == null)
{
label3.Text = "NO DATA AVAILABLE";
}
else if (Date_Nodes != null)
{
foreach (HtmlNode item in Date_Nodes)
{
DataRow dr = table.NewRow();
dr[1] = "";
dr[0] = item.InnerText;
DataList.Add(dr);
/*result = item.InnerText;
// table.Rows.Add(new Object[] { 1, "Smith" });
DataRow dr = table.NewRow();
dr[0] = result;
table.Rows.Add(dr);*/
}
int i = 0;
foreach (HtmlNode item in Close_Nodes)
{
DataRow dr2 = DataList[i];
dr2[1] = item.InnerText;
DataList[i] = dr2;
i++;
}
DataList.Reverse();
foreach (DataRow dr in DataList)
{
table.Rows.Add(dr);
}
dataGridView1.DataSource = table;
dataGridView1.AllowUserToAddRows = false;
}
else
{
// Every. Single. Time.
}
table = new DataTable();
DataList = new List<DataRow>();
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
|
using Foundation;
using UIKit;
using Flurry.Analytics;
using HockeyApp;
using System;
using System.Threading.Tasks;
using Facebook.CoreKit;
using System.Collections.Generic;
namespace Lettuce.IOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
// Various app keys - Facebook, Flurry, HockeyApp
private string FlurryKey = "5YW4HP9W2P8YMQWRGQB2";
private string HockeyID = "13567c35d7940036ee8035d18ecd04a3";
private string FacebookAppID = "822825007835530";
private string FacebookAppName = "Lettuce";
public UINavigationController NavigationController {get; set;}
public static ProfileViewController ProfileController { get; set; }
// class-level declarations
public override UIWindow Window {
get;
set;
}
public RootViewController RootViewController { get { return Window.RootViewController as RootViewController; } }
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// Override point for customization after application launch.
// If not required for your application you can safely delete this method
// Code to start the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
Xamarin.Calabash.Start();
#endif
// Flurry
FlurryAgent.StartSession(FlurryKey);
// HockeyApp
//We MUST wrap our setup in this block to wire up
// Mono's SIGSEGV and SIGBUS signals
HockeyApp.Setup.EnableCustomCrashReporting (() => {
//Get the shared instance
var manager = BITHockeyManager.SharedHockeyManager;
//Configure it to use our APP_ID
manager.Configure (HockeyID);
//Start the manager
manager.StartManager ();
//Authenticate (there are other authentication options)
manager.Authenticator.AuthenticateInstallation ();
//Rethrow any unhandled .NET exceptions as native iOS
// exceptions so the stack traces appear nicely in HockeyApp
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
Setup.ThrowExceptionAsNative(e.ExceptionObject);
TaskScheduler.UnobservedTaskException += (sender, e) =>
Setup.ThrowExceptionAsNative(e.Exception);
});
// Facebooke
Profile.EnableUpdatesOnAccessTokenChange (true);
Settings.AppID = FacebookAppID;
Settings.DisplayName = FacebookAppName;
//create the initial view controller
ConfigNavMenu ();
// This method verifies if you have been logged into the app before, and keep you logged in after you reopen or kill your app.
return ApplicationDelegate.SharedInstance.FinishedLaunching (application, launchOptions);
}
private void ConfigNavMenu()
{
Window = new UIWindow(UIScreen.MainScreen.Bounds);
Window.BackgroundColor = LettuceColor.BoyBlue;
// If you have defined a root view controller, set it here:
Window.RootViewController = new RootViewController();
// make the window visible
Window.MakeKeyAndVisible();
}
public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
// We need to handle URLs by passing them to their own OpenUrl in order to make the SSO authentication works.
return ApplicationDelegate.SharedInstance.OpenUrl (application, url, sourceApplication, annotation);
}
public override void OnResignActivation (UIApplication application)
{
// Invoked when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Games should use this method to pause the game.
}
public override void DidEnterBackground (UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
}
public override void WillEnterForeground (UIApplication application)
{
// Called as part of the transiton from background to active state.
// Here you can undo many of the changes made on entering the background.
}
public override void OnActivated (UIApplication application)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
}
public override void WillTerminate (UIApplication application)
{
// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
}
}
}
|
// Accord Math Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Contains functions from the Cephes Math Library Release 2.8:
// June, 2000 Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
//
// Original license is listed below:
//
// Some software in this archive may be from the book _Methods and
// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
// International, 1989) or from the Cephes Mathematical Library, a
// commercial product. In either event, it is copyrighted by the author.
// What you see here may be used freely but it comes with no support or
// guarantee.
//
// The two known misprints in the book are repaired here in the
// source listings for the gamma function and the incomplete beta
// integral.
//
//
// Stephen L. Moshier
// moshier@na-net.ornl.gov
//
namespace Accord.Math
{
using Accord.Math.Random;
using System;
/// <summary>
/// Gamma Γ(x) functions.
/// </summary>
///
/// <remarks>
/// <para>
/// In mathematics, the gamma function (represented by the capital Greek
/// letter Γ) is an extension of the factorial function, with its argument
/// shifted down by 1, to real and complex numbers. That is, if <c>n</c> is
/// a positive integer:</para>
/// <code>
/// Γ(n) = (n-1)!</code>
/// <para>
/// The gamma function is defined for all complex numbers except the negative
/// integers and zero. For complex numbers with a positive real part, it is
/// defined via an improper integral that converges:</para>
/// <code>
/// ∞
/// Γ(z) = ∫ t^(z-1)e^(-t) dt
/// 0
/// </code>
/// <para>
/// This integral function is extended by analytic continuation to all
/// complex numbers except the non-positive integers (where the function
/// has simple poles), yielding the meromorphic function we call the gamma
/// function.</para>
/// <para>
/// The gamma function is a component in various probability-distribution
/// functions, and as such it is applicable in the fields of probability
/// and statistics, as well as combinatorics.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description>
/// Wikipedia contributors, "Gamma function,". Wikipedia, The Free
/// Encyclopedia. Available at: http://en.wikipedia.org/wiki/Gamma_function
/// </description></item>
/// <item><description>
/// Cephes Math Library, http://www.netlib.org/cephes/ </description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <code>
/// double x = 0.17;
///
/// // Compute main Gamma function and variants
/// double gamma = Gamma.Function(x); // 5.4511741801042106
/// double gammap = Gamma.Function(x, p: 2); // -39.473585841300675
/// double log = Gamma.Log(x); // 1.6958310313607003
/// double logp = Gamma.Log(x, p: 2); // 3.6756317353404273
/// double stir = Gamma.Stirling(x); // 24.040352622960743
/// double psi = Gamma.Digamma(x); // -6.2100942259248626
/// double tri = Gamma.Trigamma(x); // 35.915302055854525
///
/// double a = 4.2;
///
/// // Compute the incomplete regularized Gamma functions P and Q:
/// double lower = Gamma.LowerIncomplete(a, x); // 0.000015685073063633753
/// double upper = Gamma.UpperIncomplete(a, x); // 0.9999843149269364
/// </code>
/// </example>
///
public static class Gamma
{
/// <summary>Maximum gamma on the machine.</summary>
public const double GammaMax = 171.624376956302725; // TODO: Rename to Max
/// <summary>
/// Gamma function of the specified value.
/// </summary>
///
public static double Function(double x)
{
double[] P =
{
1.60119522476751861407E-4,
1.19135147006586384913E-3,
1.04213797561761569935E-2,
4.76367800457137231464E-2,
2.07448227648435975150E-1,
4.94214826801497100753E-1,
9.99999999999999996796E-1
};
double[] Q =
{
-2.31581873324120129819E-5,
5.39605580493303397842E-4,
-4.45641913851797240494E-3,
1.18139785222060435552E-2,
3.58236398605498653373E-2,
-2.34591795718243348568E-1,
7.14304917030273074085E-2,
1.00000000000000000320E0
};
double p, z;
double q = System.Math.Abs(x);
if (q > 33.0)
{
if (x < 0.0)
{
p = System.Math.Floor(q);
if (p == q)
throw new OverflowException();
z = q - p;
if (z > 0.5)
{
p += 1.0;
z = q - p;
}
z = q * System.Math.Sin(System.Math.PI * z);
if (z == 0.0)
throw new OverflowException();
z = System.Math.Abs(z);
z = System.Math.PI / (z * Stirling(q));
return -z;
}
else
{
return Stirling(x);
}
}
z = 1.0;
while (x >= 3.0)
{
x -= 1.0;
z *= x;
}
while (x < 0.0)
{
if (x == 0.0)
{
throw new ArithmeticException();
}
else if (x > -1.0E-9)
{
return (z / ((1.0 + 0.5772156649015329 * x) * x));
}
z /= x;
x += 1.0;
}
while (x < 2.0)
{
if (x == 0.0)
{
throw new ArithmeticException();
}
else if (x < 1.0E-9)
{
return (z / ((1.0 + 0.5772156649015329 * x) * x));
}
z /= x;
x += 1.0;
}
if ((x == 2.0) || (x == 3.0))
return z;
x -= 2.0;
p = Special.Polevl(x, P, 6);
q = Special.Polevl(x, Q, 7);
return z * p / q;
}
/// <summary>
/// Multivariate Gamma function
/// </summary>
///
public static double Multivariate(double x, int p)
{
if (p < 1)
throw new ArgumentOutOfRangeException("p",
"Parameter p must be higher than 1.");
if (p == 1)
return Function(x);
double prod = Math.Pow(Math.PI, (1 / 4.0) * p * (p - 1));
for (int i = 0; i < p; i++)
prod *= Function(x - 0.5 * i);
return prod;
}
/// <summary>
/// Digamma function.
/// </summary>
///
public static double Digamma(double x)
{
if (x == 0)
return Double.NegativeInfinity;
double s = 0;
double w = 0;
double y = 0;
double z = 0;
double nz = 0;
bool negative = false;
if (x <= 0.0)
{
negative = true;
double q = x;
double p = (int)System.Math.Floor(q);
if (p == q)
throw new OverflowException("Function computation resulted in arithmetic overflow.");
nz = q - p;
if (nz != 0.5)
{
if (nz > 0.5)
{
p = p + 1.0;
nz = q - p;
}
nz = Math.PI / Math.Tan(System.Math.PI * nz);
}
else
{
nz = 0.0;
}
x = 1.0 - x;
}
if (x <= 10.0 & x == Math.Floor(x))
{
y = 0.0;
int n = (int)Math.Floor(x);
for (int i = 1; i <= n - 1; i++)
{
w = i;
y = y + 1.0 / w;
}
y = y - 0.57721566490153286061;
}
else
{
s = x;
w = 0.0;
while (s < 10.0)
{
w = w + 1.0 / s;
s = s + 1.0;
}
if (s < 1.0E17)
{
z = 1.0 / (s * s);
double polv = 8.33333333333333333333E-2;
polv = polv * z - 2.10927960927960927961E-2;
polv = polv * z + 7.57575757575757575758E-3;
polv = polv * z - 4.16666666666666666667E-3;
polv = polv * z + 3.96825396825396825397E-3;
polv = polv * z - 8.33333333333333333333E-3;
polv = polv * z + 8.33333333333333333333E-2;
y = z * polv;
}
else
{
y = 0.0;
}
y = Math.Log(s) - 0.5 / s - y - w;
}
if (negative == true)
{
y = y - nz;
}
return y;
}
/// <summary>
/// Trigamma function.
/// </summary>
///
/// <remarks>
/// This code has been adapted from the FORTRAN77 and subsequent
/// C code by B. E. Schneider and John Burkardt. The code had been
/// made public under the GNU LGPL license.
/// </remarks>
///
public static double Trigamma(double x)
{
double a = 0.0001;
double b = 5.0;
double b2 = 0.1666666667;
double b4 = -0.03333333333;
double b6 = 0.02380952381;
double b8 = -0.03333333333;
double value;
double y;
double z;
// Check the input.
if (x <= 0.0)
{
throw new ArgumentException("The input parameter x must be positive.", "x");
}
z = x;
// Use small value approximation if X <= A.
if (x <= a)
{
value = 1.0 / x / x;
return value;
}
// Increase argument to ( X + I ) >= B.
value = 0.0;
while (z < b)
{
value = value + 1.0 / z / z;
z = z + 1.0;
}
// Apply asymptotic formula if argument is B or greater.
y = 1.0 / z / z;
value = value + 0.5 *
y + (1.0
+ y * (b2
+ y * (b4
+ y * (b6
+ y * b8)))) / z;
return value;
}
/// <summary>
/// Gamma function as computed by Stirling's formula.
/// </summary>
///
public static double Stirling(double x)
{
double[] STIR =
{
7.87311395793093628397E-4,
-2.29549961613378126380E-4,
-2.68132617805781232825E-3,
3.47222221605458667310E-3,
8.33333333333482257126E-2,
};
double MAXSTIR = 143.01608;
double w = 1.0 / x;
double y = Math.Exp(x);
w = 1.0 + w * Special.Polevl(w, STIR, 4);
if (x > MAXSTIR)
{
double v = Math.Pow(x, 0.5 * x - 0.25);
if (Double.IsPositiveInfinity(v) && Double.IsPositiveInfinity(y))
{
// lim x -> inf { (x^(0.5*x - 0.25)) * (x^(0.5*x - 0.25) / exp(x)) }
y = Double.PositiveInfinity;
}
else
{
y = v * (v / y);
}
}
else
{
y = System.Math.Pow(x, x - 0.5) / y;
}
y = Constants.Sqrt2PI * y * w;
return y;
}
/// <summary>
/// Upper incomplete regularized Gamma function Q
/// (a.k.a the incomplete complemented Gamma function)
/// </summary>
///
/// <remarks>
/// This function is equivalent to Q(x) = Γ(s, x) / Γ(s).
/// </remarks>
///
public static double UpperIncomplete(double a, double x)
{
const double big = 4.503599627370496e15;
const double biginv = 2.22044604925031308085e-16;
double ans, ax, c, yc, r, t, y, z;
double pk, pkm1, pkm2, qk, qkm1, qkm2;
if (x <= 0 || a <= 0)
return 1.0;
if (x < 1.0 || x < a)
return 1.0 - LowerIncomplete(a, x);
if (Double.IsPositiveInfinity(x))
return 0;
ax = a * Math.Log(x) - x - Log(a);
if (ax < -Constants.LogMax)
return 0.0;
ax = Math.Exp(ax);
// continued fraction
y = 1.0 - a;
z = x + y + 1.0;
c = 0.0;
pkm2 = 1.0;
qkm2 = x;
pkm1 = x + 1.0;
qkm1 = z * x;
ans = pkm1 / qkm1;
do
{
c += 1.0;
y += 1.0;
z += 2.0;
yc = y * c;
pk = pkm1 * z - pkm2 * yc;
qk = qkm1 * z - qkm2 * yc;
if (qk != 0)
{
r = pk / qk;
t = Math.Abs((ans - r) / r);
ans = r;
}
else
t = 1.0;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if (Math.Abs(pk) > big)
{
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
} while (t > Constants.DoubleEpsilon);
return ans * ax;
}
/// <summary>
/// Lower incomplete regularized gamma function P
/// (a.k.a. the incomplete Gamma function).
/// </summary>
///
/// <remarks>
/// This function is equivalent to P(x) = γ(s, x) / Γ(s).
/// </remarks>
///
public static double LowerIncomplete(double a, double x)
{
if (a <= 0)
return 1.0;
if (x <= 0)
return 0.0;
if (x > 1.0 && x > a)
return 1.0 - UpperIncomplete(a, x);
double ax = a * Math.Log(x) - x - Log(a);
if (ax < -Constants.LogMax)
return 0.0;
ax = Math.Exp(ax);
double r = a;
double c = 1.0;
double ans = 1.0;
do
{
r += 1.0;
c *= x / r;
ans += c;
} while (c / ans > Constants.DoubleEpsilon);
return ans * ax / a;
}
/// <summary>
/// Natural logarithm of the gamma function.
/// </summary>
///
public static double Log(double x)
{
if (x == 0)
return Double.PositiveInfinity;
double p, q, w, z;
double[] A =
{
8.11614167470508450300E-4,
-5.95061904284301438324E-4,
7.93650340457716943945E-4,
-2.77777777730099687205E-3,
8.33333333333331927722E-2
};
double[] B =
{
-1.37825152569120859100E3,
-3.88016315134637840924E4,
-3.31612992738871184744E5,
-1.16237097492762307383E6,
-1.72173700820839662146E6,
-8.53555664245765465627E5
};
double[] C =
{
-3.51815701436523470549E2,
-1.70642106651881159223E4,
-2.20528590553854454839E5,
-1.13933444367982507207E6,
-2.53252307177582951285E6,
-2.01889141433532773231E6
};
if (x < -34.0)
{
q = -x;
w = Log(q);
p = Math.Floor(q);
if (p == q)
throw new OverflowException();
z = q - p;
if (z > 0.5)
{
p += 1.0;
z = p - q;
}
z = q * Math.Sin(System.Math.PI * z);
if (z == 0.0)
throw new OverflowException();
z = Constants.LogPI - Math.Log(z) - w;
return z;
}
if (x < 13.0)
{
z = 1.0;
while (x >= 3.0)
{
x -= 1.0;
z *= x;
}
while (x < 2.0)
{
if (x == 0.0)
throw new OverflowException();
z /= x;
x += 1.0;
}
if (z < 0.0)
z = -z;
if (x == 2.0)
return System.Math.Log(z);
x -= 2.0;
p = x * Special.Polevl(x, B, 5) / Special.P1evl(x, C, 6);
return (Math.Log(z) + p);
}
if (x > 2.556348e305)
throw new OverflowException();
q = (x - 0.5) * Math.Log(x) - x + 0.91893853320467274178;
if (x > 1.0e8)
return (q);
p = 1.0 / (x * x);
if (x >= 1000.0)
{
q += ((7.9365079365079365079365e-4 * p
- 2.7777777777777777777778e-3) * p
+ 0.0833333333333333333333) / x;
}
else
{
q += Special.Polevl(p, A, 4) / x;
}
return q;
}
/// <summary>
/// Natural logarithm of the multivariate Gamma function.
/// </summary>
///
public static double Log(double x, int p)
{
if (p < 1)
throw new ArgumentOutOfRangeException("p", "Parameter p must be higher than 1.");
if (p == 1)
return Log(x);
double sum = Constants.LogPI / p;
for (int i = 0; i < p; i++)
sum += Log(x - 0.5 * i);
return sum;
}
/// <summary>
/// Inverse of the <see cref="LowerIncomplete">
/// incomplete Gamma integral (LowerIncomplete, P)</see>.
/// </summary>
///
public static double InverseLowerIncomplete(double a, double y)
{
return inverse(a, 1 - y);
}
/// <summary>
/// Inverse of the <see cref="UpperIncomplete">complemented
/// incomplete Gamma integral (UpperIncomplete, Q)</see>.
/// </summary>
///
public static double InverseUpperIncomplete(double a, double y)
{
return inverse(a, y);
}
/// <summary>
/// Inverse of the <see cref="UpperIncomplete">complemented
/// incomplete Gamma integral (UpperIncomplete, Q)</see>.
/// </summary>
///
//[Obsolete("Please use InverseUpperIncomplete instead.")]
public static double Inverse(double a, double y)
{
return inverse(a, y);
}
private static double inverse(double a, double y)
{
// bound the solution
double x0 = Double.MaxValue;
double yl = 0;
double x1 = 0;
double yh = 1.0;
double dithresh = 5.0 * Constants.DoubleEpsilon;
// approximation to inverse function
double d = 1.0 / (9.0 * a);
double yy = (1.0 - d - Normal.Inverse(y) * Math.Sqrt(d));
double x = a * yy * yy * yy;
double lgm = Gamma.Log(a);
for (int i = 0; i < 10; i++)
{
if (x > x0 || x < x1)
goto ihalve;
yy = Gamma.UpperIncomplete(a, x);
if (yy < yl || yy > yh)
goto ihalve;
if (yy < y)
{
x0 = x;
yl = yy;
}
else
{
x1 = x;
yh = yy;
}
// compute the derivative of the function at this point
d = (a - 1.0) * Math.Log(x) - x - lgm;
if (d < -Constants.LogMax)
goto ihalve;
d = -Math.Exp(d);
// compute the step to the next approximation of x
d = (yy - y) / d;
if (Math.Abs(d / x) < Constants.DoubleEpsilon)
return x;
x = x - d;
}
// Resort to interval halving if Newton iteration did not converge.
ihalve:
d = 0.0625;
if (x0 == Double.MaxValue)
{
if (x <= 0.0)
x = 1.0;
while (x0 == Double.MaxValue && !Double.IsNaN(x))
{
x = (1.0 + d) * x;
yy = Gamma.UpperIncomplete(a, x);
if (yy < y)
{
x0 = x;
yl = yy;
break;
}
d = d + d;
}
}
d = 0.5;
double dir = 0;
for (int i = 0; i < 400; i++)
{
double t = x1 + d * (x0 - x1);
if (Double.IsNaN(t))
break;
x = t;
yy = Gamma.UpperIncomplete(a, x);
lgm = (x0 - x1) / (x1 + x0);
if (Math.Abs(lgm) < dithresh)
break;
lgm = (yy - y) / y;
if (Math.Abs(lgm) < dithresh)
break;
if (x <= 0.0)
break;
if (yy >= y)
{
x1 = x;
yh = yy;
if (dir < 0)
{
dir = 0;
d = 0.5;
}
else if (dir > 1)
d = 0.5 * d + 0.5;
else
d = (y - yl) / (yh - yl);
dir += 1;
}
else
{
x0 = x;
yl = yy;
if (dir > 0)
{
dir = 0;
d = 0.5;
}
else if (dir < -1)
d = 0.5 * d;
else
d = (y - yl) / (yh - yl);
dir -= 1;
}
}
if (x == 0.0 || Double.IsNaN(x))
throw new ArithmeticException();
return x;
}
/// <summary>
/// Random Gamma-distribution number generation
/// based on Marsaglia's Simple Method (2000).
/// </summary>
///
public static double Random(double d, double c)
{
var g = new GaussianGenerator(0, 1, Generator.Random.Next());
// References:
//
// - Marsaglia, G. A Simple Method for Generating Gamma Variables, 2000
//
while (true)
{
// 2. Generate v = (1+cx)^3 with x normal
double x, t, v;
do
{
x = g.Next();
t = (1.0 + c * x);
v = t * t * t;
} while (v <= 0);
// 3. Generate uniform U
double U = Accord.Math.Random.Generator.Random.NextDouble();
// 4. If U < 1-0.0331*x^4 return d*v.
double x2 = x * x;
if (U < 1 - 0.0331 * x2 * x2)
return d * v;
// 5. If log(U) < 0.5*x^2 + d*(1-v+log(v)) return d*v.
if (Math.Log(U) < 0.5 * x2 + d * (1.0 - v + Math.Log(v)))
return d * v;
// 6. Goto step 2
}
}
}
}
|
// Copyright (c) 2019 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Xml.Linq;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ILSpy.BamlDecompiler.Rewrite
{
internal class ConnectionIdRewritePass : IRewritePass
{
static readonly TopLevelTypeName componentConnectorTypeName = new TopLevelTypeName("System.Windows.Markup", "IComponentConnector");
public void Run(XamlContext ctx, XDocument document)
{
var mappings = DecompileEventMappings(ctx, document);
ProcessConnectionIds(document.Root, mappings);
}
static void ProcessConnectionIds(XElement element, List<(LongSet key, EventRegistration[] value)> eventMappings)
{
foreach (var child in element.Elements())
ProcessConnectionIds(child, eventMappings);
foreach (var annotation in element.Annotations<BamlConnectionId>()) {
int index;
if ((index = eventMappings.FindIndex(item => item.key.Contains(annotation.Id))) > -1) {
foreach (var entry in eventMappings[index].value) {
string xmlns = ""; // TODO : implement xmlns resolver!
element.Add(new XAttribute(xmlns + entry.EventName, entry.MethodName));
}
}
}
}
List<(LongSet, EventRegistration[])> DecompileEventMappings(XamlContext ctx, XDocument document)
{
var result = new List<(LongSet, EventRegistration[])>();
var xClass = document.Root.Elements().First().Attribute(ctx.GetKnownNamespace("Class", XamlContext.KnownNamespace_Xaml));
if (xClass == null)
return result;
var type = ctx.TypeSystem.FindType(new FullTypeName(xClass.Value)).GetDefinition();
if (type == null)
return result;
var connectorInterface = ctx.TypeSystem.FindType(componentConnectorTypeName).GetDefinition();
if (connectorInterface == null)
return result;
var connect = connectorInterface.GetMethods(m => m.Name == "Connect").SingleOrDefault();
IMethod method = null;
MethodDefinition metadataEntry = default;
var module = ctx.TypeSystem.MainModule.PEFile;
foreach (IMethod m in type.Methods) {
if (m.ExplicitlyImplementedInterfaceMembers.Any(md => md.MemberDefinition.Equals(connect))) {
method = m;
metadataEntry = module.Metadata.GetMethodDefinition((MethodDefinitionHandle)method.MetadataToken);
break;
}
}
if (method == null || metadataEntry.RelativeVirtualAddress <= 0)
return result;
var body = module.Reader.GetMethodBody(metadataEntry.RelativeVirtualAddress);
var genericContext = new GenericContext(
classTypeParameters: method.DeclaringType?.TypeParameters,
methodTypeParameters: method.TypeParameters);
// decompile method and optimize the switch
var ilReader = new ILReader(ctx.TypeSystem.MainModule);
var function = ilReader.ReadIL((MethodDefinitionHandle)method.MetadataToken, body, genericContext, ILFunctionKind.TopLevelFunction, ctx.CancellationToken);
var context = new ILTransformContext(function, ctx.TypeSystem, null) {
CancellationToken = ctx.CancellationToken
};
function.RunTransforms(CSharpDecompiler.GetILTransforms(), context);
var block = function.Body.Children.OfType<Block>().First();
var ilSwitch = block.Descendants.OfType<SwitchInstruction>().FirstOrDefault();
if (ilSwitch != null) {
foreach (var section in ilSwitch.Sections) {
var events = FindEvents(section.Body);
result.Add((section.Labels, events));
}
} else {
foreach (var ifInst in function.Descendants.OfType<IfInstruction>()) {
var comp = ifInst.Condition as Comp;
if (comp.Kind != ComparisonKind.Inequality && comp.Kind != ComparisonKind.Equality)
continue;
if (!comp.Right.MatchLdcI4(out int id))
continue;
var events = FindEvents(comp.Kind == ComparisonKind.Inequality ? ifInst.FalseInst : ifInst.TrueInst);
result.Add((new LongSet(id), events));
}
}
return result;
}
EventRegistration[] FindEvents(ILInstruction inst)
{
var events = new List<EventRegistration>();
switch (inst) {
case Block b:
foreach (var node in ((Block)inst).Instructions) {
FindEvents(node, events);
}
FindEvents(((Block)inst).FinalInstruction, events);
break;
case Branch br:
return FindEvents(br.TargetBlock);
default:
FindEvents(inst, events);
break;
}
return events.ToArray();
}
void FindEvents(ILInstruction inst, List<EventRegistration> events)
{
CallInstruction call = inst as CallInstruction;
if (call == null || call.OpCode == OpCode.NewObj)
return;
if (IsAddEvent(call, out string eventName, out string handlerName) || IsAddAttachedEvent(call, out eventName, out handlerName))
events.Add(new EventRegistration { EventName = eventName, MethodName = handlerName });
}
bool IsAddAttachedEvent(CallInstruction call, out string eventName, out string handlerName)
{
eventName = "";
handlerName = "";
if (call.Arguments.Count == 3) {
var addMethod = call.Method;
if (addMethod.Name != "AddHandler" || addMethod.Parameters.Count != 2)
return false;
if (!call.Arguments[1].MatchLdsFld(out IField field))
return false;
eventName = field.DeclaringType.Name + "." + field.Name;
if (eventName.EndsWith("Event", StringComparison.Ordinal) && eventName.Length > "Event".Length)
eventName = eventName.Remove(eventName.Length - "Event".Length);
var newObj = call.Arguments[2] as NewObj;
if (newObj == null || newObj.Arguments.Count != 2)
return false;
var ldftn = newObj.Arguments[1];
if (ldftn.OpCode != OpCode.LdFtn && ldftn.OpCode != OpCode.LdVirtFtn)
return false;
handlerName = ((IInstructionWithMethodOperand)ldftn).Method.Name;
return true;
}
return false;
}
bool IsAddEvent(CallInstruction call, out string eventName, out string handlerName)
{
eventName = "";
handlerName = "";
if (call.Arguments.Count == 2) {
var addMethod = call.Method;
if (!addMethod.Name.StartsWith("add_", StringComparison.Ordinal) || addMethod.Parameters.Count != 1)
return false;
eventName = addMethod.Name.Substring("add_".Length);
var newObj = call.Arguments[1] as NewObj;
if (newObj == null || newObj.Arguments.Count != 2)
return false;
var ldftn = newObj.Arguments[1];
if (ldftn.OpCode != OpCode.LdFtn && ldftn.OpCode != OpCode.LdVirtFtn)
return false;
handlerName = ((IInstructionWithMethodOperand)ldftn).Method.Name;
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PoweredSoft.Docker.PostgresBackup.Backup
{
public class BackupOptions
{
public string BasePath { get; set; } = "postgres_backups";
public string Databases { get; set; } = "*";
}
}
|
using ServiceDesk.Api.Systems.RequestSystem.Dtos.Comment;
namespace ServiceDesk.Api.Systems.RequestSystem.DtoBuilders.Comment
{
public class CommentDtoBuilder : ICommentDtoBuilder<CommentDto>
{
public CommentDto Build(Core.Entities.RequestSystem.Comment entity)
{
var commentDto = new CommentDto()
{
Id = entity.Id,
Text = entity.Text,
AuthorId = entity.AuthorId,
CreationDate = entity.CreationDate
};
return commentDto;
}
}
}
|
using System;
using System.Windows;
using DevExpress.Xpf.Core;
using log4net;
namespace InsightsAnalyser.ViewModels
{
public static class ErrorReporter
{
public static void Report(ILog logger, Exception ex)
{
logger.Error(ex);
DXMessageBox.Show("An error has occurred.\n\n" + ex.Message + "\n\nPlease restart the application and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
} |
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_ProceduralProcessorUsage : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.ProceduralProcessorUsage");
LuaObject.addMember(l, 0, "Unsupported");
LuaObject.addMember(l, 1, "One");
LuaObject.addMember(l, 2, "Half");
LuaObject.addMember(l, 3, "All");
LuaDLL.lua_pop(l, 1);
}
}
|
using System.Linq;
using NSubstitute;
using Shouldly;
using Xunit;
namespace Howff.Navigation.Tests {
public class NavigationTests {
[Fact]
public void GetItems_RootItemNull_ReturnsEmptyItemCollection() {
var navigation = MakeDefaultNavigationFake();
var navigationItems = navigation.GetItems(null, Substitute.For<INavigationItem>(), Substitute.For<INavigationConfig>());
navigationItems.ShouldBeEmpty();
}
[Fact]
public void GetItems_StartLevelRootEndLevelOneGetChildrenOnRootItemReturnsNull_ReturnsCollectionWithRoot() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(
fakes.RootWithNullChildren,
Substitute.For<INavigationItem>(),
new NavigationConfig(0, 1, IncludeItemsMode.All, IncludeItemsMode.All)
).ToArray();
navigationItemsArray.Length.ShouldBe(1);
navigationItemsArray[0].Name.ShouldBe("0-children-null");
navigationItemsArray[0].Children.ShouldBeEmpty();
}
[Fact]
public void GetItems_StartLevelRootEndLevelRootGetChildrenOnRootItemReturnsNullRootItemCurrent_ReturnsCollectionWithSelectedRoot() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(fakes.RootWithNullChildren, fakes.RootWithNullChildren, new NavigationConfig()).ToArray();
navigationItemsArray[0].Selected.ShouldBeTrue();
}
[Fact]
public void GetItems_StartLevelRootEndLevelOneDefaultIncludeConfig_ReturnsCollectionWithRootItemAndVisibleRootChildren() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(fakes.Root, Substitute.For<INavigationItem>(), new NavigationConfig(0, 1)).ToArray();
navigationItemsArray.Length.ShouldBe(1);
navigationItemsArray[0].Name.ShouldBe("0");
var rootChildrenArray = navigationItemsArray[0].Children.ToArray();
rootChildrenArray.Length.ShouldBe(2);
rootChildrenArray[0].Name.ShouldBe("1-1");
rootChildrenArray[0].Children.ShouldBeEmpty();
rootChildrenArray[1].Name.ShouldBe("1-2");
rootChildrenArray[1].Children.ShouldBeEmpty();
}
[Fact]
public void GetItems_StartLevelRootEndLevelOneSecondChildCurrent_ReturnsCollectionWithSecondRootChildSelected() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.SecondChildOfRoot, new NavigationConfig(0, 1)).ToArray();
var rootChildrenArray = navigationItemsArray[0].Children.ToArray();
rootChildrenArray[1].Selected.ShouldBeTrue();
}
[Fact]
public void GetItems_StartLevelOneEndLevelOneDefaultConfig_ReturnsRootChildren() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(fakes.Root, Substitute.For<INavigationItem>(), new NavigationConfig(1, 1)).ToArray();
navigationItemsArray.Length.ShouldBe(2);
navigationItemsArray[0].Name.ShouldBe("1-1");
navigationItemsArray[0].Children.ShouldBeEmpty();
navigationItemsArray[1].Name.ShouldBe("1-2");
navigationItemsArray[1].Children.ShouldBeEmpty();
}
[Fact]
public void GetItems_StartLevelOneEndLevelOneFirstChildSelected_ReturnsRootChildrenFirstChildSelected() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.FirstChildOfRoot, new NavigationConfig(1, 1)).ToArray();
navigationItemsArray[0].Selected.ShouldBeTrue();
}
[Fact]
public void GetItems_StartLevelOneEndLevelTwoSecondItemCurrent_ReturnsRootChildrenAndSecondItemChildren() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.SecondChildOfRoot, new NavigationConfig(1, 2)).ToArray();
navigationItemsArray[0].Children.ShouldBeEmpty();
navigationItemsArray[1].Children.Count.ShouldBe(2);
}
[Fact]
public void GetItems_StartLevelOneEndLevelTwoIncludeChildItemsAll_ReturnsRootChildrenAndAllTheirVisibleChildren() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationConfig = new NavigationConfig(1, 2, IncludeItemsMode.All, IncludeItemsMode.All);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.SecondChildOfRoot, navigationConfig).ToArray();
navigationItemsArray[0].Children.Count.ShouldBe(2);
var firstItemChildrenArray = navigationItemsArray[0].Children.ToArray();
firstItemChildrenArray[0].Name.ShouldBe("1-1-1");
firstItemChildrenArray[1].Name.ShouldBe("1-1-2");
navigationItemsArray[1].Children.Count.ShouldBe(2);
var secondItemChildrenArray = navigationItemsArray[1].Children.ToArray();
secondItemChildrenArray[0].Name.ShouldBe("1-2-1");
secondItemChildrenArray[1].Name.ShouldBe("1-2-2");
}
[Fact]
public void GetItems_StartLevelOneEndLevelTwoIncludeChildItemsAllIncludeNoneVisibleItemsAll_ReturnsRootChildrenAndAllTheirChildren() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationConfig = new NavigationConfig(1, 2, IncludeItemsMode.All, IncludeItemsMode.All, IncludeItemsMode.All);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.SecondChildOfRoot, navigationConfig).ToArray();
navigationItemsArray.Length.ShouldBe(3);
navigationItemsArray[2].Visible.ShouldBeFalse();
var thirdItemChildrenArray = navigationItemsArray[2].Children.ToArray();
thirdItemChildrenArray[0].Name.ShouldBe("1-3-1");
thirdItemChildrenArray[1].Name.ShouldBe("1-3-2");
}
[Fact]
public void GetItems_StartLevelTwoEndLevelTwoIncludeRootLevelItemsInSelectedPath_ReturnsChildrenOfSecondChildOfRoot() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationConfig = new NavigationConfig(2, 2, IncludeItemsMode.InSelectedPath);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.SecondChildOfRoot, navigationConfig).ToArray();
navigationItemsArray.Length.ShouldBe(2);
}
[Fact]
public void GetItems_StartLevelTwoEndLevelThreeIncludeRootLevelItemsInSelectedPathIncludeAllChildItems_ContainsAllChildrenOfRootItemsInSelectedPath() {
var fakes = MakeDefaultNavigationItemFakes();
var navigation = MakeDefaultNavigationFake(fakes);
var navigationConfig = new NavigationConfig(2, 3, IncludeItemsMode.InSelectedPath, IncludeItemsMode.All);
var navigationItemsArray = navigation.GetItems(fakes.Root, fakes.SecondChildOfRoot, navigationConfig).ToArray();
navigationItemsArray.Length.ShouldBe(2);
var firstItemChildrenArray = navigationItemsArray[0].Children.ToArray();
firstItemChildrenArray.Length.ShouldBe(2);
firstItemChildrenArray[0].Name.ShouldBe("1-2-1-1");
firstItemChildrenArray[1].Name.ShouldBe("1-2-1-2");
var secondItemChildrenArray = navigationItemsArray[1].Children.ToArray();
secondItemChildrenArray.Length.ShouldBe(2);
secondItemChildrenArray[0].Name.ShouldBe("1-2-2-1");
secondItemChildrenArray[1].Name.ShouldBe("1-2-2-2");
}
private NavigationFake MakeDefaultNavigationFake() {
return new NavigationFake(new NavigationItemFakes());
}
private NavigationFake MakeDefaultNavigationFake(NavigationItemFakes navigationItemFakes) {
return new NavigationFake(navigationItemFakes);
}
private NavigationItemFakes MakeDefaultNavigationItemFakes() {
return new NavigationItemFakes();
}
}
} |
using Checkout.Payment.Command.Domain.Models;
using Checkout.Payment.Command.Seedwork.Extensions;
using System;
using System.Threading.Tasks;
namespace Checkout.Payment.Command.Domain.Interfaces
{
public interface IPaymentRepository
{
Task<ITryResult<PaymentRequest>> TryCreatePayment(CreatePaymentCommand command);
Task<ITryResult> TryRemovePayment(Guid paymentId);
Task<ITryResult<bool>> TryUpdatePayment(UpdatePaymentCommand command);
}
}
|
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace sd_luciprod;
public class JobDriver_sd_luciprod_TakeLuciOutOfDistillery : JobDriver
{
private const TargetIndex BarrelInd = TargetIndex.A;
private const TargetIndex sd_luciprod_rawBatchToHaulInd = TargetIndex.B;
private const TargetIndex StorageCellInd = TargetIndex.C;
private const int Duration = 200;
protected Building_sd_luciprod_distillery Barrel =>
(Building_sd_luciprod_distillery)job.GetTarget(TargetIndex.A).Thing;
protected Thing sd_luciprod_rawlucibatch => job.GetTarget(TargetIndex.B).Thing;
public override bool TryMakePreToilReservations(bool errorOnFailed)
{
return pawn.Reserve(Barrel, job);
}
protected override IEnumerable<Toil> MakeNewToils()
{
this.FailOnDespawnedNullOrForbidden(TargetIndex.A);
this.FailOnBurningImmobile(TargetIndex.A);
yield return Toils_Reserve.Reserve(TargetIndex.A);
yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch);
yield return Toils_General.Wait(200).FailOnDestroyedNullOrForbidden(TargetIndex.A)
.FailOn(() => !Barrel.Distilled).WithProgressBarToilDelay(TargetIndex.A);
yield return new Toil
{
initAction = delegate
{
var thing = Barrel.TakeOutrawlucibatch();
GenPlace.TryPlaceThing(thing, pawn.Position, Map, ThingPlaceMode.Near);
var currentPriority = StoreUtility.CurrentStoragePriorityOf(thing);
if (StoreUtility.TryFindBestBetterStoreCellFor(thing, pawn, Map, currentPriority, pawn.Faction,
out var c))
{
job.SetTarget(TargetIndex.C, c);
job.SetTarget(TargetIndex.B, thing);
job.count = thing.stackCount;
}
else
{
EndJobWith(JobCondition.Incompletable);
}
},
defaultCompleteMode = ToilCompleteMode.Instant
};
yield return Toils_Reserve.Reserve(TargetIndex.B);
yield return Toils_Reserve.Reserve(TargetIndex.C);
yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch);
yield return Toils_Haul.StartCarryThing(TargetIndex.B);
var toil = Toils_Haul.CarryHauledThingToCell(TargetIndex.C);
yield return toil;
yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, toil, true);
}
} |
namespace SGDE.Domain.Entities
{
#region Using
using System;
using System.Collections.Generic;
#endregion
public class User : BaseEntity
{
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Dni { get; set; }
public string SecuritySocialNumber { get; set; }
public DateTime? BirthDate { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string Observations { get; set; }
public string AccountNumber { get; set; }
public byte[] Photo { get; set; }
public string Token { get; set; }
//public int? ProfessionId { get; set; }
//public virtual Profession Profession { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
public int? WorkId { get; set; }
public virtual Work Work { get; set; }
public int? ClientId { get; set; }
public virtual Client Client { get; set; }
public virtual ICollection<UserProfession> UserProfessions { get; set; } = new HashSet<UserProfession>();
public virtual ICollection<Training> Trainings { get; set; } = new HashSet<Training>();
public virtual ICollection<User> ContactPersons { get; set; } = new HashSet<User>();
public virtual ICollection<UserHiring> UserHirings { get; set; } = new HashSet<UserHiring>();
public virtual ICollection<DailySigning> DailySignings { get; set; } = new HashSet<DailySigning>();
public virtual ICollection<CostWorker> CostWorkers { get; set; } = new HashSet<CostWorker>();
public virtual ICollection<Embargo> Embargos { get; set; } = new HashSet<Embargo>();
public virtual ICollection<SSHiring> SSHirings { get; set; } = new HashSet<SSHiring>();
public virtual ICollection<Advance> Advances { get; set; } = new HashSet<Advance>();
}
}
|
using System;
using System.IO;
using NUnit.Framework;
using GildedRose.Console;
namespace GildedRose.Tests
{
[TestFixture]
public class TestAssemblyTests
{
private Program _prog;
[SetUp]
public void SetUp()
{
_prog = Program.GetApp();
}
[Test]
public void GoldenMasterTest()
{
var reader = new StreamReader("master.txt");
for (var i = 0; i < 200; i++)
{
_prog.UpdateQuality();
var masterLine = reader.ReadLine();
Assert.That(_prog.Status(), Is.EqualTo(masterLine));
}
}
[TestCase("This is a standard item", 10, 9)]
[TestCase("This is a standard item", 0, 8)]
[TestCase("Backstage passes to a TAFKAL80ETC concert", 16, 11)]
[TestCase("Backstage passes to a TAFKAL80ETC concert", 15, 11)]
[TestCase("Backstage passes to a TAFKAL80ETC concert", 10, 12)]
[TestCase("Backstage passes to a TAFKAL80ETC concert", 1, 13)]
[TestCase("Backstage passes to a TAFKAL80ETC concert", 0, 0)]
[TestCase("Aged Brie", 10, 11)]
[TestCase("Aged Brie", 5, 11)]
[TestCase("Aged Brie", 0, 12)]
[TestCase("Aged Brie", -1, 12)]
public void TestItemQualityOnUpdate(String itemName, int startingSellIn, int expectedQualityAfterUpdate)
{
var item = new Item
{
Name = itemName,
Quality = 10,
SellIn = startingSellIn
};
item.Update();
Assert.That(item.Quality, Is.EqualTo(expectedQualityAfterUpdate));
}
//[TestCase(10, 9)]
//[TestCase(0, 8)]
//public void StandardItemDecreasesInQuality(int startingSellIn, int expectedValueAfterUpdate)
//{
// var item = new Item
// {
// Name = "This is a standard item",
// Quality = 10,
// SellIn = startingSellIn
// };
// item.Update();
// Assert.That(item.Quality, Is.EqualTo(expectedValueAfterUpdate));
//}
[TestCase(1000, -50)]
[TestCase(-80, 0)]
[TestCase(1, 1)]
public void LegendaryItemDoesNotChange(int quality, int sellIn)
{
var item = new Item
{
Name = "Sulfuras, Hand of Ragnaros",
Quality = quality,
SellIn = sellIn
};
item.Update();
Assert.That(item.Quality, Is.EqualTo(quality));
Assert.That(item.SellIn, Is.EqualTo(sellIn));
}
//[TestCase(16, 21)]
//[TestCase(15, 21)]
//[TestCase(10, 22)]
//[TestCase(1, 23)]
//[TestCase(0, 0)]
//public void BackstagePassQualityDecreasesBeforeEvent(int startingSellIn, int expectedQualityAfterUpdate)
//{
// var item = new Item
// {
// Name = "Backstage passes to a TAFKAL80ETC concert",
// Quality = 20,
// SellIn = startingSellIn
// };
// item.Update();
// Assert.That(item.Quality, Is.EqualTo(expectedQualityAfterUpdate));
//}
//[TestCase(10, 11)]
//[TestCase(5, 11)]
//[TestCase(0, 12)]
//[TestCase(-1, 12)]
//public void IncreasingValueItemsIncreaseInQuality(int startingSellIn, int expectedQualityAfterUpdate)
//{
// var item = new Item
// {
// Name = "Aged Brie",
// Quality = 10,
// SellIn = startingSellIn
// };
// item.Update();
// Assert.That(item.Quality, Is.EqualTo(expectedQualityAfterUpdate));
//}
}
} |
// Accord Imaging Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// Copyright © Peter Kovesi, 1995-2010
// Centre for Exploration Targeting
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// This work has been inspired by the original work of Peter Kovesi,
// shared under a permissive MIT license. Details are given below:
//
// Copyright (c) 1995-2010 Peter Kovesi
// Centre for Exploration Targeting
// School of Earth and Environment
// The University of Western Australia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// The software is provided "as is", without warranty of any kind, express or
// implied, including but not limited to the warranties of merchantability,
// fitness for a particular purpose and noninfringement. In no event shall the
// authors or copyright holders be liable for any claim, damages or other liability,
// whether in an action of contract, tort or otherwise, arising from, out of or in
// connection with the software or the use or other dealings in the software.
//
namespace Accord.Imaging
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using Accord.Math;
using AForge;
using Accord.Imaging.Filters;
/// <summary>
/// Maximum cross-correlation feature point matching algorithm.
/// </summary>
///
/// <remarks>
/// <para>
/// This class matches feature points by using a maximum cross-correlation measure.</para>
/// <para>
/// References:
/// <list type="bullet">
/// <item><description>
/// P. D. Kovesi. MATLAB and Octave Functions for Computer Vision and Image Processing.
/// School of Computer Science and Software Engineering, The University of Western Australia.
/// Available in: <a href="http://www.csse.uwa.edu.au/~pk/Research/MatlabFns/Match/matchbycorrelation.m">
/// http://www.csse.uwa.edu.au/~pk/Research/MatlabFns/Match/matchbycorrelation.m </a>
/// </description></item>
/// <item><description>
/// <a href="http://www.instructor.com.br/unesp2006/premiados/PauloHenrique.pdf">
/// http://www.instructor.com.br/unesp2006/premiados/PauloHenrique.pdf </a>
/// </description></item>
/// <item><description>
/// <a href="http://siddhantahuja.wordpress.com/2010/04/11/correlation-based-similarity-measures-summary/">
/// http://siddhantahuja.wordpress.com/2010/04/11/correlation-based-similarity-measures-summary/ </a>
/// </description></item>
/// </list></para>
/// </remarks>
///
/// <seealso cref="RansacHomographyEstimator"/>
///
public class CorrelationMatching
{
private Bitmap image1;
private Bitmap image2;
private int windowSize;
private double dmax;
/// <summary>
/// Gets or sets the maximum distance to consider
/// points as correlated.
/// </summary>
///
public double DistanceMax
{
get { return dmax; }
set { dmax = value; }
}
/// <summary>
/// Gets or sets the size of the correlation window.
/// </summary>
///
public int WindowSize
{
get { return windowSize; }
set { windowSize = value; }
}
/// <summary>
/// Constructs a new Correlation Matching algorithm.
/// </summary>
///
[Obsolete("Please use the overload that accepts bitmaps.")]
public CorrelationMatching(int windowSize)
: this(windowSize, 0)
{
}
/// <summary>
/// Constructs a new Correlation Matching algorithm.
/// </summary>
///
public CorrelationMatching(int windowSize, Bitmap image1, Bitmap image2)
: this(windowSize, 0, image1, image2)
{
}
/// <summary>
/// Constructs a new Correlation Matching algorithm.
/// </summary>
///
[Obsolete("Please use the overload that accepts bitmaps.")]
public CorrelationMatching(int windowSize, double maxDistance)
: this(windowSize, maxDistance, null, null)
{
}
/// <summary>
/// Constructs a new Correlation Matching algorithm.
/// </summary>
///
public CorrelationMatching(int windowSize, double maxDistance, Bitmap image1, Bitmap image2)
{
if (windowSize % 2 == 0)
throw new ArgumentException("Window size should be odd", "windowSize");
this.image1 = image1;
this.image2 = image2;
this.windowSize = windowSize;
this.dmax = maxDistance;
}
/// <summary>
/// Matches two sets of feature points computed from the given images.
/// </summary>
///
[Obsolete("Please use Match(points1, points2) instead.")]
public IntPoint[][] Match(Bitmap image1, Bitmap image2,
IEnumerable<IntPoint> points1, IEnumerable<IntPoint> points2)
{
this.image1 = image1;
this.image2 = image2;
return Match(points1, points2);
}
/// <summary>
/// Matches two sets of feature points computed from the given images.
/// </summary>
///
public IntPoint[][] Match(IEnumerable<IntPoint> points1, IEnumerable<IntPoint> points2)
{
return Match(points1.ToArray(), points2.ToArray());
}
/// <summary>
/// Matches two sets of feature points computed from the given images.
/// </summary>
///
[Obsolete("Please use Match(points1, points2) instead.")]
public IntPoint[][] Match(Bitmap image1, Bitmap image2,
IntPoint[] points1, IntPoint[] points2)
{
this.image1 = image1;
this.image2 = image2;
return Match(points1, points2);
}
/// <summary>
/// Matches two sets of feature points computed from the given images.
/// </summary>
///
public IntPoint[][] Match(IntPoint[] points1, IntPoint[] points2)
{
// Make sure we are dealing with grayscale images.
Bitmap grayImage1, grayImage2;
if (image1.PixelFormat == PixelFormat.Format8bppIndexed)
{
grayImage1 = image1;
}
else
{
// create temporary grayscale image
grayImage1 = Grayscale.CommonAlgorithms.BT709.Apply(image1);
}
if (image2.PixelFormat == PixelFormat.Format8bppIndexed)
{
grayImage2 = image2;
}
else
{
// create temporary grayscale image
grayImage2 = Grayscale.CommonAlgorithms.BT709.Apply(image2);
}
// Generate correlation matrix
double[,] correlationMatrix =
computeCorrelationMatrix(grayImage1, points1, grayImage2, points2, windowSize, dmax);
// Free allocated resources
if (image1.PixelFormat != PixelFormat.Format8bppIndexed)
grayImage1.Dispose();
if (image2.PixelFormat != PixelFormat.Format8bppIndexed)
grayImage2.Dispose();
// Select points with maximum correlation measures
int[] colp2forp1; Matrix.Max(correlationMatrix, 1, out colp2forp1);
int[] rowp1forp2; Matrix.Max(correlationMatrix, 0, out rowp1forp2);
// Construct the lists of matched point indices
int rows = correlationMatrix.GetLength(0);
List<int> p1ind = new List<int>();
List<int> p2ind = new List<int>();
// For each point in the first set of points,
for (int i = 0; i < rows; i++)
{
// Get the point j in the second set of points with which
// this point i has a maximum correlation measure. (i->j)
int j = colp2forp1[i];
// Now, check if this point j in the second set also has
// a maximum correlation measure with the point i. (j->i)
if (rowp1forp2[j] == i)
{
// The points are consistent. Ensure they are valid.
if (correlationMatrix[i, j] != Double.NegativeInfinity)
{
// We have a corresponding pair (i,j)
p1ind.Add(i); p2ind.Add(j);
}
}
}
// Extract matched points from original arrays
var m1 = points1.Submatrix(p1ind.ToArray());
var m2 = points2.Submatrix(p2ind.ToArray());
// Create matching point pairs
return new IntPoint[][] { m1, m2 };
}
/// <summary>
/// Constructs the correlation matrix between selected points from two images.
/// </summary>
///
/// <remarks>
/// Rows correspond to points from the first image, columns correspond to points
/// in the second.
/// </remarks>
///
private static double[,] computeCorrelationMatrix(
Bitmap image1, IntPoint[] points1,
Bitmap image2, IntPoint[] points2,
int windowSize, double maxDistance)
{
// Create the initial correlation matrix
double[,] matrix = Matrix.Create(points1.Length, points2.Length, Double.NegativeInfinity);
// Gather some information
int width1 = image1.Width;
int width2 = image2.Width;
int height1 = image1.Height;
int height2 = image2.Height;
int r = (windowSize - 1) / 2; // 'radius' of correlation window
double m = maxDistance * maxDistance; // maximum considered distance
double[,] w1 = new double[windowSize, windowSize]; // first window
double[,] w2 = new double[windowSize, windowSize]; // second window
// Lock the images
BitmapData bitmapData1 = image1.LockBits(new Rectangle(0, 0, width1, height1),
ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
BitmapData bitmapData2 = image2.LockBits(new Rectangle(0, 0, width2, height2),
ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
int stride1 = bitmapData1.Stride;
int stride2 = bitmapData2.Stride;
// We will ignore points at the edge
int[] idx1 = Matrix.Find(points1,
p => p.X >= r && p.X < width1 - r &&
p.Y >= r && p.Y < height1 - r);
int[] idx2 = Matrix.Find(points2,
p => p.X >= r && p.X < width2 - r &&
p.Y >= r && p.Y < height2 - r);
// For each index in the first set of points
foreach (int n1 in idx1)
{
// Get the current point
var p1 = points1[n1];
unsafe // Create the first window for the current point
{
byte* src = (byte*)bitmapData1.Scan0 + (p1.X - r) + (p1.Y - r) * stride1;
for (int j = 0; j < windowSize; j++)
{
for (int i = 0; i < windowSize; i++)
w1[i, j] = (byte)(*(src + i));
src += stride1;
}
}
// Normalize the window
double sum = 0;
for (int i = 0; i < windowSize; i++)
for (int j = 0; j < windowSize; j++)
sum += w1[i, j] * w1[i, j];
sum = System.Math.Sqrt(sum);
for (int i = 0; i < windowSize; i++)
for (int j = 0; j < windowSize; j++)
w1[i, j] /= sum;
// Identify the indices of points in p2 that we need to consider.
int[] candidates;
if (maxDistance == 0)
{
// We should consider all points
candidates = idx2;
}
else
{
// We should consider points that are within
// distance maxDistance apart
// Compute distances from the current point
// to all points in the second image.
double[] distances = new double[idx2.Length];
for (int i = 0; i < idx2.Length; i++)
{
double dx = p1.X - points2[idx2[i]].X;
double dy = p1.Y - points2[idx2[i]].Y;
distances[i] = dx * dx + dy * dy;
}
candidates = idx2.Submatrix(Matrix.Find(distances, d => d < m));
}
// Calculate normalized correlation measure
foreach (int n2 in candidates)
{
var p2 = points2[n2];
unsafe // Generate window in 2nd image
{
byte* src = (byte*)bitmapData2.Scan0 + (p2.X - r) + (p2.Y - r) * stride2;
for (int j = 0; j < windowSize; j++)
{
for (int i = 0; i < windowSize; i++)
w2[i, j] = (byte)(*(src + i));
src += stride2;
}
}
double sum1 = 0, sum2 = 0;
for (int i = 0; i < windowSize; i++)
{
for (int j = 0; j < windowSize; j++)
{
sum1 += w1[i, j] * w2[i, j];
sum2 += w2[i, j] * w2[i, j];
}
}
matrix[n1, n2] = sum1 / Math.Sqrt(sum2);
}
}
// Release the images
image1.UnlockBits(bitmapData1);
image2.UnlockBits(bitmapData2);
return matrix;
}
}
}
|
namespace Pyramidic
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Pyramidic
{
public static void Main(string[] args)
{
//var for number of strings;
var n = int.Parse(Console.ReadLine());
//list for piramids strings;
var piramids = new List<string>();
//array for lines;
string[] lines = new string[n];
//fill the line array;
for (int i = 0; i < n; i++)
{
lines[i] = Console.ReadLine();
}
for (int i = 0; i < lines.Length; i++)
{
//var for current line in lines array;
var currentLine = lines[i];
for (int j = 0; j < currentLine.Length; j++)
{
//var current char in current line;
var currentChar = currentLine[j];
//var for count of matched substring;
var count = 3;
for (int k = i + 1; k < lines.Length; k++)
{
//var for matched string;
var matchStr = new string(currentChar, count);
//add matched string to piramid list;
if (lines[k].Contains(matchStr))
{
piramids.Add(matchStr);
}
count = count + 2;
}//end of third for loop;
}//end of second for loo;
}//end of first for loop;
//take the string with highest length in piramids list;
var maxStr = piramids.OrderByDescending(x => x.Count()).First();
//take first char of highest length string;
var maxChar = maxStr.First();
//printing the result;
for (int i = 1; i <= maxStr.Length; i = i + 2)
{
Console.WriteLine(new string(maxChar, i));
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Platformer.Mechanics;
using UnityEngine.UI;
public class SkillButton : MonoBehaviour
{
public GameObject[] previousReq;
public GameObject[] nextReq;
bool skillPlus1 = false;
public int abilityLevel = 0;
public GameObject skillTree;
public int abilityLevelReq = 1;
public bool unlockThisSkill = false;
public bool unlockNextSkill = false;
public string skilButtonID;
public void SetDefault()
{
unlockThisSkill = false;
unlockNextSkill = false;
if(previousReq == null || previousReq.Length == 0)
{
unlockThisSkill = true;
}
if(unlockThisSkill == true){
GetComponent<Image>().color = new Color (1, 1, 1, 1);
}else
{
GetComponent<Image>().color = new Color (.5f, .5f, .5f, 1);
}
}
void Start()
{
SetDefault();
}
public void UnlockCurrentTeir()
{
if(previousReq == null)
{
unlockThisSkill = true;
GetComponent<Image>().color = new Color (1, 1, 1, 1);
return;
}
for (int i = 0; i < previousReq.Length; i++)
{
if(previousReq[i].GetComponent<SkillButton>().unlockNextSkill == false)
{
unlockThisSkill = false;
GetComponent<Image>().color = new Color (.5f, .5f, .5f, 1);
return;
}
}
unlockThisSkill = true;
GetComponent<Image>().color = new Color (1, 1, 1, 1);
return;
}
public void UnlockNextTeir()
{
if(abilityLevel == abilityLevelReq)
{
unlockNextSkill = true;
}
for (int i = 0; i < nextReq.Length; i++)
{
nextReq[i].GetComponent<SkillButton>().UnlockCurrentTeir();
}
}
void OnMouseDown()
{
if (unlockThisSkill == false)
{
//holding left click colors red trying to upgrade a locked skill
GetComponent<Image>().color = new Color (1, 0, 0, 1);
}
else
{
if (skillTree.GetComponent<SkillTree>().abilityPoints != 0)
{
//holding left click this colors green upgrading a skill
GetComponent<Image>().color = new Color (0, 1, 0, 1);
}
else
{
//holding left click this colors red upgrading a skill without any points left
GetComponent<Image>().color = new Color (1, 0, 0, 1);
}
}
}
public void UseButton()
{
if (unlockThisSkill == true)
{
//if skill is unlocked, then you decuct a point from skill tree
skillPlus1 = skillTree.GetComponent<SkillTree>().UpgradeSkill();
}
if(skillPlus1 == true)
{
abilityLevel = abilityLevel + 1;
UnlockNextTeir();
UnlockCurrentTeir();
skillPlus1 = false;
}
}
// Update is called once per frame
void Update()
{
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Xml.Serialization;
using System.IO;
public class AchievementList
{
List<Achievement> m_AchievementList;
private static AchievementList m_sInstance = null;
private AchievementList()
{
m_sInstance = this;
}
public static AchievementList Instance
{
get
{
if (m_sInstance == null)
{
m_sInstance = new AchievementList();
}
return m_sInstance;
}
}
public void Init()
{
m_AchievementList = new List<Achievement>();
TextAsset txt = (TextAsset)Resources.Load("AchivementTable", typeof(TextAsset));
string[] linesInFile = txt.text.Split('\n');
int idx = 0;
int aid = 0;
while (idx < linesInFile.GetLength(0)) {
string title = linesInFile[idx++];
string des = linesInFile[idx++];
string[] numbers = linesInFile[idx++].Split(' ');
List<int> req = new List<int>();
for (int i = 0; i < numbers.GetLength(0); i++)
{
req.Add(int.Parse(numbers[i]));
}
Achievement_Action action = (Achievement_Action)Enum.Parse(typeof(Achievement_Action), linesInFile[idx++]);
Achievement a = new Achievement();
a.SetInfo(title, des, req, action);
a.SetCounter(GameManager.Instance.GetPlayerProfile().m_AchievementCounter[aid]);
m_AchievementList.Add(a);
aid++;
}
}
public int GetAchievementCount()
{
return m_AchievementList.Count;
}
public Achievement GetAchievementBy(int id)
{
return m_AchievementList[id];
}
public void OnAction(Achievement_Action action)
{
PlayerProfile pl = GameManager.Instance.GetPlayerProfile();
for (int i = 0; i < m_AchievementList.Count; i++)
{
m_AchievementList[i].OnAction(action);
pl.m_AchievementCounter[i] = m_AchievementList[i].GetCounter();
}
pl.Save();
}
public void OnSingleWin()
{
OnAction(Achievement_Action.WIN_SINGLE);
}
public void OnMultiWin()
{
OnAction(Achievement_Action.WIN_MULTI);
}
}
|
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel;
namespace Promact.Oauth.Server
{
public static class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel(KestralOptions)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
private static void KestralOptions(KestrelServerOptions kestrelServerOptions)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (environment == "Production")
{
var password = Environment.GetEnvironmentVariable("SELFSIGNED_CERT_PASSWORD");
kestrelServerOptions.UseHttps("cert.pfx", password);
}
}
}
}
|
namespace _02.OneToManyRelation
{
using _02.OneToManyRelation.Data;
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer("Server=.;Database=TestDatabase;Integrated Security=True;");
base.OnConfiguring(builder);
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Employee>()
.HasOne(e => e.Department)
.WithMany(d => d.Employees)
.HasForeignKey(e => e.DepartmentId);
builder.Entity<Employee>()
.HasOne(e => e.Manager)
.WithMany(m => m.Employees)
.HasForeignKey(e => e.ManagerId)
.OnDelete(DeleteBehavior.Restrict);
}
}
} |
using UnityEngine;
public class RigidPaperAirplane : MonoBehaviour {
private const float killHeight = -10.0f;
private Rigidbody rigidBody;
public bool isSpinning = false;
void Start() {
rigidBody = GetComponent<Rigidbody>();
rigidBody.maxAngularVelocity = 0.0f;
rigidBody.freezeRotation = true;
}
void Update () {
// Remove game object when it falls under the floor.
if (transform.position.y < killHeight) {
Destroy(gameObject);
}
// Always point in the direction of motion.
if (!isSpinning) {
Vector3 forward = transform.rotation * Vector3.forward;
Quaternion rotation = Quaternion.FromToRotation(forward, rigidBody.velocity);
transform.rotation = rotation * transform.rotation;
}
}
public void Spin() {
if (!isSpinning) {
rigidBody.freezeRotation = false;
rigidBody.maxAngularVelocity = 8.0f;
rigidBody.angularVelocity = Random.onUnitSphere * 8.0f;
isSpinning = true;
}
}
}
|
using System;
using Logs.Common;
using Logs.Providers.Contracts;
using Ninject.Extensions.Interception;
namespace Logs.Web.Infrastructure.Interception
{
public class CachingInterceptor : IInterceptor
{
private readonly ICachingProvider cachingProvider;
private readonly IDateTimeProvider dateTimeProvider;
public CachingInterceptor(ICachingProvider cachingProvider, IDateTimeProvider dateTimeProvider)
{
if (cachingProvider == null)
{
throw new ArgumentNullException(nameof(cachingProvider));
}
if (dateTimeProvider == null)
{
throw new ArgumentNullException(nameof(dateTimeProvider));
}
this.cachingProvider = cachingProvider;
this.dateTimeProvider = dateTimeProvider;
}
public void Intercept(IInvocation invocation)
{
var key = string.Format("{0}{1}", invocation.Request.Method.Name, string.Join("&", invocation.Request.Arguments));
var result = this.cachingProvider.GetItem(key);
if (result != null)
{
invocation.ReturnValue = result;
}
else
{
invocation.Proceed();
result = invocation.ReturnValue;
var date = this.dateTimeProvider.GetTimeFromCurrentTime(Constants.HoursCaching,
Constants.MinutesCaching,
Constants.SecondsCaching);
this.cachingProvider.AddItem(key, result, date);
}
}
}
} |
namespace FeedsProcessing.Common.Models
{
public class BackingStoreInfo
{
public BackingStoreInfo(NotificationSource source, int index, string id)
{
FileId = id;
Source = source.ToString().ToLowerInvariant();
DirIndex = index;
}
public string Source { get; }
public string FileId { get; }
public int DirIndex { get; }
}
}
|
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using App1.Services;
namespace App1
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
btnScan.Clicked += BtnScan_Clicked;
}
private async void BtnScan_Clicked(object sender, EventArgs e)
{
var scanner = DependencyService.Get<IScanner>();
var result = await scanner.ScanAsync();
if (result != null)
barcode.Text = result;
}
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using TourApi.Models;
using TourApi.Repos;
namespace TourApi.Controllers
{
[Authorize]
[Route("[controller]")]
public class SightsController : Controller
{
private ISightsRepository _sightRepository;
public SightsController(ISightsRepository sightRepository)
{
_sightRepository = sightRepository;
}
[HttpGet]
public async Task<IActionResult> GetAllSights()
{
return Ok(await _sightRepository.GetAllSights());
}
[HttpGet("{id}")]
public async Task<IActionResult> GetSights(Guid id)
{
var result = await _sightRepository.GetSights(id);
if(result.Count != 0)
return Ok(result);
return NotFound();
}
[HttpPost]
public async Task<IActionResult> AddSight([FromBody]Sight sight)
{
Sight result;
try
{
result = await _sightRepository.Create(sight);
}
catch (Exception ex)
{
return BadRequest();
}
return Ok(result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using DataAccess.POCO;
namespace DataAccess.Interfaces
{
public interface IAddressesRepository : IRepository<Addresses>
{
IEnumerable<Addresses> GetByCustomer(string id);
}
}
|
using System.Threading.Tasks;
using WooliesChallenge.Application.Helpers;
using WooliesChallenge.Application.Interfaces;
using WooliesChallenge.Application.Models;
namespace WooliesChallenge.Application.Services
{
public class UserService: IUserService
{
public async Task<User> GetUser()
{
return await Task.FromResult(new User {Name = Constants.Name, Token = Constants.Token });
}
}
}
|
using AutoMapper;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using MyCashFlow.Domains.DataObject;
using MyCashFlow.Identity.Context;
using MyCashFlow.Web.ViewModels.Account;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using System;
namespace MyCashFlow.Web.Services.Account
{
public class AccountService : IAccountService
{
private readonly ApplicationDbContext _dbContext;
public AccountService(ApplicationDbContext dbContext)
{
if(dbContext == null)
{
throw new ArgumentNullException(nameof(dbContext));
}
_dbContext = dbContext;
}
public RegisterViewModel BuildRegisterViewModel()
{
var model = new RegisterViewModel
{
Countries = GetCountries()
};
return model;
}
public IEnumerable<Country> GetCountries()
{
var countries = _dbContext.Countries;
return countries;
}
public VerifyCodeViewModel BuildVerifyCodeViewModel(
string provider,
string returnUrl,
bool rememberMe)
{
var result = new VerifyCodeViewModel
{
Provider = provider,
ReturnUrl = returnUrl,
RememberMe = rememberMe
};
return result;
}
public async Task<IdentityResult> RegisterUserAsync(
UserManager<User, int> userManager,
SignInManager<User, int> signInManager,
RegisterViewModel model)
{
var user = Mapper.Map<User>(model);
var result = await userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await signInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
}
return result;
}
public async Task<IdentityResult> ResetPasswordAsync(
UserManager<User, int> userManager,
ResetPasswordViewModel model)
{
var user = await userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return IdentityResult.Success;
}
var result = await userManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
return result;
}
public async Task<SendCodeViewModel> BuildSendCodeViewModelAsync(
UserManager<User, int> userManager,
SignInManager<User, int> signInManager,
string returnUrl,
bool rememberMe)
{
var userId = await signInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return null;
}
var userFactors = await userManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
var result = new SendCodeViewModel
{
Providers = factorOptions,
ReturnUrl = returnUrl,
RememberMe = rememberMe
};
return result;
}
public async Task<IdentityResult> ConfirmExternalLoginAsync(
IAuthenticationManager authenticationManager,
UserManager<User, int> userManager,
SignInManager<User, int> signInManager,
ExternalLoginConfirmationViewModel model)
{
// Get the information about the user from the external login provider
var info = await authenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return null;
}
// TODO: Automapper
var user = new User
{
UserName = model.Email,
Email = model.Email
};
var result = await userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await userManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await signInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return IdentityResult.Success;
}
}
return result;
}
}
} |
namespace ModelAndroidApp.ModelAndroid
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Movimento")]
public partial class Movimento
{
public int ID { get; set; }
[Column(TypeName = "date")]
public DateTime? Data { get; set; }
[StringLength(250)]
public string Detalhe { get; set; }
public decimal? Valor { get; set; }
public int? IDMovimento { get; set; }
public int? DocumentoID { get; set; }
public int? NumeroPedido { get; set; }
[StringLength(500)]
public string Operacao { get; set; }
[StringLength(500)]
public string Pessoa { get; set; }
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TrackBack.Data;
using TrackBack.Models;
namespace TrackBack.Controllers
{
public class BookmarksController : Controller
{
private readonly DataContext _context;
public BookmarksController(DataContext context)
{
_context = context;
}
public IActionResult Index()
{
var bookmarkItems = _context.Bookmarks.Include(bookmark => bookmark.Project);
return View(bookmarkItems);
}
public IActionResult Create(int projectId)
{
ViewBag.ProjectId = projectId;
return View();
}
[HttpPost]
public IActionResult Create(Bookmark bookmark)
{
_context.Bookmarks.Add(bookmark);
_context.SaveChanges();
return RedirectToAction("Dashboard", "Projects", new { id = bookmark.ProjectId });
}
public IActionResult Edit(int id)
{
var bookmarkToEdit = _context.Bookmarks.Find(id);
if (bookmarkToEdit == null)
{
return NotFound();
}
return View(bookmarkToEdit);
}
[HttpPost]
public IActionResult Edit(Bookmark bookmark)
{
_context.Bookmarks.Update(bookmark);
_context.SaveChanges();
return RedirectToAction("Dashboard", "Projects", new { id = bookmark.ProjectId });
}
public IActionResult Delete(int id)
{
var bookmarkToDelete = _context.Bookmarks.Find(id);
if (bookmarkToDelete == null)
{
return NotFound();
}
_context.Bookmarks.Remove(bookmarkToDelete);
_context.SaveChanges();
return RedirectToAction("Dashboard", "Projects", new { id = bookmarkToDelete.ProjectId });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.Web;
using System.Web.Mvc;
using KT.ServiceInterfaces;
using KnowledgeTester.Helpers;
using KnowledgeTester.Models;
using KnowledgeTester.Ninject;
using KnowledgeTester.WCFServices;
using KT.Logger;
using Newtonsoft.Json;
namespace KnowledgeTester.Controllers
{
public class HomeController : Controller
{
private static ILogger _log = ServicesFactory.GetService<ILogger>();
public ActionResult Index()
{
if (SessionWrapper.UserIsAdmin)
{
return RedirectToAction("Index", "AdminPanel");
}
if (SessionWrapper.UserIsLoggedIn)
{
return RedirectToAction("Index", "StudentPanel");
}
return View(new LoginModel());
}
[HttpPost]
public ActionResult Login(LoginModel pageModel)
{
try
{
if (!ModelState.IsValid)
{
return View("Index", pageModel);
}
var valid = ServicesFactory.GetService<IKtUsersService>().
Authenticate(pageModel.UserName, pageModel.Password);
if (valid)
{
SessionWrapper.User = ServicesFactory.GetService<IKtUsersService>().GetByKey(pageModel.UserName);
SessionWrapper.UserIsAdmin = SessionWrapper.User.IsAdmin;
_log.Info("Logged in from Home Controller", SessionWrapper.User.Username);
if (SessionWrapper.UserIsAdmin)
{
return RedirectToAction("Index", "AdminPanel");
}
return RedirectToAction("Index", "StudentPanel");
}
return View("Index", pageModel);
}
catch (Exception ex)
{
_log.Error(ex.Message, SessionWrapper.User.Username, ex);
throw;
}
}
[HttpPost]
public ActionResult Logout()
{
SessionWrapper.Logout();
return RedirectToAction("Index", "Home");
}
[HttpPost]
public ActionResult GetHint(string userName)
{
var value = ServicesFactory.GetService<IKtUsersService>().GetHint(userName);
return Json(value, JsonRequestBehavior.AllowGet);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoursIngesup._3___Héritage
{
class Point
{
#region variable
int x;
int y;
#endregion
#region constructeur
#endregion
#region fonction
#endregion
}
}
|
using System;
using tryfsharplib;
using Xamarin.Forms;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace tryfsharpforms
{
public class AnalyzingStockMarketsPage : BasePage
{
GetDataButton obtainListOfIndicatorsButton = new GetDataButton(Borders.Thin,1){ Text = "Obtain Indicators" };
public AnalyzingStockMarketsPage ()
{
Content = new StackLayout {
Padding = new Thickness (15),
Children = {
new Label {
Text = "Obtain list of global market indicators",
HorizontalOptions = LayoutOptions.CenterAndExpand,
FontAttributes = FontAttributes.Bold,
TextColor = MyColors.Clouds
},
obtainListOfIndicatorsButton
}
};
obtainListOfIndicatorsButton.Clicked += ObtainListOfIndicatorsButton_Clicked;
}
void ObtainListOfIndicatorsButton_Clicked (object sender, EventArgs e)
{
Navigation.PushAsync (new AnalyzingStockMarketsChartPage ());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using CHashLab1;
namespace CHashLab2
{
class HTTPServer
{
private HttpListener listener;
private string path;
int port;
private Thread thread;
public HTTPServer(string path, int port)
{
this.path = path;
this.port = port;
thread = new Thread(this.listen);
thread.Start();
}
private void listen()
{
try
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:"+port+"/");
listener.Start();
while (true)
{
Console.WriteLine("Listening...");
HttpListenerContext context = listener.GetContext();
exist(context,path);
}
}
catch (WebException e)
{
Console.WriteLine(e.Status);
}
}
public void stop()
{
thread.Abort();
listener.Stop();
}
private void exist(HttpListenerContext context,string path)
{
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
string responseString="";
string fileName = context.Request.Url.AbsolutePath;
fileName = fileName.Substring(1);
fileName = Path.Combine(path, fileName);
string[] fileList = Directory.GetFiles(path);
if (File.Exists(fileName))
{
try
{
foreach (string file_name in fileList)
{
if (file_name == fileName)
{
Console.WriteLine(file_name);
responseString = File.ReadAllText(fileName);
responseString += status(request);
contentView(responseString, response);
}
}
context.Response.StatusCode = (int)HttpStatusCode.OK;
}
catch (Exception ex)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
responseString = "500";
contentView(responseString, response);
Console.WriteLine(context.Response.StatusCode);
}
}
else if(fileName == path)
{
Random rnd = new Random();
int random = rnd.Next(1, 5);
string[] tabString = null;
Html obiekt1, obiekt2, obiekt3, obiekt4;
obiekt1 = new Html(2, 2, 1, tabString);
obiekt2 = new Html(2, 3, 2, tabString);
obiekt3 = new Html(3, "lab2_3.csv");
obiekt4 = new Html(2, 5, 4, tabString);
if (random == 1)
{
responseString = obiekt1.kodWynikowy();
obiekt1.zapisPliku(responseString,0);
}
else if (random == 2)
{
responseString = obiekt2.kodWynikowy();
obiekt2.zapisPliku(responseString, 0);
}
else if (random == 3)
{
responseString = obiekt3.kodWynikowy();
obiekt3.zapisPliku(responseString, 0);
}
else if (random == 4)
{
responseString = obiekt4.kodWynikowy();
obiekt4.zapisPliku(responseString, 0);
}
Console.WriteLine(fileName+@"\index.html");
responseString += status(request);
contentView(responseString, response);
}
else
{
if (context.Request.Url.AbsolutePath.Substring(1) == "favicon.ico")
{
return;
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
responseString = "404";
contentView(responseString, response);
Console.WriteLine(context.Response.StatusCode);
}
}
}
public string status(HttpListenerRequest request)
{
string str = "\n<br>";
System.Collections.Specialized.NameValueCollection headers = request.Headers;
foreach (string key in headers.AllKeys)
{
string[] values = headers.GetValues(key);
if (values.Length > 0)
{
str += key + ":";
foreach (string value in values)
{
str += " " + value + "\n<br>" ;
}
}
else
Console.WriteLine("There is no value associated with the header.");
}
return str;
}
public void contentView(string responseString, HttpListenerResponse response)
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
}
}
}
|
using System;
using System.Collections.Generic;
using FitBox.DomainModel;
using FitBox.Helper;
using FitBox.Logic;
namespace FitBox
{
public static class Program
{
public static void Main(string[] args)
{
Service.DisplayHeader();
// Read measuring unit
(string dimension,string mass) = Service.CollectUnitOfMeasurmentInformation();
//Read boxes information
(Box boxOne,Box boxTwo) = Service.CollectBoxesInfo(2, dimension, mass);
//Process the boxes
var processBox = new FitBoxProcess();
var bigBox = processBox.AnaylseBoxes(boxOne, boxTwo);
var totalNumberOfBoxes = processBox.NumberOfBoxesThatFits(boxOne, boxTwo);
var totalWeight = processBox.CalculateTotalWeight(totalNumberOfBoxes, boxOne, boxTwo);
//Display information of boxes and results
Service.DisplayBoxInformation(new List<Box> { boxOne, boxTwo }, dimension, mass);
Service.DisplayConclusion(bigBox, totalNumberOfBoxes, totalWeight, mass);
Console.ReadLine();
}
}
}
|
using Mis_Recetas.Controlador;
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 Mis_Recetas.Vista
{
public partial class FormModificarUsuario : Form
{
public FormModificarUsuario()
{
InitializeComponent();
}
CmdUsuarios com = new CmdUsuarios();
private int idUser;
private void btnCerrar_Click(object sender, EventArgs e)
{
this.Close();
}
private void dgvUsuarios_CellClick(object sender, DataGridViewCellEventArgs e)
{
string nombre = dgvUsuarios.Rows[e.RowIndex].Cells[1].Value.ToString();
string apellido = dgvUsuarios.Rows[e.RowIndex].Cells[2].Value.ToString();
string rol = dgvUsuarios.Rows[e.RowIndex].Cells[3].Value.ToString();
string user = dgvUsuarios.Rows[e.RowIndex].Cells[4].Value.ToString();
string pass = dgvUsuarios.Rows[e.RowIndex].Cells[5].Value.ToString();
txtNombre.Text = nombre;
txtApellido.Text = apellido;
cboRol.SelectedIndex = getRol(rol) - 1;
txtNomUsuario.Text = user;
txtPass.Text = pass;
idUser = Convert.ToInt32(dgvUsuarios.CurrentRow.Cells["ID"].Value);
}
private int getRol(string rol)
{
switch (rol)
{
case "Admin":
return 1;
case "Administración":
return 2;
case "Recepcionista":
return 3;
default:
return 3;
}
}
private void txtNombre_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar))
e.Handled = false;
else if (Char.IsControl(e.KeyChar)) //permitir teclas de control como retroceso
e.Handled = false;
else
e.Handled = true; //el resto de teclas pulsadas se desactivan
}
private void txtApellido_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar))
e.Handled = false;
else if (Char.IsControl(e.KeyChar)) //permitir teclas de control como retroceso
e.Handled = false;
else
e.Handled = true; //el resto de teclas pulsadas se desactivan
}
private void btnModificar_Click(object sender, EventArgs e)
{
//Obtengo el valor de lo campos y lo casteo a una variable.
string nombre = txtNombre.Text;
string apellido = txtApellido.Text;
int rol = cboRol.SelectedIndex + 1;
string user = txtNomUsuario.Text;
string pass = txtPass.Text;
//Llamo a los metodos y les paso las variables previamente casteadas.
com.ActualizarUsuario(user, pass, rol, nombre, apellido, idUser);
com.CargarUsuarios(dgvUsuarios);
limpiarCampos();
}
private void limpiarCampos()
{
txtApellido.Clear();
txtNombre.Clear();
txtNomUsuario.Clear();
txtPass.Clear();
}
private void btnMostrar_Click(object sender, EventArgs e)
{
com.CargarUsuarios(dgvUsuarios);
dgvUsuarios.ClearSelection();
}
private void cargarComboRoles()
{
com.CargarComboRol(cboRol);
cboRol.DisplayMember = "Descripcion";
cboRol.ValueMember = "Id_Rol";
}
private void FormModificarUsuario_Load(object sender, EventArgs e)
{
cargarComboRoles();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class GameProperties
{
public static int HaveShoes { get; set; } = 0;
public static int HaveScarf { get; set; } = 0;
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotationSensor : PlcInput {
public Transform target;
public Vector3 rotationOffset; // Offset from initial local position when the sensor state is set to 1
public float threshold = 0.5f; // [degree]
public bool debugValue;
Vector3 targetRotation;
void Start()
{
targetRotation = target.localEulerAngles + rotationOffset;
}
void Update()
{
bool okX = Mathf.Abs(Mathf.DeltaAngle(target.localEulerAngles.x, targetRotation.x)) <= threshold;
bool okY = Mathf.Abs(Mathf.DeltaAngle(target.localEulerAngles.y, targetRotation.y)) <= threshold;
bool okZ = Mathf.Abs(Mathf.DeltaAngle(target.localEulerAngles.z, targetRotation.z)) <= threshold;
bool value = okX && okY && okZ;
//if(name == "PackMotorLeftRotSensor")
// Debug.Log(target.localEulerAngles.z +" ->" + targetRotation.z + " = " + Mathf.DeltaAngle(target.localEulerAngles.z, targetRotation.z));
if (Value != value)
Value = value;
debugValue = Value;
}
}
|
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Ambassador.Entities;
using Ambassador.Models;
using System.Threading.Tasks;
using System.Reflection;
using System.ComponentModel;
namespace Ambassador.Data
{
public class DatabaseContext : IdentityDbContext<User>
{
public DbSet<Entities.Ambassador> Ambassadors { get; set; }
public DbSet<Organization> Organizations { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<EventSeries> EventSeries { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<MessageReceiver> MessageReceivers { get; set; }
public DbSet<Announcement> Announcements { get; set; }
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<User>().ToTable("Users");
builder.Entity<IdentityRole>().ToTable("Roles");
builder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");
builder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
builder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
builder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
builder.Entity<IdentityRoleClaim<Guid>>().ToTable("RoleClaims");
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public async Task<Result> PersistChangesAsync()
{
var result = new Result();
try
{
await this.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
var entityType = ex.Entries[0].Entity.GetType();
var displayNameAttribute = entityType.GetTypeInfo().GetCustomAttribute(typeof(DisplayNameAttribute));
var displayName = (displayNameAttribute as DisplayNameAttribute)?.DisplayName ?? entityType.Name;
result.AddError("", $"Unable to save changes to {displayName} because another user has modified this record. Reload the record to see the most recent version");
}
catch (DbUpdateException ex)
{
var entityType = ex.Entries[0].Entity.GetType();
var displayNameAttribute = entityType.GetTypeInfo().GetCustomAttribute(typeof(DisplayNameAttribute));
var displayName = (displayNameAttribute as DisplayNameAttribute)?.DisplayName ?? entityType.Name;
result.AddError("", $"Unable to save changes to {displayName} at this time. Please contact the system administrator if the problem persists");
}
return result;
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_MaterialGlobalIlluminationFlags : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.MaterialGlobalIlluminationFlags");
LuaObject.addMember(l, 0, "None");
LuaObject.addMember(l, 1, "RealtimeEmissive");
LuaObject.addMember(l, 2, "BakedEmissive");
LuaObject.addMember(l, 4, "EmissiveIsBlack");
LuaDLL.lua_pop(l, 1);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using CardLib;
using System.Diagnostics;
namespace Durak_Game
{
class Durak
{
private Deck deck;
private List<CardBox> computerCards;
private List<CardBox> myCards;
private CardBox topCard;
private List<Card> playingCards = new List<Card>();
private CardValues[] playingCardValues = {CardValues.Ace,CardValues.Six,CardValues.Seven,CardValues.Eight,CardValues.Nine,CardValues.Ten,
CardValues.Jack,CardValues.Queen,CardValues.King};
private CardSuits[] playingCardSuits = { CardSuits.Club, CardSuits.Diamond, CardSuits.Heart, CardSuits.Spade };
private Label computerCardsLeft;
private Label myCardsLeft;
private Label remaingCardsLeft;
private Label computerAttackerLabel;
private Label userAttackerLabel;
private Panel table;
private Panel computerDesk;
private Panel myDesk;
private CardSuits trumpSuite;
private List<CardBox> tableCards;
private static int COMPUTER = 1;
private static int ME = 2;
private int nowPlaying = 0;
private Form1 ui;
int top = 1;
private String logFileName = "log.txt";
private Boolean gameOver = false;
private int attacker;
public Durak()
{
deck = new Deck();
/*Initialise the list of cards gameCards with all the cards
* that are needed in the game.
**/
for (int i = 0; i < playingCardSuits.Length; i++)
{
for (int j = 0; j < playingCardValues.Length; j++)
{
Card card = new Card(playingCardSuits[i], playingCardValues[j]);
playingCards.Add(card);
}
}
/** Set the playing cards to deck */
deck.Cards = playingCards;
tableCards = new List<CardBox>();
}
public void setComputerCards()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
this.computerCards = new List<CardBox>();
for (int i = 0; i < 6; i++)
{
CardBox box = new CardBox();
this.computerCards.Add(box);
}
foreach (CardBox cardbox in this.computerCards)
{
Card deckDard = deck.GetRandomCard();
cardbox.setCard(deckDard);
}
computerCardsLeft.Text = "Cards Left : " + computerCards.Count;
arrangeComputerCards();
}
public void setMyCards()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
this.myCards = new List<CardBox>(6);
for (int i = 0; i < 6; i++)
{
CardBox box = new CardBox();
box.Cursor = Cursors.Hand;
box.Tag = i + 1;
box.cardBoxClicked += (s, e) =>
{
playGame((int)box.Tag);
};
this.myCards.Add(box);
}
foreach (CardBox cardbox in this.myCards)
{
Card deckDard = deck.GetRandomCard();
cardbox.setCard(deckDard);
cardbox.flipCard();
}
myCardsLeft.Text = "Cards Left : " + myCards.Count;
arrangeMyCards();
}
private void arrangeComputerCards()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
int x = 10;
int y = 10;
int xCount = 100;
if (computerCards.Count > 12)
{
xCount = 50;
}
foreach (CardBox computerCard in this.computerCards)
{
computerCard.SetBounds(x, y, 94, 125);
computerDesk.Controls.Add(computerCard);
computerCard.BringToFront();
x += xCount;
}
}
private void arrangeMyCards()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
int x = 10;
int y = 10;
//CardBox myCard in this.myCards
int xCount = 100;
if (myCards.Count > 12)
{
xCount = 50;
}
int i = 1;
foreach (CardBox myCard in this.myCards)
{
myCard.SetBounds(x, y, 94, 125);
myCard.Tag = i;
myDesk.Controls.Add(myCard);
myCard.BringToFront();
i++;
x += xCount;
}
}
public void setTopCard(CardBox card)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
this.topCard = card;
this.topCard.setCard(deck.GetRandomCard());
this.topCard.flipCard();
remaingCardsLeft.Text = "Remaining Cards \n " + (deck.NumberOfCards + 1);
trumpSuite = topCard.getCard().Suit;
deck.setTrumphCard(topCard.getCard());
}
public void setLabels(Label lbl1, Label lbl2, Label lbl3,Label lbl4,Label lbl5)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
this.computerCardsLeft = lbl1;
this.myCardsLeft = lbl2;
this.remaingCardsLeft = lbl3;
this.computerAttackerLabel = lbl4;
this.userAttackerLabel = lbl5;
}
public void setPanels(Panel table, Panel computerPanel, Panel myPanel)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
this.table = table;
this.computerDesk = computerPanel;
this.myDesk = myPanel;
}
public void playGame(int clickedCardIndex)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
if (nowPlaying != Durak.ME)
{
PopUp("You cant place this card");
log("User Attempt to place invalid card");
return;
}
if (gameOver)
{
return;
}
if (isValidMove(myCards, clickedCardIndex - 1))
{
log("User : valid Move ");
putCardOnTable(myCards, clickedCardIndex - 1);
nowPlaying = Durak.COMPUTER;
computerPutACard();
}
else
{
CardBox clickedCard = myCards.ElementAt<CardBox>(clickedCardIndex - 1);
Card card = clickedCard.getCard();
PopUp("Sorry... Can't place that card : " + card.ToString());
log(" User :Invalid move attempted");
}
//cardBox.Parent = table;
}
public Boolean isValidMove(List<CardBox> cards, int clickedCardIndex)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
if (tableCards.Count() <= 0) // First chance, when no cards on the table
{
return true;
}
CardBox clickedCard = cards.ElementAt<CardBox>(clickedCardIndex);
Card card = clickedCard.getCard();
/* if (card.Suit == trumpSuite && card.getCardRank()>topCard.getCard().getCardRank())
{
return true;
}*/
if (tableCards.Count == 1)
{
CardBox tableCardBox = tableCards.ElementAt<CardBox>(0);
Card tableCard = tableCardBox.getCard();
if (card.Suit == tableCard.Suit && card.getCardRank() > tableCard.getCardRank())
{
return true;
}
}
else
{
CardBox tableCardBox1 = tableCards.ElementAt<CardBox>(0);
Card tableCard1 = tableCardBox1.getCard();
CardBox tableCardBox2 = tableCards.ElementAt<CardBox>(1);
Card tableCard2 = tableCardBox2.getCard();
if (tableCards.Count() == 2 || tableCards.Count % 2 == 0)
{
if (card.getCardRank() == tableCard1.getCardRank() || card.getCardRank() == tableCard2.getCardRank())
{
return true;
}
else
{
return false;
}
}
else
{
CardBox topTableCard = tableCards.ElementAt<CardBox>(tableCards.Count - 1);
Card topCard = tableCardBox1.getCard();
if (card.getCardRank() == tableCard2.getCardRank() && card.Suit == topCard.Suit)
{
return true;
}
else
{
return false;
}
}
}
/*int tableRank = -1;
CardSuits tableSuit = CardSuits.Club;
foreach (CardBox cardbox in tableCards)
{
Card tableCard = cardbox.getCard();
if (tableCard.getCardRank() > tableRank)
{
tableRank = tableCard.getCardRank();
tableSuit = tableCard.Suit;
}
}
for (int i = 0; i < tableCards.Count; i++)
{
CardBox tableCardBox = tableCards.ElementAt<CardBox>(i);
Card tableCard = tableCardBox.getCard();
if (card.Suit == tableCard.Suit && card.getCardRank()>tableRank)
{
return true;
}
}*/
return false;
}
public void startGame()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
nowPlaying = findAttacker();
if (nowPlaying == Durak.COMPUTER)
{
PopUp("Computer is the attacker");
computerPutACard();
nowPlaying = Durak.ME;
}
else
{
PopUp("You are the attacker ");
setLabelTexts();
}
}
public int findAttacker()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
int computerSmallTrumph = findLowestTrump(computerCards);
int mySmallTrumph = findLowestTrump(myCards);
if (computerSmallTrumph < mySmallTrumph)
{
attacker = Durak.COMPUTER;
return Durak.COMPUTER;
}
attacker = Durak.ME;
return Durak.ME;
}
public int findLowestTrump(List<CardBox> cards)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
int small = 999;
foreach (CardBox card in cards)
{
Card playCard = card.getCard();
if (playCard.Suit == trumpSuite)
{
if (playCard.getCardRank() < small)
{
small = playCard.getCardRank();
}
}
}
return small;
}
public void setUI(Form1 ui)
{
this.ui = ui;
}
public void PopUp(String message)
{
MessageBox.Show(message);
log(message);
}
public void computerPutACard()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
if (gameOver)
{
return;
}
if (tableCards.Count() <= 0) // First chance, when no cards on the table
{
int cardNum = 0;
if (computerCards.Count <= 0)
{
return;
}
int rank = computerCards.ElementAt<CardBox>(cardNum).getCard().getCardRank();
for (int i = 1; i < computerCards.Count(); i++)
{
CardBox card = computerCards.ElementAt<CardBox>(i);
Card playCard = card.getCard();
if (playCard.getCardRank() > rank)
{
rank = playCard.getCardRank();
cardNum = i;
}
}
if (tableCards.Count() <= 0)
{
//first play
putCardOnTable(computerCards, cardNum);
}
if (detectThrow() == false)
{
nowPlaying = Durak.ME;
}
else
{
PopUp("You have no card to put... so computer will continue");
throwCards(Durak.COMPUTER);
computerPutACard();
nowPlaying = Durak.COMPUTER;
while (detectThrow())
{
PopUp("You have no card to put... so computer will continue");
throwCards(Durak.COMPUTER);
nowPlaying = Durak.COMPUTER;
computerPutACard();
}
nowPlaying = Durak.ME;
}
}
else
{
int cardNum = -1;
for (int i = 0; i < computerCards.Count; i++)
{
if (isValidMove(computerCards, i))
{
cardNum = i;
break;
}
}
if (cardNum != -1)
{
putCardOnTable(computerCards, cardNum);
if (detectThrow() == false)
{
nowPlaying = Durak.ME;
}
else
{
PopUp("You have no card to put... so computer will continue");
throwCards(Durak.COMPUTER);
nowPlaying = Durak.COMPUTER;
computerPutACard();
while (detectThrow())
{
PopUp("You have no card to put... so computer will continue");
throwCards(Durak.COMPUTER);
nowPlaying = Durak.COMPUTER;
computerPutACard();
}
nowPlaying = Durak.ME;
}
}
else
{
PopUp("Computer has no card to put, you can continue");
throwCards(Durak.ME);
nowPlaying = Durak.ME;
}
}
}
private void putCardOnTable(List<CardBox> cards, int clickedCardIndex)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
CardBox clickedCard = cards.ElementAt<CardBox>(clickedCardIndex);
clickedCard.Visible = false;
Card card = clickedCard.getCard();
CardBox cardBox = new CardBox();
cardBox.setCard(card);
cardBox.Width = 94;
cardBox.Height = 125;
cardBox.BackgroundImageLayout = ImageLayout.Stretch;
cardBox.flipCard();
tableCards.Add(cardBox);
int x = 10;
int y = 10;
foreach (CardBox tableCard in tableCards)
{
tableCard.SetBounds(x, y, 94, 125);
table.Controls.Add(tableCard);
tableCard.BringToFront();
if (y == 10)
{
y = 50;
}
else
{
y = 10;
x += 100;
}
}
cards.Remove(clickedCard);
setLabelTexts();
if (nowPlaying == Durak.ME)
{
arrangeMyCards();
}
else
{
arrangeComputerCards();
}
findWinner();
}
private void setLabelTexts()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
int computerCardsCount = computerCards.Count;//getVisibleCardCount(this.computerCards);
computerCardsLeft.Text = "Cards Left : " + computerCardsCount;
int myCardCount = myCards.Count;//getVisibleCardCount(this.myCards);
myCardsLeft.Text = "Cards Left : " + myCardCount;
if (top == 1)
{
remaingCardsLeft.Text = "Remaining Cards \n " + (deck.NumberOfCards + 1);
}
else
{
remaingCardsLeft.Text = "Remaining Cards \n 0";
}
if (attacker == Durak.COMPUTER)
{
computerAttackerLabel.Visible = true;
userAttackerLabel.Visible = false;
}
else
{
computerAttackerLabel.Visible = false;
userAttackerLabel.Visible = true;
}
}
public void throwCards(int fromPlayer)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
CardBox tableTopCard = tableCards.ElementAt<CardBox>(tableCards.Count - 1);
Boolean takeCards = true;
if (fromPlayer == Durak.COMPUTER && attacker == Durak.ME)
{
takeCards = false;
}
if (fromPlayer == Durak.ME && attacker == Durak.COMPUTER)
{
takeCards = false;
}
if (takeCards)
{
if (attacker == Durak.COMPUTER)
{
PopUp("You need to take the card from table");
nowPlaying = Durak.COMPUTER;
takeCardsFromTable(myCards);
}
else
{
PopUp("Computer takes the cards from table");
nowPlaying = Durak.ME;
takeCardsFromTable(computerCards);
}
}
tableCards.Clear();
table.Controls.Clear();
addCardsFromDeck();
}
private Boolean detectThrow()
{
for (int i = 0; i < myCards.Count; i++)
{
if (isValidMove(myCards, i))
return false;
}
return true;
}
private void findWinner()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
if (deck.NumberOfCards == 0 && top == 0)
{
if (computerCards.Count == 0)
{
PopUp("Computer Wins...");
writeWinner("computer");
gameOver = true;
}
else if (myCards.Count == 0)
{
PopUp("Congrats ... You wins...");
writeWinner("user");
gameOver = true;
}
}
else
{
if (deck.NumberOfCards == 0 && top != 0)
{
addCardsFromDeck();
}
}
}
private void addCardsFromDeck()
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
for (int i = computerCards.Count; i < 6; i++)
{
CardBox box = new CardBox();
Card deckDard = deck.GetRandomCard();
if (deckDard != null)
{
box.setCard(deckDard);
this.computerCards.Add(box);
}
else
{
if (top == 1)
{
// box = topCard;
box.setCard(topCard.getCard());
this.computerCards.Add(box);
topCard.Visible = false;
top = 0;
}
break;
}
}
for (int i = myCards.Count; i < 6; i++)
{
CardBox box = new CardBox();
box.Tag = i + 1;
box.cardBoxClicked += (s, e) =>
{
playGame((int)box.Tag);
};
Card deckDard = deck.GetRandomCard();
if (deckDard != null)
{
box.setCard(deckDard);
box.flipCard();
this.myCards.Add(box);
}
else
{
if (top == 1)
{
//box = topCard;
box.setCard(topCard.getCard());
box.flipCard();
this.myCards.Add(box);
topCard.Visible = false;
top = 0;
}
break;
}
}
arrangeComputerCards();
arrangeMyCards();
setLabelTexts();
}
private void takeCardsFromTable(List<CardBox> cards)
{
StackTrace stackTrace = new StackTrace();
log(stackTrace.GetFrame(0).GetMethod().Name);
int loopTill = cards.Count + tableCards.Count;
int j = 0;
for (int i = cards.Count - 1; i < loopTill - 1; i++)
{
CardBox box = tableCards.ElementAt<CardBox>(j);
CardBox newCard = new CardBox();
Card card = box.getCard();
newCard.setCard(box.getCard());
if (nowPlaying == Durak.ME)
{
}
else
{
//PopUp("Card Flipped");
newCard.flipCard();
newCard.Tag = i + 1;
newCard.cardBoxClicked += (s, e) =>
{
playGame((int)newCard.Tag);
};
}
cards.Add(newCard);
j++;
}
arrangeComputerCards();
arrangeMyCards();
}
public void log(String logMessage)
{
using (FileStream aFile = new FileStream(logFileName, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(aFile))
{
sw.Write("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
sw.Write(" : ");
sw.WriteLine(logMessage);
}
}
public void clearLogFile()
{
System.IO.File.WriteAllText(logFileName, string.Empty);
}
private void writeWinner(String winnerName)
{
using (FileStream aFile = new FileStream("stat.txt", FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(aFile))
{
sw.WriteLine(winnerName);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FreezeDurationBufferPowerup : BufferPowerup
{
// Start is called before the first frame update
void Start()
{
powerup = SaveLoad.playerProgress.freeze;
level = SaveLoad.playerProgress.freeze.durationLevel;
price = SaveLoad.playerProgress.freeze.durationPrice;
}
}
|
using System.Text.Json.Serialization;
namespace OrderService.Models
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Currency
{
Ru = 1,
Eu = 2,
Usd = 3
}
} |
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace Bb.Expressions.Statements
{
public class ConditionalStatement : Statement
{
public ConditionalStatement()
{
}
public Expression ConditionalExpression { get; set; }
public SourceCode Then
{
get
{
if (_then == null)
Then = new SourceCode();
return _then;
}
set
{
_then = value;
if (this.ParentIsNull)
_then.SetParent(this.GetParent());
}
}
public SourceCode Else
{
get
{
if (_else == null)
Else = new SourceCode();
return _else;
}
set
{
if (this.ParentIsNull)
_else.SetParent(this.GetParent());
_else = value;
}
}
public override Expression GetExpression(HashSet<string> variableParent)
{
Expression b1 = Then.GetExpression(new HashSet<string>(variableParent));
Expression b2 = null;
if (_else != null)
b2 = Else.GetExpression(new HashSet<string>(variableParent));
Expression expression = b2 == null
? Expression.IfThen(ConditionalExpression, b1)
: Expression.IfThenElse(ConditionalExpression, b1, b2)
;
if (expression.CanReduce)
expression = expression.Reduce();
return expression;
}
internal override void SetParent(SourceCode sourceCodes)
{
_then.SetParent(sourceCodes);
if (_else != null)
_else.SetParent(sourceCodes);
}
private SourceCode _then;
private SourceCode _else;
}
}
|
using System.Collections.Generic.V40;
namespace System.Collections.Immutable
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Validation;
[DebuggerDisplay("Count = {Count}"), DebuggerTypeProxy(typeof(ImmutableList<>.DebuggerProxy))]
public sealed class ImmutableList<T> : IImmutableList<T>, IList<T>, ICollection<T>, IList, ICollection, IOrderedCollection<T>, IImmutableListQueries<T>, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
public static readonly ImmutableList<T> Empty;
private readonly Node root;
static ImmutableList()
{
ImmutableList<T>.Empty = new ImmutableList<T>();
}
internal ImmutableList()
{
this.root = Node.EmptyNode;
}
private ImmutableList(Node root)
{
Requires.NotNull<Node>(root, "root");
root.Freeze();
this.root = root;
}
public ImmutableList<T> Add(T value)
{
Node root = this.root.Add(value);
return this.Wrap(root);
}
public ImmutableList<T> AddRange(IEnumerable<T> items)
{
Requires.NotNull<IEnumerable<T>>(items, "items");
if (this.IsEmpty)
{
return this.FillFromEmpty(items);
}
Node root = this.root;
foreach (T local in items)
{
root = root.Add(local);
}
return this.Wrap(root);
}
public int BinarySearch(T item)
{
return this.BinarySearch(item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
return this.BinarySearch(0, this.Count, item, comparer);
}
public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
{
return this.root.BinarySearch(index, count, item, comparer);
}
public ImmutableList<T> Clear()
{
return ImmutableList<T>.Empty;
}
public bool Contains(T value)
{
return (this.IndexOf(value) >= 0);
}
public ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter)
{
Requires.NotNull<Func<T, TOutput>>(converter, "converter");
return ImmutableList<TOutput>.WrapNode(this.root.ConvertAll<TOutput>(converter));
}
public void CopyTo(T[] array)
{
Requires.NotNull<T[]>(array, "array");
Requires.Range(array.Length >= this.Count, "array", null);
this.root.CopyTo(array);
}
public void CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull<T[]>(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range(array.Length >= (arrayIndex + this.Count), "arrayIndex", null);
this.root.CopyTo(array, arrayIndex);
}
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
this.root.CopyTo(index, array, arrayIndex, count);
}
public bool Exists(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.Exists(match);
}
private ImmutableList<T> FillFromEmpty(IEnumerable<T> items)
{
ImmutableList<T> listV40;
if (ImmutableList<T>.TryCastToImmutableList(items, out listV40))
{
return listV40;
}
IOrderedCollection<T> ordereds = items.AsOrderedCollection<T>();
if (ordereds.Count == 0)
{
return (ImmutableList<T>) this;
}
return new ImmutableList<T>(Node.NodeTreeFromList(ordereds, 0, ordereds.Count));
}
public T Find(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.Find(match);
}
public ImmutableList<T> FindAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindAll(match);
}
public int FindIndex(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindIndex(match);
}
public int FindIndex(int startIndex, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(startIndex <= this.Count, "startIndex", null);
return this.root.FindIndex(startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((startIndex + count) <= this.Count, "count", null);
return this.root.FindIndex(startIndex, count, match);
}
public T FindLast(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindLast(match);
}
public int FindLastIndex(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindLastIndex(match);
}
public int FindLastIndex(int startIndex, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range((startIndex == 0) || (startIndex < this.Count), "startIndex", null);
return this.root.FindLastIndex(startIndex, match);
}
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(count <= this.Count, "count", null);
Requires.Range(((startIndex - count) + 1) >= 0, "startIndex", null);
return this.root.FindLastIndex(startIndex, count, match);
}
public void ForEach(Action<T> action)
{
Requires.NotNull<Action<T>>(action, "action");
foreach (T local in this)
{
action(local);
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(this.root, null, -1, -1, false);
}
public ImmutableList<T> GetRange(int index, int count)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
return this.Wrap(Node.NodeTreeFromList(this, index, count));
}
public int IndexOf(T value)
{
return this.IndexOf<T>(value, ((IEqualityComparer<T>) EqualityComparer<T>.Default));
}
public int IndexOf(T item, int index, int count, IEqualityComparer<T> equalityComparer)
{
return this.root.IndexOf(item, index, count, equalityComparer);
}
public ImmutableList<T> Insert(int index, T item)
{
Requires.Range((index >= 0) && (index <= this.Count), "index", null);
return this.Wrap(this.root.Insert(index, item));
}
public ImmutableList<T> InsertRange(int index, IEnumerable<T> items)
{
Requires.Range((index >= 0) && (index <= this.Count), "index", null);
Requires.NotNull<IEnumerable<T>>(items, "items");
Node root = this.root;
foreach (T local in items)
{
root = root.Insert(index++, local);
}
return this.Wrap(root);
}
public int LastIndexOf(T item, int index, int count, IEqualityComparer<T> equalityComparer)
{
return this.root.LastIndexOf(item, index, count, equalityComparer);
}
public ImmutableList<T> Remove(T value)
{
return this.Remove(value, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public ImmutableList<T> Remove(T value, IEqualityComparer<T> equalityComparer)
{
int index = this.IndexOf<T>(value, equalityComparer);
if (index >= 0)
{
return this.RemoveAt(index);
}
return (ImmutableList<T>) this;
}
public ImmutableList<T> RemoveAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.Wrap(this.root.RemoveAll(match));
}
public ImmutableList<T> RemoveAt(int index)
{
Requires.Range((index >= 0) && (index < this.Count), "index", null);
Node root = this.root.RemoveAt(index);
return this.Wrap(root);
}
public ImmutableList<T> RemoveRange(IEnumerable<T> items)
{
return this.RemoveRange(items, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public ImmutableList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull<IEnumerable<T>>(items, "items");
Requires.NotNull<IEqualityComparer<T>>(equalityComparer, "equalityComparer");
if (this.IsEmpty)
{
return (ImmutableList<T>) this;
}
Node root = this.root;
foreach (T local in items)
{
int index = root.IndexOf(local, equalityComparer);
if (index >= 0)
{
root = root.RemoveAt(index);
}
}
return this.Wrap(root);
}
public ImmutableList<T> RemoveRange(int index, int count)
{
Requires.Range((index >= 0) && ((index < this.Count) || ((index == this.Count) && (count == 0))), "index", null);
Requires.Range((count >= 0) && ((index + count) <= this.Count), "count", null);
Node root = this.root;
int num = count;
while (num-- > 0)
{
root = root.RemoveAt(index);
}
return this.Wrap(root);
}
public ImmutableList<T> Replace(T oldValue, T newValue)
{
return this.Replace(oldValue, newValue, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public ImmutableList<T> Replace(T oldValue, T newValue, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull<IEqualityComparer<T>>(equalityComparer, "equalityComparer");
int index = this.IndexOf<T>(oldValue, equalityComparer);
if (index < 0)
{
throw new ArgumentException(Strings.CannotFindOldValue, "oldValue");
}
return this.SetItem(index, newValue);
}
public ImmutableList<T> Reverse()
{
return this.Wrap(this.root.Reverse());
}
public ImmutableList<T> Reverse(int index, int count)
{
return this.Wrap(this.root.Reverse(index, count));
}
public ImmutableList<T> SetItem(int index, T value)
{
return this.Wrap(this.root.ReplaceAt(index, value));
}
public ImmutableList<T> Sort()
{
return this.Wrap(this.root.Sort());
}
public ImmutableList<T> Sort(IComparer<T> comparer)
{
Requires.NotNull<IComparer<T>>(comparer, "comparer");
return this.Wrap(this.root.Sort(comparer));
}
public ImmutableList<T> Sort(Comparison<T> comparison)
{
Requires.NotNull<Comparison<T>>(comparison, "comparison");
return this.Wrap(this.root.Sort(comparison));
}
public ImmutableList<T> Sort(int index, int count, IComparer<T> comparer)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
Requires.NotNull<IComparer<T>>(comparer, "comparer");
return this.Wrap(this.root.Sort(index, count, comparer));
}
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
this.root.CopyTo(array, arrayIndex);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
int IList.Add(object value)
{
throw new NotSupportedException();
}
void IList.Clear()
{
throw new NotSupportedException();
}
bool IList.Contains(object value)
{
return this.Contains((T) value);
}
int IList.IndexOf(object value)
{
return this.IndexOf((T) value);
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
IImmutableList<T> IImmutableList<T>.Add(T value)
{
return this.Add(value);
}
IImmutableList<T> IImmutableList<T>.AddRange(IEnumerable<T> items)
{
return this.AddRange(items);
}
IImmutableList<T> IImmutableList<T>.Clear()
{
return this.Clear();
}
IImmutableList<T> IImmutableList<T>.Insert(int index, T item)
{
return this.Insert(index, item);
}
IImmutableList<T> IImmutableList<T>.InsertRange(int index, IEnumerable<T> items)
{
return this.InsertRange(index, items);
}
IImmutableList<T> IImmutableList<T>.Remove(T value, IEqualityComparer<T> equalityComparer)
{
return this.Remove(value, equalityComparer);
}
IImmutableList<T> IImmutableList<T>.RemoveAll(Predicate<T> match)
{
return this.RemoveAll(match);
}
IImmutableList<T> IImmutableList<T>.RemoveAt(int index)
{
return this.RemoveAt(index);
}
IImmutableList<T> IImmutableList<T>.RemoveRange(IEnumerable<T> items, IEqualityComparer<T> equalityComparer)
{
return this.RemoveRange(items, equalityComparer);
}
IImmutableList<T> IImmutableList<T>.RemoveRange(int index, int count)
{
return this.RemoveRange(index, count);
}
IImmutableList<T> IImmutableList<T>.Replace(T oldValue, T newValue, IEqualityComparer<T> equalityComparer)
{
return this.Replace(oldValue, newValue, equalityComparer);
}
IImmutableList<T> IImmutableList<T>.SetItem(int index, T value)
{
return this.SetItem(index, value);
}
public Builder ToBuilder()
{
return new Builder((ImmutableList<T>) this);
}
public bool TrueForAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.TrueForAll(match);
}
private static bool TryCastToImmutableList(IEnumerable<T> sequence, out ImmutableList<T> other)
{
other = sequence as ImmutableList<T>;
if (other != null)
{
return true;
}
Builder builder = sequence as Builder;
if (builder != null)
{
other = builder.ToImmutable();
return true;
}
return false;
}
private ImmutableList<T> Wrap(Node root)
{
if (root == this.root)
{
return (ImmutableList<T>) this;
}
if (!root.IsEmpty)
{
return new ImmutableList<T>(root);
}
return this.Clear();
}
private static ImmutableList<T> WrapNode(Node root)
{
if (!root.IsEmpty)
{
return new ImmutableList<T>(root);
}
return ImmutableList<T>.Empty;
}
public int Count
{
get
{
return this.root.Count;
}
}
[DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.Never)]
public bool IsEmpty
{
get
{
return this.root.IsEmpty;
}
}
public T this[int index]
{
get
{
return this.root[index];
}
}
bool ICollection<T>.IsReadOnly
{
get
{
return true;
}
}
T IList<T>.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
[DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
return true;
}
}
[DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
bool IList.IsReadOnly
{
get
{
return true;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
T IOrderedCollection<T>.this[int index]
{
get
{
return this[index];
}
}
[DebuggerDisplay("Count = {Count}"), DebuggerTypeProxy(typeof(ImmutableList<>.DebuggerProxy))]
public sealed class Builder : IList<T>, ICollection<T>, IList, ICollection, IOrderedCollection<T>, IImmutableListQueries<T>, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
private ImmutableList<T> immutable;
private ImmutableList<T>.Node root;
private object syncRoot;
private int version;
internal Builder(ImmutableList<T> listV40)
{
this.root = ImmutableList<T>.Node.EmptyNode;
Requires.NotNull<ImmutableList<T>>(listV40, "listV40");
this.root = listV40.root;
this.immutable = listV40;
}
public void Add(T item)
{
this.Root = this.Root.Add(item);
}
public int BinarySearch(T item)
{
return this.BinarySearch(item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
return this.BinarySearch(0, this.Count, item, comparer);
}
public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
{
return this.Root.BinarySearch(index, count, item, comparer);
}
public void Clear()
{
this.Root = ImmutableList<T>.Node.EmptyNode;
}
public bool Contains(T item)
{
return (this.IndexOf(item) >= 0);
}
public ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter)
{
Requires.NotNull<Func<T, TOutput>>(converter, "converter");
return ImmutableList<TOutput>.WrapNode(this.root.ConvertAll<TOutput>(converter));
}
public void CopyTo(T[] array)
{
Requires.NotNull<T[]>(array, "array");
Requires.Range(array.Length >= this.Count, "array", null);
this.root.CopyTo(array);
}
public void CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull<T[]>(array, "array");
Requires.Range(array.Length >= (arrayIndex + this.Count), "arrayIndex", null);
this.root.CopyTo(array, arrayIndex);
}
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
this.root.CopyTo(index, array, arrayIndex, count);
}
public bool Exists(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.Exists(match);
}
public T Find(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.Find(match);
}
public ImmutableList<T> FindAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindAll(match);
}
public int FindIndex(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindIndex(match);
}
public int FindIndex(int startIndex, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(startIndex <= this.Count, "startIndex", null);
return this.root.FindIndex(startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((startIndex + count) <= this.Count, "count", null);
return this.root.FindIndex(startIndex, count, match);
}
public T FindLast(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindLast(match);
}
public int FindLastIndex(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.FindLastIndex(match);
}
public int FindLastIndex(int startIndex, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range((startIndex == 0) || (startIndex < this.Count), "startIndex", null);
return this.root.FindLastIndex(startIndex, match);
}
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(count <= this.Count, "count", null);
Requires.Range(((startIndex - count) + 1) >= 0, "startIndex", null);
return this.root.FindLastIndex(startIndex, count, match);
}
public void ForEach(Action<T> action)
{
Requires.NotNull<Action<T>>(action, "action");
foreach (T local in this)
{
action(local);
}
}
public ImmutableList<T>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator((ImmutableList<T>.Builder) this);
}
public ImmutableList<T> GetRange(int index, int count)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
return ImmutableList<T>.WrapNode(ImmutableList<T>.Node.NodeTreeFromList(this, index, count));
}
public int IndexOf(T item)
{
return this.Root.IndexOf(item, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public int IndexOf(T item, int index)
{
return this.root.IndexOf(item, index, this.Count - index, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public int IndexOf(T item, int index, int count)
{
return this.root.IndexOf(item, index, count, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public int IndexOf(T item, int index, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull<IEqualityComparer<T>>(equalityComparer, "equalityComparer");
return this.root.IndexOf(item, index, count, equalityComparer);
}
public void Insert(int index, T item)
{
this.Root = this.Root.Insert(index, item);
}
public void InsertRange(int index, IEnumerable<T> items)
{
Requires.Range((index >= 0) && (index <= this.Count), "index", null);
Requires.NotNull<IEnumerable<T>>(items, "items");
foreach (T local in items)
{
this.Root = this.Root.Insert(index++, local);
}
}
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.root.LastIndexOf(item, this.Count - 1, this.Count, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public int LastIndexOf(T item, int startIndex)
{
if ((this.Count == 0) && (startIndex == 0))
{
return -1;
}
return this.root.LastIndexOf(item, startIndex, startIndex + 1, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public int LastIndexOf(T item, int startIndex, int count)
{
return this.root.LastIndexOf(item, startIndex, count, (IEqualityComparer<T>) EqualityComparer<T>.Default);
}
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
return this.root.LastIndexOf(item, startIndex, count, equalityComparer);
}
public bool Remove(T item)
{
int index = this.IndexOf(item);
if (index < 0)
{
return false;
}
this.Root = this.Root.RemoveAt(index);
return true;
}
public int RemoveAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
int count = this.Count;
this.Root = this.Root.RemoveAll(match);
return (count - this.Count);
}
public void RemoveAt(int index)
{
this.Root = this.Root.RemoveAt(index);
}
public void Reverse()
{
this.Reverse(0, this.Count);
}
public void Reverse(int index, int count)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
this.Root = this.Root.Reverse(index, count);
}
public void Sort()
{
this.Root = this.Root.Sort();
}
public void Sort(IComparer<T> comparer)
{
Requires.NotNull<IComparer<T>>(comparer, "comparer");
this.Root = this.Root.Sort(comparer);
}
public void Sort(Comparison<T> comparison)
{
Requires.NotNull<Comparison<T>>(comparison, "comparison");
this.Root = this.Root.Sort(comparison);
}
public void Sort(int index, int count, IComparer<T> comparer)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
Requires.NotNull<IComparer<T>>(comparer, "comparer");
this.Root = this.Root.Sort(index, count, comparer);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
int IList.Add(object value)
{
this.Add((T) value);
return (this.Count - 1);
}
void IList.Clear()
{
this.Clear();
}
bool IList.Contains(object value)
{
return this.Contains((T) value);
}
int IList.IndexOf(object value)
{
return this.IndexOf((T) value);
}
void IList.Insert(int index, object value)
{
this.Insert(index, (T) value);
}
void IList.Remove(object value)
{
this.Remove((T) value);
}
public ImmutableList<T> ToImmutable()
{
if (this.immutable == null)
{
this.immutable = ImmutableList<T>.WrapNode(this.Root);
}
return this.immutable;
}
public bool TrueForAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.root.TrueForAll(match);
}
public int Count
{
get
{
return this.Root.Count;
}
}
public T this[int index]
{
get
{
return this.Root[index];
}
set
{
this.Root = this.Root.ReplaceAt(index, value);
}
}
internal ImmutableList<T>.Node Root
{
get
{
return this.root;
}
private set
{
this.version++;
if (this.root != value)
{
this.root = value;
this.immutable = null;
}
}
}
bool ICollection<T>.IsReadOnly
{
get
{
return false;
}
}
[DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
[DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (this.syncRoot == null)
{
Interlocked.CompareExchange<object>(ref this.syncRoot, new object(), null);
}
return this.syncRoot;
}
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
bool IList.IsReadOnly
{
get
{
return false;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (T) value;
}
}
T IOrderedCollection<T>.this[int index]
{
get
{
return this[index];
}
}
internal int Version
{
get
{
return this.version;
}
}
}
private class DebuggerProxy
{
private T[] cachedContents;
private readonly ImmutableList<T>.Node list;
public DebuggerProxy(ImmutableList<T> listV40)
{
Requires.NotNull<ImmutableList<T>>(listV40, "listV40");
this.list = listV40.root;
}
public DebuggerProxy(ImmutableList<T>.Builder builder)
{
Requires.NotNull<ImmutableList<T>.Builder>(builder, "builder");
this.list = builder.Root;
}
[DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.RootHidden)]
public T[] Contents
{
get
{
if (this.cachedContents == null)
{
this.cachedContents = this.list.ToArray<T>(this.list.Count);
}
return this.cachedContents;
}
}
}
[StructLayout(LayoutKind.Sequential), EditorBrowsable((EditorBrowsableState) EditorBrowsableState.Advanced)]
public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable, ISecurePooledObjectUser
{
private static readonly SecureObjectPool<Stack<RefAsValueType<IBinaryTree<T>>>, ImmutableList<T>.Enumerator> EnumeratingStacks;
private readonly ImmutableList<T>.Builder builder;
private readonly Guid poolUserId;
private readonly int startIndex;
private readonly int count;
private int remainingCount;
private bool reversed;
private IBinaryTree<T> root;
private SecurePooledObject<Stack<RefAsValueType<IBinaryTree<T>>>> stack;
private IBinaryTree<T> current;
private int enumeratingBuilderVersion;
internal Enumerator(IBinaryTree<T> root, ImmutableList<T>.Builder builder = null, Int32 startIndex = -1, Int32 count = -1, Boolean reversed = false)
{
Int32 num;
Requires.NotNull<IBinaryTree<T>>(root, "root");
Requires.Range(startIndex >= -1, "startIndex", null);
Requires.Range(count >= -1, "count", null);
Requires.Argument((reversed || count == -1 ? true : (startIndex == -1 ? 0 : startIndex) + count <= root.Count));
Requires.Argument((!reversed || count == -1 ? true : (startIndex == -1 ? root.Count - 1 : startIndex) - count + 1 >= 0));
this.root = root;
this.builder = builder;
this.current = null;
if (startIndex >= 0)
{
num = startIndex;
}
else
{
num = (reversed ? root.Count - 1 : 0);
}
this.startIndex = num;
this.count = (count == -1 ? root.Count : count);
this.remainingCount = this.count;
this.reversed = reversed;
this.enumeratingBuilderVersion = (builder != null ? builder.Version : -1);
this.poolUserId = Guid.NewGuid();
if (this.count <= 0)
{
this.stack = null;
}
else
{
this.stack = null;
if (!ImmutableList<T>.Enumerator.EnumeratingStacks.TryTake(this, out this.stack))
{
this.stack = ImmutableList<T>.Enumerator.EnumeratingStacks.PrepNew(this, new Stack<RefAsValueType<IBinaryTree<T>>>(root.Height));
}
}
this.Reset();
}
Guid ISecurePooledObjectUser.PoolUserId
{
get
{
return this.poolUserId;
}
}
public T Current
{
get
{
this.ThrowIfDisposed();
if (this.current == null)
{
throw new InvalidOperationException();
}
return this.current.Value;
}
}
object IEnumerator.Current
{
get
{
return this.Current;
}
}
public void Dispose()
{
this.root = null;
this.current = null;
if (this.stack != null && this.stack.Owner == this.poolUserId)
{
SecurePooledObject<Stack<RefAsValueType<IBinaryTree<T>>>>.SecurePooledObjectUser securePooledObjectUser = this.stack.Use<ImmutableList<T>.Enumerator>(this);
try
{
securePooledObjectUser.Value.Clear();
}
finally
{
((IDisposable)securePooledObjectUser).Dispose();
}
ImmutableList<T>.Enumerator.EnumeratingStacks.TryAdd(this, this.stack);
}
this.stack = null;
}
public Boolean MoveNext()
{
Boolean flag;
this.ThrowIfDisposed();
this.ThrowIfChanged();
if (this.stack != null)
{
SecurePooledObject<Stack<RefAsValueType<IBinaryTree<T>>>>.SecurePooledObjectUser securePooledObjectUser = this.stack.Use<ImmutableList<T>.Enumerator>(this);
try
{
if (this.remainingCount <= 0 || securePooledObjectUser.Value.Count <= 0)
{
this.current = null;
return false;
}
else
{
IBinaryTree<T> value = securePooledObjectUser.Value.Pop().Value;
this.current = value;
this.PushNext(this.NextBranch(value));
ImmutableList<T>.Enumerator enumerator = this;
enumerator.remainingCount = enumerator.remainingCount - 1;
flag = true;
}
}
finally
{
((IDisposable)securePooledObjectUser).Dispose();
}
return flag;
}
this.current = null;
return false;
}
public void Reset()
{
this.ThrowIfDisposed();
this.enumeratingBuilderVersion = (this.builder != null ? this.builder.Version : -1);
this.remainingCount = this.count;
if (this.stack != null)
{
SecurePooledObject<Stack<RefAsValueType<IBinaryTree<T>>>>.SecurePooledObjectUser securePooledObjectUser = this.stack.Use<ImmutableList<T>.Enumerator>(this);
try
{
securePooledObjectUser.Value.Clear();
IBinaryTree<T> binaryTree = this.root;
Int32 count = (this.reversed ? this.root.Count - this.startIndex - 1 : this.startIndex);
while (!binaryTree.IsEmpty && count != this.PreviousBranch(binaryTree).Count)
{
if (count >= this.PreviousBranch(binaryTree).Count)
{
count = count - (this.PreviousBranch(binaryTree).Count + 1);
binaryTree = this.NextBranch(binaryTree);
}
else
{
securePooledObjectUser.Value.Push(new RefAsValueType<IBinaryTree<T>>(binaryTree));
binaryTree = this.PreviousBranch(binaryTree);
}
}
if (!binaryTree.IsEmpty)
{
securePooledObjectUser.Value.Push(new RefAsValueType<IBinaryTree<T>>(binaryTree));
}
}
finally
{
((IDisposable)securePooledObjectUser).Dispose();
}
}
}
private IBinaryTree<T> NextBranch(IBinaryTree<T> node)
{
if (!this.reversed)
{
return node.Right;
}
return node.Left;
}
private IBinaryTree<T> PreviousBranch(IBinaryTree<T> node)
{
if (!this.reversed)
{
return node.Left;
}
return node.Right;
}
private void ThrowIfDisposed()
{
if (this.root == null)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (this.stack != null)
{
this.stack.ThrowDisposedIfNotOwned<ImmutableList<T>.Enumerator>(this);
}
}
private void ThrowIfChanged()
{
if ((this.builder != null) && (this.builder.Version != this.enumeratingBuilderVersion))
{
throw new InvalidOperationException(Strings.CollectionModifiedDuringEnumeration);
}
}
private void PushNext(IBinaryTree<T> node)
{
Requires.NotNull<IBinaryTree<T>>(node, "node");
if (!node.IsEmpty)
{
SecurePooledObject<Stack<RefAsValueType<IBinaryTree<T>>>>.SecurePooledObjectUser securePooledObjectUser = this.stack.Use<ImmutableList<T>.Enumerator>(this);
try
{
while (!node.IsEmpty)
{
securePooledObjectUser.Value.Push(new RefAsValueType<IBinaryTree<T>>(node));
node = this.PreviousBranch(node);
}
}
finally
{
((IDisposable)securePooledObjectUser).Dispose();
}
}
}
static Enumerator()
{
ImmutableList<T>.Enumerator.EnumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<IBinaryTree<T>>>, ImmutableList<T>.Enumerator>();
}
}
[DebuggerDisplay("{key}")]
internal sealed class Node : IBinaryTree<T>, IEnumerable<T>, IEnumerable
{
private int count;
internal static readonly ImmutableList<T>.Node EmptyNode;
private bool frozen;
private int height;
private T key;
private ImmutableList<T>.Node left;
private ImmutableList<T>.Node right;
static Node()
{
ImmutableList<T>.Node.EmptyNode = new ImmutableList<T>.Node();
}
private Node()
{
this.frozen = true;
}
private Node(T key, ImmutableList<T>.Node left, ImmutableList<T>.Node right, bool frozen = false)
{
Requires.NotNull<ImmutableList<T>.Node>(left, "left");
Requires.NotNull<ImmutableList<T>.Node>(right, "right");
this.key = key;
this.left = left;
this.right = right;
this.height = 1 + Math.Max(left.height, right.height);
this.count = (1 + left.count) + right.count;
this.frozen = frozen;
}
internal ImmutableList<T>.Node Add(T key)
{
return this.Insert(this.count, key);
}
private static int Balance(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
return (tree.right.height - tree.left.height);
}
internal int BinarySearch(int index, int count, T item, IComparer<T> comparer)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
comparer = (IComparer<T>) (comparer ?? Comparer<T>.Default);
if (this.IsEmpty || (count <= 0))
{
return ~index;
}
int num = this.left.Count;
if ((index + count) > num)
{
if (index > num)
{
int num2 = this.right.BinarySearch((index - num) - 1, count, item, comparer);
int num3 = num + 1;
if (num2 >= 0)
{
return (num2 + num3);
}
return (num2 - num3);
}
int num4 = comparer.Compare(item, this.key);
if (num4 == 0)
{
return num;
}
if (num4 > 0)
{
int num5 = (count - (num - index)) - 1;
int num6 = (num5 < 0) ? -1 : this.right.BinarySearch(0, num5, item, comparer);
int num7 = num + 1;
if (num6 >= 0)
{
return (num6 + num7);
}
return (num6 - num7);
}
if (index == num)
{
return ~index;
}
}
return this.left.BinarySearch(index, count, item, comparer);
}
internal ImmutableList<TOutput>.Node ConvertAll<TOutput>(Func<T, TOutput> converter)
{
ImmutableList<TOutput>.Node emptyNode = ImmutableList<TOutput>.Node.EmptyNode;
foreach (T local in this)
{
emptyNode = emptyNode.Add(converter(local));
}
return emptyNode;
}
internal void CopyTo(T[] array)
{
Requires.NotNull<T[]>(array, "array");
Requires.Argument(array.Length >= this.Count);
int num = 0;
foreach (T local in this)
{
array[num++] = local;
}
}
internal void CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull<T[]>(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range(arrayIndex <= array.Length, "arrayIndex", null);
Requires.Argument((arrayIndex + this.Count) <= array.Length);
foreach (T local in this)
{
array[arrayIndex++] = local;
}
}
internal void CopyTo(Array array, int arrayIndex)
{
Requires.NotNull<Array>(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range(array.Length >= (arrayIndex + this.Count), "arrayIndex", null);
foreach (T local in this)
{
array.SetValue(local, new int[] { arrayIndex++ });
}
}
internal void CopyTo(int index, T[] array, int arrayIndex, int count)
{
Requires.NotNull<T[]>(array, "array");
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range((arrayIndex + count) <= array.Length, "arrayIndex", null);
using (ImmutableList<T>.Enumerator enumerator = new ImmutableList<T>.Enumerator(this, null, index, count, false))
{
while (enumerator.MoveNext())
{
array[arrayIndex++] = enumerator.Current;
}
}
}
private static ImmutableList<T>.Node DoubleLeft(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
if (tree.right.IsEmpty)
{
return tree;
}
return ImmutableList<T>.Node.RotateLeft(tree.Mutate(null, ImmutableList<T>.Node.RotateRight(tree.right)));
}
private static ImmutableList<T>.Node DoubleRight(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
if (tree.left.IsEmpty)
{
return tree;
}
return ImmutableList<T>.Node.RotateRight(tree.Mutate(ImmutableList<T>.Node.RotateLeft(tree.left), null));
}
internal bool Exists(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
foreach (T local in this)
{
if (match(local))
{
return true;
}
}
return false;
}
internal T Find(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
foreach (T local in this)
{
if (match(local))
{
return local;
}
}
return default(T);
}
internal ImmutableList<T> FindAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
ImmutableList<T>.Builder builder = ImmutableList<T>.Empty.ToBuilder();
foreach (T local in this)
{
if (match(local))
{
builder.Add(local);
}
}
return builder.ToImmutable();
}
internal int FindIndex(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
return this.FindIndex(0, this.count, match);
}
internal int FindIndex(int startIndex, Predicate<T> match)
{
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(startIndex <= this.Count, "startIndex", null);
Requires.NotNull<Predicate<T>>(match, "match");
return this.FindIndex(startIndex, this.Count - startIndex, match);
}
internal int FindIndex(int startIndex, int count, Predicate<T> match)
{
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(count >= 0, "count", null);
Requires.Argument((startIndex + count) <= this.Count);
Requires.NotNull<Predicate<T>>(match, "match");
using (ImmutableList<T>.Enumerator enumerator = new ImmutableList<T>.Enumerator(this, null, startIndex, count, false))
{
for (int i = startIndex; enumerator.MoveNext(); i++)
{
if (match(enumerator.Current))
{
return i;
}
}
}
return -1;
}
internal T FindLast(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
using (ImmutableList<T>.Enumerator enumerator = new ImmutableList<T>.Enumerator(this, null, -1, -1, true))
{
while (enumerator.MoveNext())
{
if (match(enumerator.Current))
{
return enumerator.Current;
}
}
}
return default(T);
}
internal int FindLastIndex(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
if (this.IsEmpty)
{
return -1;
}
return this.FindLastIndex(this.Count - 1, this.Count, match);
}
internal int FindLastIndex(int startIndex, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range((startIndex == 0) || (startIndex < this.Count), "startIndex", null);
if (this.IsEmpty)
{
return -1;
}
return this.FindLastIndex(startIndex, startIndex + 1, match);
}
internal int FindLastIndex(int startIndex, int count, Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
Requires.Range(startIndex >= 0, "startIndex", null);
Requires.Range(count <= this.Count, "count", null);
Requires.Argument(((startIndex - count) + 1) >= 0);
using (ImmutableList<T>.Enumerator enumerator = new ImmutableList<T>.Enumerator(this, null, startIndex, count, true))
{
for (int i = startIndex; enumerator.MoveNext(); i--)
{
if (match(enumerator.Current))
{
return i;
}
}
}
return -1;
}
internal void Freeze()
{
if (!this.frozen)
{
this.left.Freeze();
this.right.Freeze();
this.frozen = true;
}
}
public ImmutableList<T>.Enumerator GetEnumerator()
{
return new ImmutableList<T>.Enumerator(this, null, -1, -1, false);
}
internal ImmutableList<T>.Enumerator GetEnumerator(ImmutableList<T>.Builder builder)
{
return new ImmutableList<T>.Enumerator(this, builder, -1, -1, false);
}
internal int IndexOf(T item, IEqualityComparer<T> equalityComparer)
{
return this.IndexOf(item, 0, this.Count, equalityComparer);
}
internal int IndexOf(T item, int index, int count, IEqualityComparer<T> equalityComparer)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range(count <= this.Count, "count", null);
Requires.Range((index + count) <= this.Count, "count", null);
Requires.NotNull<IEqualityComparer<T>>(equalityComparer, "equalityComparer");
using (ImmutableList<T>.Enumerator enumerator = new ImmutableList<T>.Enumerator(this, null, index, count, false))
{
while (enumerator.MoveNext())
{
if (equalityComparer.Equals(item, enumerator.Current))
{
return index;
}
index++;
}
}
return -1;
}
internal ImmutableList<T>.Node Insert(int index, T key)
{
ImmutableList<T>.Node node;
Requires.Range((index >= 0) && (index <= this.Count), "index", null);
if (this.IsEmpty)
{
return new ImmutableList<T>.Node(key, (ImmutableList<T>.Node) this, (ImmutableList<T>.Node) this, false);
}
if (index <= this.left.count)
{
ImmutableList<T>.Node left = this.left.Insert(index, key);
node = this.Mutate(left, null);
}
else
{
ImmutableList<T>.Node right = this.right.Insert((index - this.left.count) - 1, key);
node = this.Mutate(null, right);
}
return ImmutableList<T>.Node.MakeBalanced(node);
}
private static bool IsLeftHeavy(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
return (ImmutableList<T>.Node.Balance(tree) <= -2);
}
private static bool IsRightHeavy(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
return (ImmutableList<T>.Node.Balance(tree) >= 2);
}
internal int LastIndexOf(T item, int index, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull<IEqualityComparer<T>>(equalityComparer, "ValueComparer");
Requires.Range(index >= 0, "index", null);
Requires.Range((count >= 0) && (count <= this.Count), "count", null);
Requires.Argument(((index - count) + 1) >= 0);
using (ImmutableList<T>.Enumerator enumerator = new ImmutableList<T>.Enumerator(this, null, index, count, true))
{
while (enumerator.MoveNext())
{
if (equalityComparer.Equals(item, enumerator.Current))
{
return index;
}
index--;
}
}
return -1;
}
private static ImmutableList<T>.Node MakeBalanced(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
if (ImmutableList<T>.Node.IsRightHeavy(tree))
{
if (!ImmutableList<T>.Node.IsLeftHeavy(tree.right))
{
return ImmutableList<T>.Node.RotateLeft(tree);
}
return ImmutableList<T>.Node.DoubleLeft(tree);
}
if (!ImmutableList<T>.Node.IsLeftHeavy(tree))
{
return tree;
}
if (!ImmutableList<T>.Node.IsRightHeavy(tree.left))
{
return ImmutableList<T>.Node.RotateRight(tree);
}
return ImmutableList<T>.Node.DoubleRight(tree);
}
private ImmutableList<T>.Node Mutate(T value)
{
if (this.frozen)
{
return new ImmutableList<T>.Node(value, this.left, this.right, false);
}
this.key = value;
return (ImmutableList<T>.Node) this;
}
private ImmutableList<T>.Node Mutate(ImmutableList<T>.Node left = null, ImmutableList<T>.Node right = null)
{
if (this.frozen)
{
return new ImmutableList<T>.Node(this.key, left ?? this.left, right ?? this.right, false);
}
if (left != null)
{
this.left = left;
}
if (right != null)
{
this.right = right;
}
this.height = 1 + Math.Max(this.left.height, this.right.height);
this.count = (1 + this.left.count) + this.right.count;
return (ImmutableList<T>.Node) this;
}
internal static ImmutableList<T>.Node NodeTreeFromList(IOrderedCollection<T> items, int start, int length)
{
Requires.NotNull<IOrderedCollection<T>>(items, "items");
Requires.Range(start >= 0, "start", null);
Requires.Range(length >= 0, "length", null);
if (length == 0)
{
return ImmutableList<T>.Node.EmptyNode;
}
int num = (length - 1) / 2;
int num2 = (length - 1) - num;
ImmutableList<T>.Node left = ImmutableList<T>.Node.NodeTreeFromList(items, start, num2);
return new ImmutableList<T>.Node(items[start + num2], left, ImmutableList<T>.Node.NodeTreeFromList(items, (start + num2) + 1, num), true);
}
internal ImmutableList<T>.Node RemoveAll(Predicate<T> match)
{
Requires.NotNull<Predicate<T>>(match, "match");
ImmutableList<T>.Node ts = this;
Int32 num = 0;
foreach (T t in this)
{
if (!match(t))
{
num++;
}
else
{
ts = ts.RemoveAt(num);
}
}
return ts;
}
internal ImmutableList<T>.Node RemoveAt(Int32 index)
{
Requires.Range((index < 0 ? false : index < this.Count), "index", null);
ImmutableList<T>.Node emptyNode = this;
if (index != this.left.count)
{
if (index >= this.left.count)
{
ImmutableList<T>.Node ts = this.right.RemoveAt(index - this.left.count - 1);
emptyNode = this.Mutate(null, ts);
}
else
{
ImmutableList<T>.Node ts1 = this.left.RemoveAt(index);
emptyNode = this.Mutate(ts1, null);
}
}
else if (this.right.IsEmpty && this.left.IsEmpty)
{
emptyNode = ImmutableList<T>.Node.EmptyNode;
}
else if (this.right.IsEmpty && !this.left.IsEmpty)
{
emptyNode = this.left;
}
else if (this.right.IsEmpty || !this.left.IsEmpty)
{
ImmutableList<T>.Node ts2 = this.right;
while (!ts2.left.IsEmpty)
{
ts2 = ts2.left;
}
ImmutableList<T>.Node ts3 = this.right.RemoveAt(0);
emptyNode = ts2.Mutate(this.left, ts3);
}
else
{
emptyNode = this.right;
}
if (emptyNode.IsEmpty)
{
return emptyNode;
}
return ImmutableList<T>.Node.MakeBalanced(emptyNode);
}
internal ImmutableList<T>.Node ReplaceAt(int index, T value)
{
Requires.Range((index >= 0) && (index < this.Count), "index", null);
if (index == this.left.count)
{
return this.Mutate(value);
}
if (index < this.left.count)
{
ImmutableList<T>.Node left = this.left.ReplaceAt(index, value);
return this.Mutate(left, null);
}
ImmutableList<T>.Node right = this.right.ReplaceAt((index - this.left.count) - 1, value);
return this.Mutate(null, right);
}
internal ImmutableList<T>.Node Reverse()
{
return this.Reverse(0, this.Count);
}
internal ImmutableList<T>.Node Reverse(Int32 index, Int32 count)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Range(index + count <= this.Count, "index", null);
ImmutableList<T>.Node ts = this;
Int32 num = index;
for (Int32 i = index + count - 1; num < i; i--)
{
T item = ts[num];
T t = ts[i];
ts = ts.ReplaceAt(i, item).ReplaceAt(num, t);
num++;
}
return ts;
}
private static ImmutableList<T>.Node RotateLeft(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
if (tree.right.IsEmpty)
{
return tree;
}
ImmutableList<T>.Node right = tree.right;
return right.Mutate(tree.Mutate(null, right.left), null);
}
private static ImmutableList<T>.Node RotateRight(ImmutableList<T>.Node tree)
{
Requires.NotNull<ImmutableList<T>.Node>(tree, "tree");
if (tree.left.IsEmpty)
{
return tree;
}
ImmutableList<T>.Node left = tree.left;
return left.Mutate(null, tree.Mutate(left.right, null));
}
internal ImmutableList<T>.Node Sort()
{
return this.Sort((IComparer<T>) Comparer<T>.Default);
}
internal ImmutableList<T>.Node Sort(IComparer<T> comparer)
{
Requires.NotNull<IComparer<T>>(comparer, "comparer");
return this.Sort(0, this.Count, comparer);
}
internal ImmutableList<T>.Node Sort(Comparison<T> comparison)
{
Requires.NotNull<Comparison<T>>(comparison, "comparison");
T[] array = new T[this.Count];
this.CopyTo(array);
Array.Sort<T>(array, comparison);
return ImmutableList<T>.Node.NodeTreeFromList(array.AsOrderedCollection<T>(), 0, this.Count);
}
internal ImmutableList<T>.Node Sort(int index, int count, IComparer<T> comparer)
{
Requires.Range(index >= 0, "index", null);
Requires.Range(count >= 0, "count", null);
Requires.Argument((index + count) <= this.Count);
Requires.NotNull<IComparer<T>>(comparer, "comparer");
T[] array = new T[this.Count];
this.CopyTo(array);
Array.Sort<T>(array, index, count, comparer);
return ImmutableList<T>.Node.NodeTreeFromList(array.AsOrderedCollection<T>(), 0, this.Count);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
internal bool TrueForAll(Predicate<T> match)
{
foreach (T local in this)
{
if (!match(local))
{
return false;
}
}
return true;
}
public int Count
{
get
{
return this.count;
}
}
public bool IsEmpty
{
get
{
return (this.left == null);
}
}
internal T this[int index]
{
get
{
Requires.Range((index >= 0) && (index < this.Count), "index", null);
if (index < this.left.count)
{
return this.left[index];
}
if (index > this.left.count)
{
return this.right[(index - this.left.count) - 1];
}
return this.key;
}
}
internal T Key
{
get
{
return this.key;
}
}
int IBinaryTree<T>.Height
{
get
{
return this.height;
}
}
IBinaryTree<T> IBinaryTree<T>.Left
{
get
{
return this.left;
}
}
IBinaryTree<T> IBinaryTree<T>.Right
{
get
{
return this.right;
}
}
T IBinaryTree<T>.Value
{
get
{
return this.key;
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerCtrlBJY : MonoBehaviour
{
[Header("UI 관련")]
[SerializeField] private GameObject m_G_ButtonPanel;
[SerializeField] private Text m_T_CommandText;
[SerializeField] private Image m_I_ButtonGage;
[Header("조사하기 커맨드 관련")]
private Component m_G_lookObject; //조사하기 실행 시 표시할 오브젝트
// ↓ 기타 조작 관련
GameObject G_Item; //아이템 태그가 붙은 오브젝트를 관리하는 변수
private bool m_b_ItemRay; //아이템에 마우스가 올라가 있는지 확인하는 변수
private bool m_b_doneLook = false; //조사하기 커맨드가 완료되었는지 확인하는 변수
public static bool m_b_canMove = true;
float h = 0f;
float v = 0f;
float r = 0f;
public float moveSpeed = 3f;
public float rotSpeed;
private Transform tr;
Animator A_animator;
private Rigidbody rb;
GameObject Item;
void Start()
{
rb = GetComponent<Rigidbody>();
A_animator = GetComponent<Animator>();
tr = GetComponent<Transform>();
}
void Update()
{
h = Input.GetAxisRaw("Horizontal");// ↕ 방향키
v = Input.GetAxisRaw("Vertical");// ↕
r = Input.GetAxisRaw("Mouse X"); //회전
Vector3 moveDir = (Vector3.forward * v) + (Vector3.right * h);
moveDir = moveDir.normalized;
if (m_b_canMove == true)
{
tr.Translate(moveDir * moveSpeed * Time.deltaTime, Space.Self);
tr.Rotate(Vector3.up * rotSpeed * Time.deltaTime * r);
}
Ani();
ItemRaycast();
}
void Ani()
{
if ((h != 0 || v !=0 ) && Input.GetKey(KeyCode.LeftShift))
{
A_animator.SetBool("isWalk", false);
A_animator.SetBool("isRun", true);
moveSpeed = 6f;
}
else if (h != 0 || v != 0)
{
A_animator.SetBool("isWalk", true);
A_animator.SetBool("isRun", false);
moveSpeed = 3f;
}
else if (Input.GetKeyDown(KeyCode.F))
{
A_animator.SetTrigger("Attack");
}
else
{
A_animator.SetBool("isWalk", false);
A_animator.SetBool("isRun", false);
}
}
void ItemRaycast()
{
RaycastHit hit = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction, out hit))
{
if (hit.transform.gameObject.CompareTag("Item"))
{
Item = hit.transform.gameObject;
Item.GetComponent<Outline>().enabled = true;
}
else
{
if (Item != null)
{
Item.GetComponent<Outline>().enabled = false;
}
return;
}
}
}
// ↓ 아이템 획득 조작 함수
void GetItem()
{
float distance = Vector3.Distance(G_Item.transform.position, transform.position);
if (m_b_ItemRay && distance <= 3f) //아이템에 마우스가 올라가 있고 아이템과 플레이어간의 거리가 3f 이내일 때
{
m_T_CommandText.text = "획득";
m_G_ButtonPanel.SetActive(true); //키 조작 안내 UI ON
if (Input.GetKey(KeyCode.E) && G_Item.CompareTag("DelayItem")) //딜레이를 가진 아이템 획득 시
{
ButtonGage(1);
}
else if (Input.GetKeyDown(KeyCode.E) && G_Item.CompareTag("Item")) //일반 아이템 획득 시
{
G_Item.SetActive(false);
}
else
{
ButtonGage(0);
}
}
else if (m_b_ItemRay && distance > 3f)
{
m_G_ButtonPanel.SetActive(false); //키 조작 안내 UI OFF
m_I_ButtonGage.fillAmount = 0; //게이지의 수치를 0으로 초기화
}
else
{
m_G_ButtonPanel.SetActive(false);
m_I_ButtonGage.fillAmount = 0;
G_Item = null;
}
}
// ↓ 딜레이 UI 게이지 조정 및 커맨드 함수들
void ButtonGage(int a)
{
float t;
if (m_I_ButtonGage.fillAmount >= 0.8)
t = Time.deltaTime * 6;
else
t = Time.deltaTime;
switch (a)
{
case 0: //버튼의 게이지를 서서히 0으로 변화(공통)
m_I_ButtonGage.fillAmount = Mathf.Lerp(m_I_ButtonGage.fillAmount, 0, t);
break;
case 1: //딜레이를 가진 아이템 획득 시
m_I_ButtonGage.fillAmount = Mathf.Lerp(m_I_ButtonGage.fillAmount, 1, t);
if (m_I_ButtonGage.fillAmount >= 0.99)
{
m_G_ButtonPanel.SetActive(false);
m_I_ButtonGage.fillAmount = 0;
G_Item.SetActive(false);
G_Item = null;
}
break;
case 2: //조사하기 커맨드 실행 시
m_I_ButtonGage.fillAmount = Mathf.Lerp(m_I_ButtonGage.fillAmount, 1, t);
break;
}
}
// ↓ 조사하기 함수 (OnCollisionStay 함수에 넣을 것)
void LookPoint(Collider other)
{
if (other.CompareTag("LookPoint")) //플레이어가 조사 영역 내에 있을 때
{
m_T_CommandText.text = "조사";
m_G_ButtonPanel.SetActive(true);
if (Input.GetKey(KeyCode.E)) //플레이어가 E버튼을 누르고 있을 때
{
ButtonGage(2);
}
else if (m_I_ButtonGage.fillAmount < 0.98 && !Input.GetKey(KeyCode.E))
{
ButtonGage(0);
}
if (m_I_ButtonGage.fillAmount >= 0.99)
{
m_G_ButtonPanel.SetActive(false);
other.gameObject.GetComponent<LookPoint>().Action(other);
}
}
}
// ↓ 조사 영역을 벗어났을 때의 함수(OnCollisionExit 함수에 넣을 것)
void OutLookArea(Collider other)
{
if (other.CompareTag("LookPoint"))
{
m_G_ButtonPanel.SetActive(false);
m_I_ButtonGage.fillAmount = 0;
if (other.gameObject.GetComponent<LookPoint>().m_b_doneLook)
{
// ↓ 조사가 끝났을 시 조사영역 off(조사가 끝났는데도 조사 버튼이 계속 뜨는 걸 방지)
other.gameObject.GetComponent<BoxCollider>().enabled = false;
}
}
}
}
|
//using System.Collections;
//using System.Collections.Generic;
//using UnityEngine;
//using UnityEditor;
//public class DotAlignmenter : MonoBehaviour {
// public int hDistance=75;
// public int vDistance=54;
// public int hCount;
// public int vCount;
// [MenuItem("Karuna/Renamer %#R")]
// public static void AddComponent()
// {
// try
// {
// Selection.activeTransform.gameObject.AddComponent(typeof(DotAlignmenter));
// }
// catch (System.Exception)
// {
// Debug.Log("Select the parent to align childs.");
// }
// }
// public void AlignDots()
// {
// Debug.Log("Aligned");
// GameObject dot = Selection.activeTransform.GetChild(0).gameObject;
// float x = -(hDistance / hCount);
// float y = vDistance / vCount;
// float name = 1;
// for (int i = 0; i < vCount; i++)
// {
// for (int j = 0; j < hCount; j++)
// {
// Vector3 dotPos = new Vector3(x, y, 0);
// GameObject go = Instantiate(dot, dotPos, Quaternion.identity) as GameObject;
// go.transform.SetParent(dot.transform.parent);
// go.name = name.ToString();
// name++;
// x += hDistance / hCount;
// }
// x = -(hDistance / hCount);
// y -= (vDistance / hCount);
// }
// DestroyImmediate(dot);
// }
//}
|
using System;
using System.Collections;
using System.Collections.Generic;
using ReadyGamerOne.Common;
using ReadyGamerOne.Script;
using UnityEngine;
using UnityEngine.Assertions;
using Object = UnityEngine.Object;
namespace ReadyGamerOne.MemorySystem
{
public class AssetBundleResourceLoader:
Singleton<AssetBundleResourceLoader>,
IResourceLoader
{
#region Fields
private Dictionary<string, Object> sourceObjectDic;
private AssetBundleLoader assetBundleLoader;
private IHotUpdatePath pather;
private IOriginAssetBundleUtil originBundleConst;
#endregion
#region Properties
private Dictionary<string, Object> SourceObjects
{
get
{
if (sourceObjectDic == null)
sourceObjectDic = new Dictionary<string, Object>();
return sourceObjectDic;
}
set { sourceObjectDic = value; }
}
#endregion
#region Private
/// <summary>
/// 从缓存中获取资源,否则采用默认方式初始化
/// </summary>
/// <param name="key"></param>
/// <param name="defaultGetMethod"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private T GetSourceFromCache<T>(string key, Func<string, T> defaultGetMethod = null)
where T : Object
{
if (SourceObjects.ContainsKey(key))
{
if (SourceObjects[key] == null)
throw new Exception("资源已经释放,但字典中引用亦然保留");
var ans = SourceObjects[key] as T;
if (ans == null)
Debug.LogWarning("资源引用存在,但类型转化失败,小心bug");
return ans;
}
if (null == defaultGetMethod)
{
Debug.LogWarning("defaultGetMethod is null");
return null;
}
var source = defaultGetMethod(key);
if (source == null)
{
Debug.LogError("资源加载错误,错误路径:" + key);
return null;
}
SourceObjects.Add(key, source);
return source;
}
#endregion
public void ShowDebugInfo()
{
Debug.Log("《AssetBundle加载情况》\n" + assetBundleLoader.DebugInfo());
}
#region IResourceLoader
public void Init(IHotUpdatePath pather, IOriginAssetBundleUtil originConstData,IAssetConstUtil assetConstUtil)
{
if (null == pather)
return;
if (null == originConstData)
return;
this.originBundleConst = originConstData;
this.pather = pather;
assetBundleLoader = new AssetBundleLoader();
MainLoop.Instance.StartCoroutine(assetBundleLoader.StartBundleManager(pather, originConstData));
}
public T GetAsset<T>(string objName, string bundleKey = null)
where T : Object
{
if (null == pather)
throw new Exception("没有初始化MemoryMgr.Pather");
if (originBundleConst == null)
throw new Exception("originBundleConst is null");
return GetSourceFromCache(objName,
key =>
{
var ab = assetBundleLoader.GetBundle(bundleKey);
Assert.IsTrue(ab);
return ab.LoadAsset<T>(key);
});
}
public IEnumerator GetAssetAsync<T>(string objName, string bundleKey = null, Action<T> onGetObj = null)
where T : Object
{
if (null == pather)
throw new Exception("没有初始化MemoryMgr.Pather");
Assert.IsNotNull(onGetObj);
if (originBundleConst.KeyToName.ContainsKey(bundleKey))
{
var bundleName = originBundleConst.KeyToName[bundleKey];
//如果缓存中有,就直接使用缓存
var temp = GetSourceFromCache<T>($"{bundleName}_{objName}");
if (null != temp)
{
onGetObj(temp);
yield break;
}
}
//缓存没有,使用加载器加载
yield return assetBundleLoader.GetBundleAsync(bundleKey,
ab => GetAssetFormBundleAsync(ab, objName, onGetObj));
}
private IEnumerator GetAssetFormBundleAsync<T>(AssetBundle assetBundle, string _objName, Action<T> _onGetObj)
where T : Object
{
var objRequest = assetBundle.LoadAssetAsync<T>(_objName);
yield return objRequest;
//添加到缓存
var ans = objRequest.asset as T;
if (null == ans)
throw new Exception("Get Asset is null");
SourceObjects.Add($"{assetBundle.name}_{_objName}", ans);
var asset = (T) objRequest.asset;
Assert.IsNotNull(asset);
//使用物品
_onGetObj(asset);
}
public void ClearCache()
{
SourceObjects.Clear();
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace BuildFeed
{
public static class DatabaseConfig
{
public static string Host { get; private set; }
public static int Port { get; private set; }
public static long Database { get; private set; }
static DatabaseConfig()
{
Host = ConfigurationManager.AppSettings["data:ServerHost"];
int _port;
bool success = int.TryParse(ConfigurationManager.AppSettings["data:ServerPort"], out _port);
if(!success)
{
_port = 6379; // redis default port
}
Port = _port;
long _db;
success = long.TryParse(ConfigurationManager.AppSettings["data:ServerDB"], out _db);
if (!success)
{
_db = 0; // redis default db
}
Database = _db;
}
}
} |
using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("iQuest.VendingMachine")]
namespace VendingMachineDomain.Exceptions
{
public class InsufficientStockException : Exception
{
private const string DefaultMessage = "We are out of stock !!";
public InsufficientStockException()
: base(DefaultMessage)
{
}
public InsufficientStockException(string name)
: base(String.Format($"\nWe don't have any more {name} in stock !"))
{
}
}
}
|
namespace CarDealer.Client
{
using Data;
using Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Startup
{
#region Startup
static void Main(string[] args)
{
CarDealerContext context = new CarDealerContext();
//context.Database.Initialize(true);
ImportData();
//Query 1 - Ordered Customers
//OrderedCustomers(context);
//Query 2 - Cars from make Toyota
//CarsFromMakeToyota(context);
//Query 3 - Local Supppliers
//LocalSuppliers(context);
//Query 4 - Cars with Their List of Parts
//CarsWithTheirListOfParts(context);
//Query 5 - Total Sales by Customer
//TotalSalesByCustomer(context);
//Query 6 - Sales with Applied Discount
//SalesWithAppliedDiscount(context);
}
#endregion
#region 6. Car Dealer and Export Data
private static void SalesWithAppliedDiscount(CarDealerContext context)
{
using (context)
{
var cars = context.Sales
.Where(s => s.Discount != 0)
.ToList()
.Select(s => new
{
car = new
{
Make = s.Car.Make,
Model = s.Car.Model,
TravalledDistance = s.Car.TravelledDistance,
},
CustomerName = s.Customer.Name,
Discount = s.Discount,
Price = s.Car.Parts.Sum(p => p.Price),
PriceWithDiscount = (s.Car.Parts.Sum(p => p.Price)) - (s.Car.Parts.Sum(p => p.Price) * (decimal)s.Discount)
});
string json = JsonConvert.SerializeObject(cars, Formatting.Indented);
File.WriteAllText("../../Export/salesWithAppliedDiscount.json", json);
}
}
private static void TotalSalesByCustomer(CarDealerContext context)
{
using (context)
{
var customer = context.Customers
.Where(c => c.Sales.Count >= 1)
.Select(c => new
{
FullName = c.Name,
BoughtCars = c.Sales.Count,
SpendMoney = c.Sales.Sum(s => s.Car.Parts.Sum(car => car.Price))
})
.OrderByDescending(c => c.SpendMoney)
.ThenByDescending(c => c.BoughtCars);
string jsonCustomer = JsonConvert.SerializeObject(customer, Formatting.Indented);
File.WriteAllText("../../Export/totalSalesByCustomer.json", jsonCustomer);
}
}
private static void CarsWithTheirListOfParts(CarDealerContext context)
{
using (context)
{
var cars = context.Cars
.Select(c => new
{
car = new
{
Make = c.Make,
Model = c.Model,
TravelledDistance = c.TravelledDistance,
parts = c.Parts.Select(p => new
{
Name = p.Name,
Price = p.Price
})
}
});
string jsonCars = JsonConvert.SerializeObject(cars,Formatting.Indented);
File.WriteAllText("../../Export/carsWithTheirListofParts.json", jsonCars);
}
}
private static void LocalSuppliers(CarDealerContext context)
{
using (context)
{
var suppliers = context.Suppliers
.Where(s => s.IsImporter == false)
.Select(s => new
{
Id = s.Id,
Name = s.Name,
PartsCount = s.Parts.Count
});
string jsonSuppliers = JsonConvert.SerializeObject(suppliers, Formatting.Indented);
File.WriteAllText("../../Export/localSuppliers.json", jsonSuppliers);
}
}
private static void CarsFromMakeToyota(CarDealerContext context)
{
using (context)
{
var cars = context.Cars
.Where(c => c.Make == "Toyota")
.OrderBy(c => c.Model)
.ThenByDescending(c => c.TravelledDistance)
.Select(c => new
{
c.Id,
c.Make,
c.Model,
c.TravelledDistance
});
string jsonCars = JsonConvert.SerializeObject(cars, Formatting.Indented);
File.WriteAllText("../../Export/carsFromMakeToyota.json", jsonCars);
}
}
private static void OrderedCustomers(CarDealerContext context)
{
using (context)
{
var customers = context.Customers
.OrderBy(c => c.BirthDate)
.ThenByDescending(c => c.IsYoungDriver)
.Select(c => new
{
Id = c.Id,
Name = c.Name,
BirthDate = c.BirthDate,
IsYoungDriver = c.IsYoungDriver,
Sales = c.Sales.Select(s => new
{
Id = s.Id,
CarId = s.CarId,
CustomerId = s.CustomerId,
Discount = s.Discount
})
});
string jsonCustomers = JsonConvert.SerializeObject(customers, Formatting.Indented);
File.WriteAllText("../../Export/orderedCustomers.json", jsonCustomers);
}
}
#endregion
#region 5. Car Dealer Import Data
private static void ImportData()
{
//ImportSuppliers();
//ImportParts();
//ImportCars();
//ImportCustomers();
//ImportSales();
}
private static void ImportSales()
{
using (CarDealerContext context = new CarDealerContext())
{
double[] discounts = new double[] { 0, 0.05, 0.10, 0.20, 0.30, 0.40, 0.50 };
var cars = context.Cars.ToList();
var customers = context.Customers.ToList();
Random rnd = new Random();
for (int i = 0; i < 60; i++)
{
var car = cars[rnd.Next(cars.Count)];
var customer = customers[rnd.Next(customers.Count)];
var discount = discounts[rnd.Next(discounts.Length)];
if(customer.IsYoungDriver)
{
discount += 0.05;
}
Sale sale = new Sale()
{
Car = car,
Customer = customer,
Discount = discount
};
context.Sales.Add(sale);
}
context.SaveChanges();
}
}
private static void ImportCustomers()
{
using (CarDealerContext context = new CarDealerContext())
{
string json = File.ReadAllText("../../Import/customers.json");
var jsonCustomers = JsonConvert.DeserializeObject<List<Customer>>(json);
context.Customers.AddRange(jsonCustomers);
context.SaveChanges();
}
}
private static void ImportCars()
{
using (CarDealerContext context = new CarDealerContext())
{
string json = File.ReadAllText("../../Import/cars.json");
var jsonCars = JsonConvert.DeserializeObject<List<Car>>(json);
Random rnd = new Random();
var parts = context.Part.ToList();
foreach (var c in jsonCars)
{
int randomPartsBetween10And20 = rnd.Next(10, 21);
for (int i = 0; i < randomPartsBetween10And20; i++)
{
c.Parts.Add(parts[rnd.Next(parts.Count)]);
}
}
context.Cars.AddRange(jsonCars);
context.SaveChanges();
}
}
private static void ImportParts()
{
using (CarDealerContext context = new CarDealerContext())
{
string json = File.ReadAllText("../../Import/parts.json");
var jsonParts = JsonConvert.DeserializeObject<List<Part>>(json);
Random rnd = new Random();
int countSuppliers = context.Suppliers.Count();
foreach (var p in jsonParts)
{
p.SupplierId = rnd.Next(1, countSuppliers + 1);
}
context.Part.AddRange(jsonParts);
context.SaveChanges();
}
}
private static void ImportSuppliers()
{
using (CarDealerContext context = new CarDealerContext())
{
string json = File.ReadAllText("../../Import/suppliers.json");
var jsonSuppliers = JsonConvert.DeserializeObject<List<Supplier>>(json);
context.Suppliers.AddRange(jsonSuppliers);
context.SaveChanges();
}
}
#endregion
}
}
|
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FollowDirections.Test
{
[TestClass]
public class RobotTests
{
[TestMethod]
public void RobotTest()
{
var commands = new[]
{
"Move 2",
"Turn right",
"Move 4",
"Turn left",
"Move -5",
"Turn right",
"Move 10",
"Turn left",
"Move -2",
"Turn left",
"Turn left",
"Move 5",
"Move -2",
"Turn right",
"Move 1",
"Move 0"
};
const int expectedX = 13;
const int expectedY = -8;
var grid = new Grid();
var robot = new Robot(grid);
commands.ToList().ForEach(robot.Command);
var actualX = robot.PositionX;
var actualY = robot.PositionY;
Assert.AreEqual(expectedX, actualX);
Assert.AreEqual(expectedY, actualY);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ivi.Visa.Interop;
using System.Threading;
using System.Windows.Forms;
namespace LibEqmtDriver.SA
{
public class E4440A : IISigAnalyzer
{
public static string ClassName = "E4440A MXA Class";
private FormattedIO488 _myVisaSa = new FormattedIO488();
public string IoAddress;
/// <summary>
/// Parsing Equpment Address
/// </summary>
public string Address
{
get
{
return IoAddress;
}
set
{
IoAddress = value;
}
}
public FormattedIO488 ParseIo
{
get
{
return _myVisaSa;
}
set
{
_myVisaSa = ParseIo;
}
}
public void OpenIo()
{
if (IoAddress.Length > 3)
{
try
{
ResourceManager mgr = new ResourceManager();
_myVisaSa.IO = (IMessage)mgr.Open(IoAddress, AccessMode.NO_LOCK, 2000, "");
}
catch (SystemException ex)
{
MessageBox.Show("Class Name: " + ClassName + "\nParameters: OpenIO" + "\n\nErrorDesciption: \n"
+ ex, "Error found in Class " + ClassName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
_myVisaSa.IO = null;
return;
}
}
}
public E4440A(string ioAddress)
{
Address = ioAddress;
OpenIo();
}
~E4440A() { }
#region iSigAnalyzer
public void Initialize(int equipId)
{
_myVisaSa.WriteString(":INST SA", true);
Reset();
if (equipId == 1) // PSA E4440A
{
_myVisaSa.WriteString("CORR:CSET1 OFF", true);
_myVisaSa.WriteString("CORR:CSET2 OFF", true);
_myVisaSa.WriteString("CORR:CSET3 OFF", true);
_myVisaSa.WriteString("CORR:CSET4 OFF", true);
_myVisaSa.WriteString("CORR:CSET:ALL OFF", true);
_myVisaSa.WriteString("CORR:OFFS:MAGN 0", true);
_myVisaSa.WriteString("CALC:MARK:FUNC OFF", true);
}
else if (equipId == 3) // MXA
_myVisaSa.WriteString(":CORR:SA:GAIN 0", true);
_myVisaSa.WriteString(":FORM:DATA REAL,32", true);
_myVisaSa.WriteString(":INIT:CONT 1", true);
_myVisaSa.WriteString(":BWID:VID:RAT " + "10", true);
_myVisaSa.WriteString("SWE:POIN 301", true);
_myVisaSa.WriteString("SENS:ROSC:SOUR EXT", true);
_myVisaSa.WriteString("SENS:ROSC:OUTP OFF", true);
}
public void Preset()
{
_myVisaSa.WriteString("SYST:PRES", true);
}
void IISigAnalyzer.Select_Instrument(N9020AInstrumentMode mode)
{
switch (mode)
{
case N9020AInstrumentMode.SpectrumAnalyzer: _myVisaSa.WriteString("INST:SEL SA", true); break;
case N9020AInstrumentMode.Basic: _myVisaSa.WriteString("INST:SEL BASIC", true); break;
case N9020AInstrumentMode.Wcdma: _myVisaSa.WriteString("INST:SEL WCDMA", true); break;
case N9020AInstrumentMode.Wimax: _myVisaSa.WriteString("INST:SEL WIMAXOFDMA", true); break;
case N9020AInstrumentMode.EdgeGsm: _myVisaSa.WriteString("INST:SEL EDGEGSM", true); break;
default: throw new Exception("Not such a intrument mode!");
}
}
void IISigAnalyzer.Select_Triggering(N9020ATriggeringType type)
{
switch (type)
{
///******************************************
/// SweptSA mode trigerring
///******************************************
case N9020ATriggeringType.RfExt1: _myVisaSa.WriteString("TRIG:SOUR EXT1", true); break;
case N9020ATriggeringType.RfExt2: _myVisaSa.WriteString("TRIG:SOUR EXT2", true); break;
case N9020ATriggeringType.RfRfBurst: _myVisaSa.WriteString("TRIG:SOUR RFB", true); break;
case N9020ATriggeringType.RfVideo: _myVisaSa.WriteString("TRIG:SOUR VID", true); break;
case N9020ATriggeringType.RfFreeRun: _myVisaSa.WriteString("TRIG:SOUR IMM", true); break;
///******************************************
/// EDGEGSM Transmit power type trigerring
///******************************************
///******************************************
/// EDGEGSM Power Vs Time type trigerring
///******************************************
///******************************************
/// EDGEGSM Power Vs Time type trigerring
///******************************************
///******************************************
/// EDGEGSM Edge Power Vs Time type trigerring
///******************************************
///******************************************
/// EDGEGSM Edge EVM type trigerring
///******************************************
default: throw new Exception("Not such a Trigger Mode!");
}
}
void IISigAnalyzer.Measure_Setup(N9020AMeasType type)
{
switch (type)
{
case N9020AMeasType.SweptSa: _myVisaSa.WriteString(":INIT:SAN", true); break;
case N9020AMeasType.ChanPower: _myVisaSa.WriteString(":INIT:CHP", true); break;
case N9020AMeasType.Acp: _myVisaSa.WriteString(":CONF:ACP:NDEF", true); break;
case N9020AMeasType.BTxPow: _myVisaSa.WriteString(":INIT:TXP", true); break;
case N9020AMeasType.GPowVtm: _myVisaSa.WriteString(":INIT:PVT", true); break;
case N9020AMeasType.GpHaseFreq: _myVisaSa.WriteString(":INIT:PFER", true); break;
case N9020AMeasType.GOutRfSpec: _myVisaSa.WriteString(":INIT:ORFS", true); break;
case N9020AMeasType.GTxSpur: _myVisaSa.WriteString(":INIT:TSP", true); break;
case N9020AMeasType.EPowVtm: _myVisaSa.WriteString(":INIT:EPVT", true); break;
case N9020AMeasType.Eevm: _myVisaSa.WriteString(":INIT:EEVM", true); break;
case N9020AMeasType.EOutRfSpec: _myVisaSa.WriteString(":INIT:EORF", true); break;
case N9020AMeasType.ETxSpur: _myVisaSa.WriteString(":INIT:ETSP", true); break;
case N9020AMeasType.MonitorSpec: break;
default: throw new Exception("Not such a Measure setup type!");
}
}
void IISigAnalyzer.Enable_Display(N9020ADisplay onoff)
{
_myVisaSa.WriteString(":DISP:ENAB " + onoff, true);
}
void IISigAnalyzer.VBW_RATIO(double ratio)
{
_myVisaSa.WriteString("BAND:VID:RAT " + ratio.ToString(), true);
}
void IISigAnalyzer.Span(double freqMHz)
{
_myVisaSa.WriteString("FREQ:SPAN " + freqMHz.ToString() + " MHz", true);
}
void IISigAnalyzer.MARKER_TURN_ON_NORMAL_POINT(int markerNum, float markerFreqMHz)
{
_myVisaSa.WriteString("CALC:MARK" + markerNum.ToString() + ":MODE POS", true);
_myVisaSa.WriteString("CALC:MARK" + markerNum.ToString() + ":X " + markerFreqMHz.ToString() + " MHz", true);
}
void IISigAnalyzer.TURN_ON_INTERNAL_PREAMP()
{
_myVisaSa.WriteString("POW:GAIN ON", true);
_myVisaSa.WriteString("POW:GAIN:BAND FULL", true);
}
void IISigAnalyzer.TURN_OFF_INTERNAL_PREAMP()
{
_myVisaSa.WriteString("POW:GAIN OFF", true);
}
void IISigAnalyzer.TURN_OFF_MARKER()
{
_myVisaSa.WriteString(":CALC:MARK:AOFF", true);
}
double IISigAnalyzer.READ_MARKER(int markerNum)
{
return WRITE_READ_DOUBLE("CALC:MARK" + markerNum.ToString() + ":Y?");
}
void IISigAnalyzer.SWEEP_TIMES(int sweeptimeMs)
{
_myVisaSa.WriteString(":SWE:TIME " + sweeptimeMs.ToString() + " ms", true);
}
void IISigAnalyzer.SWEEP_POINTS(int sweepPoints)
{
_myVisaSa.WriteString(":SWE:POIN " + sweepPoints.ToString(), true);
}
void IISigAnalyzer.CONTINUOUS_MEASUREMENT_ON()
{
_myVisaSa.WriteString("INIT:CONT ON", true);
}
void IISigAnalyzer.CONTINUOUS_MEASUREMENT_OFF()
{
_myVisaSa.WriteString("INIT:CONT OFF", true);
}
void IISigAnalyzer.RESOLUTION_BW(double bw)
{
_myVisaSa.WriteString(":BAND " + bw.ToString(), true);
}
double IISigAnalyzer.MEASURE_PEAK_POINT(int delayMs)
{
_myVisaSa.WriteString("CALC:MARK:MAX", true);
Thread.Sleep(delayMs);
bool status = Operation_Complete();
return WRITE_READ_DOUBLE("CALC:MARK:Y?");
}
double IISigAnalyzer.MEASURE_PEAK_FREQ(int delayMs)
{
_myVisaSa.WriteString("CALC:MARK:MAX", true);
Thread.Sleep(delayMs);
bool status = Operation_Complete();
return WRITE_READ_DOUBLE("CALC:MARK:X?");
}
void IISigAnalyzer.VIDEO_BW(double vbwHz)
{
_myVisaSa.WriteString(":BAND:VID " + vbwHz, true);
}
void IISigAnalyzer.TRIGGER_CONTINUOUS()
{
_myVisaSa.WriteString("INIT:CONT ON", true);
}
void IISigAnalyzer.TRIGGER_SINGLE()
{
_myVisaSa.WriteString("INIT:CONT OFF", true);
}
void IISigAnalyzer.TRIGGER_IMM()
{
_myVisaSa.WriteString("INIT:IMM", true);
}
void IISigAnalyzer.TRACE_AVERAGE(int avg)
{
_myVisaSa.WriteString(":AVERage:COUN " + avg.ToString(), true);
}
void IISigAnalyzer.AVERAGE_OFF()
{
_myVisaSa.WriteString(":AVER:STAT OFF", true);
}
void IISigAnalyzer.AVERAGE_ON()
{
_myVisaSa.WriteString(":AVER:STAT ON", true);
}
void IISigAnalyzer.SET_TRACE_DETECTOR(string mode)
{
switch (mode.ToUpper())
{
case "WRIT":
case "WRITE":
_myVisaSa.WriteString("TRAC:MODE WRIT", true);
break;
case "MAXH":
case "MAXHOLD":
_myVisaSa.WriteString("TRAC:MODE MAXH", true);
break;
case "MINH":
case "MINHOLD":
_myVisaSa.WriteString("TRAC:MODE MINH", true);
break;
}
}
void IISigAnalyzer.CLEAR_WRITE()
{
_myVisaSa.WriteString("TRAC:MODE WRIT", true);
}
void IISigAnalyzer.AMPLITUDE_REF_LEVEL_OFFSET(double refLvlOffset)
{
_myVisaSa.WriteString("DISP:WIND:TRAC:Y:RLEV:OFFS " + refLvlOffset, true);
}
void IISigAnalyzer.AMPLITUDE_REF_LEVEL(double refLvl)
{
_myVisaSa.WriteString("DISP:WIND:TRAC:Y:RLEV " + refLvl, true);
}
void IISigAnalyzer.AMPLITUDE_INPUT_ATTENUATION(double inputAttenuation)
{
_myVisaSa.WriteString("POW:ATT " + inputAttenuation, true);
}
void IISigAnalyzer.AUTO_ATTENUATION(bool state)
{
if (state)
{
_myVisaSa.WriteString(":SENS:POW:ATT:AUTO ON", true);
}
else
{
_myVisaSa.WriteString(":SENS:POW:ATT:AUTO OFF", true);
}
}
void IISigAnalyzer.ELEC_ATTENUATION(float inputAttenuation)
{
_myVisaSa.WriteString("POW:EATT " + inputAttenuation, true);
}
void IISigAnalyzer.ELEC_ATTEN_ENABLE(bool inputStat)
{
if (inputStat)
_myVisaSa.WriteString("POW:EATT:STAT ON", true);
else
_myVisaSa.WriteString("POW:EATT:STAT OFF", true);
}
void IISigAnalyzer.ALIGN_PARTIAL()
{
_myVisaSa.WriteString(":CAL:AUTO PART", true);
}
void IISigAnalyzer.ALIGN_ONCE()
{
_myVisaSa.WriteString(":CAL:AUTO ONCE", true);
}
void IISigAnalyzer.AUTOALIGN_ENABLE(bool inputStat)
{
if (inputStat)
_myVisaSa.WriteString(":CAL:AUTO ON", true);
else
_myVisaSa.WriteString(":CAL:AUTO OFF", true);
}
void IISigAnalyzer.Cal()
{
_myVisaSa.WriteString(":CAL", true);
}
bool IISigAnalyzer.OPERATION_COMPLETE()
{
bool complete = false;
double dummy = -9;
do
{
//timer.wait(2);
dummy = WRITE_READ_DOUBLE("*OPC?");
} while (dummy == 0);
complete = true;
return complete;
}
void IISigAnalyzer.START_FREQ(string strFreq, string strUnit)
{
_myVisaSa.WriteString("SENS:FREQ:STAR " + strFreq + strUnit, true);
}
void IISigAnalyzer.STOP_FREQ(string strFreq, string strUnit)
{
_myVisaSa.WriteString("SENS:FREQ:STOP " + strFreq + strUnit, true);
}
void IISigAnalyzer.FREQ_CENT(string strSaFreq, string strUnit)
{
_myVisaSa.WriteString(":FREQ:CENT " + strSaFreq + strUnit, true);
}
string IISigAnalyzer.READ_MXATrace(int traceNum)
{
_myVisaSa.WriteString(":FORM ASC", true);
return WRITE_READ_STRING(":TRAC? TRACE" + traceNum.ToString());
}
double IISigAnalyzer.READ_STARTFREQ()
{
return WRITE_READ_DOUBLE("SENS:FREQ:STAR?");
}
double IISigAnalyzer.READ_STOPFREQ()
{
return WRITE_READ_DOUBLE("SENS:FREQ:STOP?");
}
float IISigAnalyzer.READ_SWEEP_POINTS()
{
return WRITE_READ_SINGLE(":SWE:POIN?");
}
float[] IISigAnalyzer.IEEEBlock_READ_MXATrace(int traceNum)
{
float[] arrSaTraceData = null;
_myVisaSa.WriteString(":FORM:DATA REAL,32", true);
arrSaTraceData = WRITE_READ_IEEEBlock(":TRAC? TRACE" + traceNum.ToString(), IEEEBinaryType.BinaryType_R4);
_myVisaSa.WriteString(":FORM ASC", true);
return arrSaTraceData;
}
void IISigAnalyzer.EXT_AMP_GAIN(double gain)
{
_myVisaSa.WriteString("CORR:OFFS:MAGN " + gain, true);
}
void IISigAnalyzer.Select_MarkerFunc(N9020AMarkerFunc type)
{
switch (type)
{
case N9020AMarkerFunc.Off: _myVisaSa.WriteString("CALC:MARK:FUNC OFF", true); break;
case N9020AMarkerFunc.Bandpow: _myVisaSa.WriteString("CALC:MARK:FUNC BPOW", true); break;
case N9020AMarkerFunc.Banddensity: _myVisaSa.WriteString("CALC:MARK:FUNC BDEN", true); break;
case N9020AMarkerFunc.Noise: _myVisaSa.WriteString("CALC:MARK:FUNC NOIS", true); break;
default: throw new Exception("Not such a Marker Function type!");
}
}
#endregion
public bool Operation_Complete()
{
bool complete = false;
double dummy = -9;
do
{
//timer.wait(2);
dummy = WRITE_READ_DOUBLE("*OPC?");
} while (dummy == 0);
complete = true;
return complete;
}
public void Reset()
{
try
{
_myVisaSa.WriteString("*CLS; *RST", true);
}
catch (Exception ex)
{
throw new Exception("EquipSA: RESET -> " + ex.Message);
}
}
#region READ and WRITE function
public string READ_STRING()
{
return _myVisaSa.ReadString();
}
public void Write(string cmd)
{
_myVisaSa.WriteString(cmd, true);
}
public double WRITE_READ_DOUBLE(string cmd)
{
_myVisaSa.WriteString(cmd, true);
return Convert.ToDouble(_myVisaSa.ReadString());
}
public string WRITE_READ_STRING(string cmd)
{
_myVisaSa.WriteString(cmd, true);
return _myVisaSa.ReadString();
}
public float WRITE_READ_SINGLE(string cmd)
{
_myVisaSa.WriteString(cmd, true);
return Convert.ToSingle(_myVisaSa.ReadString());
}
public float[] READ_IEEEBlock(IEEEBinaryType type)
{
return (float[])_myVisaSa.ReadIEEEBlock(type, true, true);
}
public float[] WRITE_READ_IEEEBlock(string cmd, IEEEBinaryType type)
{
_myVisaSa.WriteString(cmd, true);
return (float[])_myVisaSa.ReadIEEEBlock(type, true, true);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AgoraJoiner : MonoBehaviour
{
// when I become in range with someone, display button to ask them to join my party
public GameObject inviteButton;
public GameObject joinButton;
public GameObject remoteVideoSurface;
public Collider otherPlayer;
string localChannel;
string remoteInviteChannel;
// when I have been asked, display a button that says join.
// Start is called before the first frame update
void Start()
{
//otherPlayer = null;
//inviteButton.SetActive(false);
//joinButton.SetActive(false);
//remoteVideoSurface.SetActive(false);
}
//private void OnTriggerEnter(Collider other)
//{
// if(other.CompareTag("Player"))
// {
// //display invite button
// inviteButton.SetActive(true);
// otherPlayer = other;
// }
//}
//private void OnTriggerExit(Collider other)
//{
// if(other.CompareTag("Player"))
// {
// otherPlayer = null;
// inviteButton.SetActive(false);
// }
//}
//public void QueryPartyJoin(string newChannel)
//{
// remoteInviteChannel = newChannel;
// // here an outsidd player has asked me to join their party
// // my join button shows up
// joinButton.SetActive(true);
//}
//public void OnInviteButtonPress()
//{
// print(gameObject.name + " pressed Invite!");
// // send channel name to other player
// otherPlayer.GetComponent<AgoraJoiner>().QueryPartyJoin(GetChannel());
//}
//// click Join to JoinChannel(newChannel)
//public void OnJoinButtonPress()
//{
// // AgoraEngine. Join Channel -> Include NEW channel name
// transform.GetChild(2).GetComponent<AgoraEngine>().JoinPlayersChat(remoteInviteChannel);
//}
//private string GetChannel()
//{
// if(localChannel == null)
// {
// localChannel = transform.GetChild(2).GetComponent<AgoraEngine>().channel;
// }
// return localChannel;
//}
}
|
using System;
namespace NotaValida
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Validação de notas entre 0 a 10 \n");
bool notaValida = false;
do
{
Console.WriteLine("Qual é a nota que vc recebeu?");
int nota = int.Parse(Console.ReadLine());
if (nota > 0 && nota <= 10)
{
notaValida = true;
Console.WriteLine("Sua nota é valida e é igual a: " + nota + "\n");
} else
{
notaValida = false;
Console.WriteLine("Essa não é uma nota válida! \n Digite uma nota de 0 a 10 \n");
}
} while (notaValida == false);
Console.WriteLine("Fim do sistema");
}
}
}
|
using DDDSouthWest.Domain;
using DDDSouthWest.Domain.Features.Account.RegisterNewUser;
using DDDSouthWest.Domain.Features.Public.Page;
using MediatR;
using StructureMap;
namespace DDDSouthWest.UnitTests
{
public static class ResolveContainer
{
public static IMediator MediatR
{
get
{
var container = new Container(cfg =>
{
cfg.Scan(scanner =>
{
scanner.AssemblyContainingType<GetPage.Query>();
scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
scanner.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
});
cfg.For<IRegistrationConfirmation>().Use<SendEmailConfirmation>();
cfg.For<ClientConfigurationOptions>().Use(() => new ClientConfigurationOptions
{
Database = new Database
{
ConnectionString =
"Host=localhost;Username=dddsouthwest_user;Password=letmein;Database=dddsouthwest"
},
WebsiteSettings = new WebsiteSettings
{
RequireNewAccountConfirmation = false
}
}).Singleton();
cfg.For<ServiceFactory>().Use<ServiceFactory>(ctx => t => ctx.GetInstance(t));
cfg.For<IMediator>().Use<Mediator>();
});
return container.GetInstance<IMediator>();
}
}
}
} |
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using StudyEspanol.Data.Managers;
using StudyEspanol.Data.Models;
using StudyEspanol.Droid;
using StudyEspanol.Res;
using StudyEspanol.Utilities;
namespace StudyEspanol.UI.Screens
{
[Activity()]
public class QuizCompleteScreen : Screen
{
#region Fields
private GridView wordList;
private AnswerListAdapter answerAdapter;
private TextView percentage;
private IMenuItem filterItem;
#endregion
#region Properties
public Intent DefaultIntent
{
get
{
Intent intent = new Intent(Intent.ActionSend);
intent.SetType("text/plain");
StringBuilder sb = new StringBuilder(Strings.share_complete_1);
sb.Append(" " + percentage.Text + " ");
sb.Append(Strings.share_complete_2);
intent.PutExtra(Intent.ExtraText, sb.ToString());
return intent;
}
}
#endregion
#region Initialization
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
SetContentView(Resource.Layout.screen_quiz_complete);
SetTitle(Resource.String.quiz_complete);
wordList = FindViewById<GridView>(Resource.Id.list_answers);
answerAdapter = new AnswerListAdapter(this, Resource.Layout.cell_answer_list, QuizManager.Instance.Objects);
wordList.Adapter = answerAdapter;
wordList.ItemClick += ListItemClicked;
percentage = FindViewById<TextView>(Resource.Id.textview_percentage);
percentage.Text = QuizManager.Instance.Percentage.ToString("P1");
TextView grade = FindViewById<TextView>(Resource.Id.textview_grade);
grade.Text = QuizManager.Instance.Correct.ToString() + "/" + QuizManager.Instance.Objects.Count.ToString();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.menu_completion, menu);
filterItem = menu.FindItem(Resource.Id.action_filter);
filterItem.SetTitle(Strings.all);
FilterMenuAction filterSAP = (FilterMenuAction)filterItem.ActionProvider;
IMenuItem shareItem = menu.FindItem(Resource.Id.action_share);
ShareActionProvider shareSAP = (ShareActionProvider)shareItem.ActionProvider;
shareSAP.SetShareIntent(DefaultIntent);
return true;
}
#endregion
#region Interactive Methods
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.action_all:
answerAdapter.DisplayFilter = AnswerListAdapter.Filters.All;
filterItem.SetTitle(Strings.all);
break;
case Resource.Id.action_correct:
answerAdapter.DisplayFilter = AnswerListAdapter.Filters.Correct;
filterItem.SetTitle(Strings.correct);
break;
case Resource.Id.action_incorrect:
answerAdapter.DisplayFilter = AnswerListAdapter.Filters.Incorrect;
filterItem.SetTitle(Strings.incorrect);
break;
default:
base.OnOptionsItemSelected(item);
break;
}
return true;
}
private void ListItemClicked(object sender, AdapterView.ItemClickEventArgs e)
{
Word word = WordsManager.Instance.Objects[e.Position];
Intent intent = new Intent(this, typeof(WordScreen));
intent.PutExtra(WordScreen.WORD, word);
StartActivity(intent);
}
#endregion
#region Methods
#endregion
}
}
|
using LAP_PowerMining.Core.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LAP_PowerMining.Controllers
{
public class WalletController : MyBaseController
{
// GET: Wallet
[Authorize]
public ActionResult Index()
{
return View();
}
}
} |
using System.Collections.Generic;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using SaleShop.Common;
using SaleShop.Model.Models;
namespace SaleShop.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<SaleShop.Data.SaleShopDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(SaleShop.Data.SaleShopDbContext context)
{
//CreateProductCategoryExample(context);
//CreateSlideExample(context);
//CreatePageExample(context);
//CreateContactDetailExample(context);
CreateConfigTitle(context);
}
private void CreateUserExample(SaleShop.Data.SaleShopDbContext context)
{
// This method will be called after migrating to the latest version.
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new SaleShopDbContext()));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new SaleShopDbContext()));
//Tạo mới user
var user = new ApplicationUser()
{
UserName = "youandpro",
Email = "dat.nguyenthaithanh@hotmail.com",
BirthDay = DateTime.Now,
FullName = "Lukas Nguyen"
};
if (manager.Users.Count(n => n.UserName == "admin") == 0)
{
manager.Create(user, "123456789");
if (!roleManager.Roles.Any())
{
roleManager.Create(new IdentityRole() { Name = "Admin" });
roleManager.Create(new IdentityRole() { Name = "User" });
var adminUser = manager.FindByEmail("dat.nguyenthaithanh@hotmail.com");
manager.AddToRoles(adminUser.Id, new string[] { "Admin", "User" });
}
}
}
private void CreateProductCategoryExample(SaleShop.Data.SaleShopDbContext context)
{
if (!context.ProductCategories.Any())
{
context.ProductCategories.AddRange(new List<ProductCategory>()
{
new ProductCategory(){Name = "Điện Lạnh",Alias = "dien-lanh",Status = true},
new ProductCategory(){Name = "Viễn thông",Alias = "vien-thong",Status = true},
new ProductCategory(){Name = "Đồ gia dụng",Alias = "do-gia-dung",Status = true},
new ProductCategory(){Name = "Mỹ phẩm",Alias = "my-pham",Status = true}
});
context.SaveChanges();
}
}
private void CreateSlideExample(SaleShop.Data.SaleShopDbContext context)
{
if (context.Slides.Count() == 0)
{
List<Slide> listSlide = new List<Slide>()
{
new Slide()
{
Name = "Slide 1",
DisplayOrder = 1 ,
Status = true,
Url = "#",
Image = "/Assets/client/images/bag.jpg",
Content = @"<h2>FLAT 50% 0FF</h2>
<label>FOR ALL PURCHASE <b>VALUE</b></label>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et </p>
<span class=""on-get"">GET NOW</span>"
},
new Slide()
{
Name = "Slide 2",
DisplayOrder = 2 ,
Status = true,
Url = "#",
Image = "/Assets/client/images/bag1.jpg",
Content = @"<h2>FLAT 50% 0FF</h2>
<label>FOR ALL PURCHASE <b>VALUE</b></label>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et </p>
<span class=""on-get"">GET NOW</span>"
}
};
context.Slides.AddRange(listSlide);
context.SaveChanges();
}
}
private void CreateFooterExample(SaleShop.Data.SaleShopDbContext context)
{
if (context.Footers.Count(n=>n.ID == CommonConstants.DefaultFooterId) == 0)
{
string content = "footer";
context.Footers.Add(new Footer
{
ID = CommonConstants.DefaultFooterId,
Content = content
});
context.SaveChanges();
}
}
private void CreatePageExample(SaleShop.Data.SaleShopDbContext context)
{
if (context.Pages.Count() == 0)
{
var page = new Page()
{
Name = "Giới thiệu",
Alias = "gioi-thieu",
Content = @"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
Status = true
};
context.Pages.Add(page);
context.SaveChanges();
}
}
private void CreateContactDetailExample(SaleShop.Data.SaleShopDbContext context)
{
if (context.ContactDetails.Count() == 0)
{
var contactDetail = new SaleShop.Model.Models.ContactDetail()
{
Name = "Lukas Shop",
Address = "Thành phố Hồ Chí Minh",
Email = "dat.nguyenthaithanh@hotmail.com",
Lat = 10.760501,
Lng = 106.663296,
Phone = "0949209493",
Website = "lukasnguyen.com",
Other = "",
Status = true
};
context.ContactDetails.Add(contactDetail);
context.SaveChanges();
}
}
private void CreateConfigTitle(SaleShopDbContext context)
{
if (!context.SystemConfigs.Any(x => x.Code == "HomeTitle"))
{
context.SystemConfigs.Add(new SystemConfig()
{
Code = "HomeTitle",
ValueString = "Trang chủ LukasShop",
});
}
if (!context.SystemConfigs.Any(x => x.Code == "HomeMetaKeyword"))
{
context.SystemConfigs.Add(new SystemConfig()
{
Code = "HomeMetaKeyword",
ValueString = "Trang chủ LukasShop",
});
}
if (!context.SystemConfigs.Any(x => x.Code == "HomeMetaDescription"))
{
context.SystemConfigs.Add(new SystemConfig()
{
Code = "HomeMetaDescription",
ValueString = "Trang chủ LukasShop",
});
}
context.SaveChanges();
}
}
}
|
using MediatR;
using Publicon.Infrastructure.DTOs;
using System;
namespace Publicon.Infrastructure.Queries.Models.Publication
{
public class DownloadPublicationQuery : IRequest<BlobInfoDTO>
{
public Guid PublicationId { get; set; }
public DownloadPublicationQuery(Guid publicationId)
{
PublicationId = publicationId;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using BLL.Dtos;
using BLL.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PL.Models;
namespace PL.Controllers
{
[Route("api/librarycards")]
[ApiController]
public class LibraryCardsController : ControllerBase
{
private ILibraryCardsService libraryCardsService;
private IMapper mapper;
public LibraryCardsController(ILibraryCardsService libraryCardsService, IMapper mapper)
{
this.libraryCardsService = libraryCardsService;
this.mapper = mapper;
}
#region Library Cards stuff
/// <summary>
/// Get list of all library cards. Recommended for library admin's panel.
/// </summary>
/// <response code="200">**Success**. Return list of library cards.</response>
/// <response code="404">**Not Found**. No library cards found in database.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpGet()]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public IActionResult GetLibraryCards()
{
try
{
var libraryCards = libraryCardsService.GetAllLibraryCards();
if (libraryCards == null || libraryCards.Count() < 1)
{
return NotFound();
}
else
{
return Ok(mapper.Map<IEnumerable<LibraryCardPL>>(libraryCards));
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Cannot get list of library cards. Error message: " + ex);
}
}
/// <summary>
/// Get specified library card.
/// </summary>
/// <param name="LibraryCardId">GUID of library card.</param>
/// <response code="200">**Success**. Return specified library card.</response>
/// <response code="404">**Not Found**. Specified library card not found.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpGet("{LibraryCardId}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public IActionResult GetLibraryCardById(Guid LibraryCardId)
{
try
{
var libraryCard = libraryCardsService.GetLibraryCardById(LibraryCardId);
if (libraryCard == null)
{
return NotFound();
}
else
{
return Ok(mapper.Map<LibraryCardPL>(libraryCard));
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Cannot get library card with id:" + LibraryCardId.ToString() + " . Error Message: " + ex);
}
}
/// <summary>
/// Manually create a library card.
/// </summary>
/// <param name="libraryCard">Requesting JSON model fields:
///
/// libraryCardId | Can be missed. New Id will be generated by server.
/// studentId | Required, GUID of owner student
/// student | Can be missed. Student will be loaded automatically.
/// </param>
/// <remarks>
/// Sample request:
///
/// POST api/librarycards
/// {
/// "studentId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// }
/// </remarks>
/// <response code="201">**Created**. Library card was created.</response>
/// <response code="400">**Bad Request**. Model is not valid or null.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpPost()]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult AddLibraryCard([FromBody] LibraryCardPL libraryCard)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
libraryCard.LibraryCardId = Guid.NewGuid();
var newCard = mapper.Map<LibraryCardDto>(libraryCard);
libraryCardsService.AddLibraryCard(newCard);
return StatusCode(201, "Library card was added");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Library card is not added. Exception message: " + ex);
}
}
/// <summary>
/// Update a library card.
/// </summary>
/// <param name="LibraryCardId">GUID of library card.</param>
/// <param name="libraryCard">Requesting JSON model fields:
///
/// libraryCardId | Required.
/// studentId | Required, GUID of owner student
/// student | Can be missed. Student will be loaded automatically.
/// </param>
/// <remarks>
/// Sample request:
///
/// PUT api/librarycards/3fa85f64-5717-4562-b3fc-2c963f66afa6
/// {
/// "libraryCardId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "studentId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// }
/// </remarks>
/// <response code="204">**No Content**. Library card was updated.</response>
/// <response code="400">**Bad Request**. Model is not valid or null.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpPut("{LibraryCardId}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult UpdateBook(Guid LibraryCardId, [FromBody] LibraryCardPL libraryCard)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
libraryCard.LibraryCardId = LibraryCardId;
var newLibraryCard = mapper.Map<LibraryCardDto>(libraryCard);
libraryCardsService.UpdateLibraryCard(newLibraryCard);
return StatusCode(204, "Library card was updated");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Library card is not updated. Exception message: " + ex);
}
}
/// <summary>
/// Delete a library card.
/// </summary>
/// <param name="LibraryCardId">GUID of library card.</param>
/// <param name="libraryCard">Requesting JSON model fields:
///
/// libraryCardId | Required.
/// studentId | Required, GUID of owner student
/// student | Can be missed. Student will be loaded automatically.
/// </param>
/// <remarks>
/// Sample request:
///
/// DELETE api/librarycards/3fa85f64-5717-4562-b3fc-2c963f66afa6
/// {
/// "libraryCardId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "studentId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// }
/// </remarks>
/// <response code="204">**No Content**. Library card was deleted.</response>
/// <response code="400">**Bad Request**. Model is not valid or null.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpDelete("{LibraryCardId}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult DeleteBook(Guid LibraryCardId, [FromBody] LibraryCardPL libraryCard)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
libraryCard.LibraryCardId = LibraryCardId;
var newLibraryCard = mapper.Map<LibraryCardDto>(libraryCard);
libraryCardsService.DeleteLibraryCard(newLibraryCard);
return StatusCode(204, "Library card was deleted");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Library card is not deleted. Exception message: " + ex);
}
}
#endregion
#region Library Card Fields stuff
/// <summary>
/// Get fields for specified library card.
/// </summary>
/// <param name="LibraryCardId">GUID of library card.</param>
/// <response code="200">**Success**. Return specified library card fields.</response>
/// <response code="404">**Not Found**. Specified library card fields not found.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpGet("{LibraryCardId}/fields")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public IActionResult GetFields(Guid LibraryCardId)
{
try
{
var fields = libraryCardsService.GetFields(LibraryCardId);
if (fields == null || fields.Count() < 1)
{
return StatusCode(404, "No fields found for this library card");
}
else
{
return Ok(mapper.Map<IEnumerable<LibraryCardFieldPL>>(fields));
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Cannot get list of fields. Error message: " + ex);
}
}
/// <summary>
/// Get specified library card field by Id.
/// </summary>
/// <param name="FieldId">GUID of field.</param>
/// /// <response code="200">**Success**. Return specified library card field.</response>
/// <response code="404">**Not Found**. Specified library card field not found.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpGet("fields/{FieldId}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public IActionResult GetFieldsById(Guid FieldId)
{
try
{
var field = libraryCardsService.GetFieldById(FieldId);
if (field == null)
{
return StatusCode(204, "Cannot find library card field with id[" + FieldId + "]");
}
else
{
return Ok(mapper.Map<LibraryCardFieldPL>(field));
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Cannot get list of fields. Error message: " + ex);
}
}
/// <summary>
/// Add field to specified library card.
/// </summary>
/// <param name="LibraryCardId">GUID of library card.</param>
/// <param name="field">Requesting JSON model fields:
///
/// id | Can be missed. New Id will be generated by server.
/// issueDate | Required, date
/// returnDate | Should be missed or null.
/// book | Must contain bookId, other can be missed.
/// libraryCard | Must contain libraryCardId, other can be missed.
/// </param>
/// <remarks>
/// Sample request:
///
/// POST api/librarycards/3fa85f64-5717-4562-b3fc-2c963f66afa6/fields
/// {
/// "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "issueDate": "10-10-2010",
/// "book": {
/// "bookId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// },
/// "libraryCard": {
/// "libraryCardId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// }
/// }
/// </remarks>
/// <response code="201">**Created**. Library card field was created.</response>
/// <response code="400">**Bad Request**. Model is not valid or null.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpPost("{LibraryCardId}/fields")]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult AddField(Guid LibraryCardId, [FromBody] LibraryCardFieldPL field)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
field.Id = Guid.NewGuid();
field.LibraryCard.LibraryCardId = LibraryCardId;
var newField = mapper.Map<LibraryCardFieldDto>(field);
libraryCardsService.AddField(newField);
return StatusCode(201, "Library card field was added");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Library card field is not added. Exception message: " + ex);
}
}
/// <summary>
/// Update specified library card field.
/// </summary>
/// <param name="FieldId"></param>
/// <param name="field">Requesting JSON model fields:
///
/// id | Required.
/// issueDate | Required, date
/// returnDate | Required, date
/// book | Must contain bookId, other can be missed.
/// libraryCard | Must contain libraryCardId, other can be missed.
/// </param>
/// <remarks>
/// Sample request:
///
/// PUT api/librarycards/fields/3fa85f64-5717-4562-b3fc-2c963f66afa6
/// {
/// "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "issueDate": "10-10-2010",
/// "returnDate": "10-10-2010",
/// "book": {
/// "bookId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// },
/// "libraryCard": {
/// "libraryCardId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// }
/// }
/// </remarks>
/// <response code="204">**No Content**. Library card field was updated.</response>
/// <response code="400">**Bad Request**. Model is not valid or null.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpPut("fields/{FieldId}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult UpdateField(Guid FieldId, [FromBody] LibraryCardFieldPL field)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
field.Id = FieldId;
var newField = mapper.Map<LibraryCardFieldDto>(field);
libraryCardsService.UpdateField(newField);
return StatusCode(204, "Library card field was updated");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Library card field is not updated. Exception message: " + ex);
}
}
/// <summary>
/// Delete specified library card field.
/// </summary>
/// <param name="FieldId"></param>
/// <param name="field">Requesting JSON model fields:
///
/// id | Required.
/// issueDate | Required, date
/// returnDate | Required, date
/// book | Must contain bookId, other can be missed.
/// libraryCard | Must contain libraryCardId, other can be missed.
/// </param>
/// <remarks>
/// Sample request:
///
/// PUT api/librarycards/fields/3fa85f64-5717-4562-b3fc-2c963f66afa6
/// {
/// "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "issueDate": "10-10-2010",
/// "returnDate": "10-10-2010",
/// "book": {
/// "bookId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// },
/// "libraryCard": {
/// "libraryCardId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
/// }
/// }
/// </remarks>
/// <response code="204">**No Content**. Library card field was deleted.</response>
/// <response code="400">**Bad Request**. Model is not valid or null.</response>
/// <response code="500">**Server Error**. Internal server error.</response>
/// <returns></returns>
[HttpDelete("fields/{FieldId}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult DeleteField(Guid FieldId, [FromBody] LibraryCardFieldPL field)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
field.Id = FieldId;
var newField = mapper.Map<LibraryCardDto>(field);
libraryCardsService.DeleteLibraryCard(newField);
return StatusCode(204, "Library card field was deleted");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Library card field is not deleted. Exception message: " + ex);
}
}
#endregion
}
} |
using System.Collections.Generic; using System;
using System.Text;
using BrainDuelsLib.utils.json;
using System;
using UnityEngine;
namespace BrainDuelsLib.model.entities
{
public class User : Entity
{
public String login { get; set; }
public int id { get; set; }
public int rank { get; set; }
public User()
{
}
public String GetRankString()
{
return GetRankString(rank);
}
public static String GetRankString(int val)
{
if (val > 0)
{
return val + "d";
}
else
{
int kyu = -val + 1;
return kyu + "k";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;
namespace QI.WikiScraping.Api.Infrastructure.Models.ApiExplorerQi
{
/// <summary>
/// Option pattern to apply configurations based Versioning and OpenApi implementation
/// </summary>
public class ApiVersioningSwaggerOptionsQi
{
/// <summary>
/// The assembly containing the metadata of ApiProject that is wanted to be exposed.
/// </summary>
public Assembly ApiAssembly { get; set; } = null;
#region Versionning
/// <summary>
/// This means, for OpenApi versioning , it will looks for a letter 'v', followed by major and minor version. IE: v1, v1.0, v2, v2.0, etc.
/// </summary>
public string GroupNameFormat { get; set; } = "'v'VV";
/// <summary>
/// Gets or sets a value indicating whether a default version is assumed when a client
/// does does not provide a service API version.</summary>
public bool AssumeDefaultVersionWhenUnspecified { get; set; } = true;
/// <summary>
/// Gets or sets the default API version applied to services that do not have explicit
/// versions.</summary>
public ApiVersion DefaultApiVersion { get; set; } = new ApiVersion(1, 0);
/// <summary>
/// Gets or sets a value indicating whether requests report the service API version
/// compatibility information in responses.
/// </summary>
/// <remarks>
/// When this property is set to true, the HTTP headers "api-supported-versions"
///and "api-deprecated-versions" will be added to all valid service routes.This
///information is useful for advertising which versions are supported and scheduled
///for deprecation to clients.This information is also useful when supporting the
///OPTIONS verb.
///By setting this property to true, the Microsoft.AspNetCore.Mvc.ReportApiVersionsAttribute
///will be added a global action filter. To enable more granular control over when
///service API versions are reported, apply the Microsoft.AspNetCore.Mvc.ReportApiVersionsAttribute
///on specific controllers or controller actions.
///
/// </remarks>
public bool ReportApiVersions { get; set; } = true;
#endregion
#region Swagger
/// <summary>
/// Dictionary with the Key/Value pairs related to Headers and Values of those headers that we want to wxpose to swagger UI.
/// </summary>
/// <code>
/// var headerSamplesKeyValues = new Dictionary<string, object>() {
/// { "HeaderKey1", "HeaderValue1" },
/// { "HeaderKey2", "HeaderValue2" },
/// { "HeaderKey3", "HeaderValue3" },
/// { "HeaderKey4", "HeaderValue4" }
/// };
/// </code>
public Dictionary<string, object> HeaderSamplesKeyValues { get; set; } = null;
/// <summary>
/// OpenApi contact Information
/// </summary>
public OpenApiContact SwaggerContactOpenApiInfo { get; set; } = null;
/// <summary>
/// OpenApi License Information
/// </summary>
public OpenApiLicense SwaggerLicenseOpenApiInfo { get; set; } = null;
/// <summary>
/// OpenApi Term Of Service Information
/// </summary>
public Uri SwaggerTermOfServiceOpenApiInfo { get; set; } = null;
#endregion
}
}
|
using GeniyIdiot.Common;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace GeniyIdiotWinFormsApp
{
public partial class GetCurrentUserName : Form
{
private User newUser;
public GetCurrentUserName(User user)
{
InitializeComponent();
newUser = user;
}
private void GetCurrentUserName_Load(object sender, EventArgs e)
{
}
private void nextButton_Click(object sender, EventArgs e)
{
var newUserName = IsValid();
if (newUserName != userNameTextBox.Text)
{
MessageBox.Show(newUserName, "Неверный формат!");
userNameTextBox.Clear();
userNameTextBox.Focus();
return;
}
else if (newUserName == "Админ")
{
addNewQuestionButton.Enabled = true;
return;
}
else
{
newUser.Name = newUserName;
userNameTextBox.Clear();
userNameTextBox.Focus();
this.Close();
}
}
private string IsValid()
{
var output = User.CheckName(userNameTextBox.Text);
if (output != userNameTextBox.Text)
{
return output;
}
else
{
return userNameTextBox.Text;
}
}
private void addNewQuestionButton_Click(object sender, EventArgs e)
{
var addNewQuestionForm = new addNewQuestionForm();
addNewQuestionForm.ShowDialog();
userNameTextBox.Clear();
userNameTextBox.Focus();
}
private void seeAllUsersResultsButton_Click(object sender, EventArgs e)
{
var getAllUsersResultsForm = new GetAllUsersResultsForm();
getAllUsersResultsForm.ShowDialog();
}
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using KaVE.Commons.Utils.Assertion;
using KaVE.VS.FeedbackGenerator.Utils;
using NUnit.Framework;
namespace KaVE.VS.FeedbackGenerator.Tests.Utils
{
internal class InverseBoolConverterTest
{
[TestCase(true),
TestCase(false)]
public void ShouldInvert(bool value)
{
var converter = new InverseBoolConverter();
var result = converter.Convert(value, null, null, null);
Assert.AreEqual(!value, result);
}
[TestCase(true),
TestCase(false)]
public void ShouldInvertBack(bool value)
{
var converter = new InverseBoolConverter();
var result = converter.ConvertBack(value, null, null, null);
Assert.AreEqual(!value, result);
}
[Test, ExpectedException(typeof (AssertException))]
public void ShouldFailToConvertNonBool()
{
var converter = new InverseBoolConverter();
converter.Convert(new object(), null, null, null);
}
[Test, ExpectedException(typeof (AssertException))]
public void ShouldFailToConvertBackNonBool()
{
var converter = new InverseBoolConverter();
converter.ConvertBack(new object(), null, null, null);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2do_Proyecto_Analisis
{
class Aula
{
string nombre;
List<int[]> horasRestringidas;
public Aula(string nombre)
{
this.nombre = nombre;
this.horasRestringidas = new List<int[]>();
}
public void añadirIntervaloHoraRestringida(int inicio, int fin)
{
int[] horaRestringida = new int[2];
horaRestringida[0] = inicio;
horaRestringida[1] = fin;
horasRestringidas.Add(horaRestringida);
}
public bool horavalida(int hora)
{
for (int i = 0; i < horasRestringidas.Count; i++)
{
if (hora>=horasRestringidas[i][0] && hora<=horasRestringidas[i][1])
{
return false;
}
}
return true;
}
public string getNombre()
{
return nombre;
}
}
}
|
using System;
public class FibonacciGenerator
{
public static void Main(string[] args)
{
int n1=0,n2=1,n3=1,number;
Console.Write("Enter the number of elements: ");
number = int.Parse(Console.ReadLine());
Console.Write(n1+" "+n2+" ");
n3=fibonacciCalculator( n1,n2,n3,number);
}
public static int fibonacciCalculator(int n1, int n2, int n3,int number)
{
for(int i=2;i<number;++i)
{
n3=n1+n2;
Console.Write(n3+" ");
n1=n2;
n2=n3;
}
return n3;
}
}
|
using Microsoft.AspNetCore.Mvc;
using PlacesBeen.Models;
using System.Collections.Generic;
namespace PlacesBeen.Controllers
{
public class PlacesController : Controller
{
[HttpGet("/places")]
public ActionResult Index() //Common RESTful route name when you want to display list of all objects (GET)
{
List<Place> allPlaces = Place.GetAll();
return View(allPlaces);
}
[HttpPost("/places")]
public ActionResult Create(string cityName, string days, string travelBuddy, string dishes) //Creates a new item on the server (POST)
{
int daysStayed = int.Parse(days);
Place myPlace = new Place(cityName, daysStayed, travelBuddy, dishes);
return RedirectToAction("Index");
}
[HttpGet("/places/new")]
public ActionResult New() //Offers form to create new object (GET)
{
return View();
}
[HttpGet("/places/{id}")]
public ActionResult Show(int id)
{
Place foundPlace = Place.Find(id); //Create .Find() method in class
return View(foundPlace);
}
[HttpPost("/places/{id}")]
public ActionResult Update(int id)
{
Place foundPlace = Place.Find(id);
foundPlace.VisitAgain = true;
return RedirectToAction("Index");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using BLL.SYSTEM;
public partial class BaseData_ExpenseSet : BasePage.WebPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class WindClass
{
//TODO: maybe switch the particle systemes and wind direction arrays here
}
public class ObstacleBehaviour : MonoBehaviour {
public enum ObstacleType
{
Spikes,
SwitchableSpikes,
HomingSpikes,
Wind
};
public ObstacleType _obstacleType;
private Collider2D _objectCollider;
public float _destroyTime;
[Header("Spike Variables")]
private Vector3 _startingPos;
public bool _canFall;
private bool _hasHit;
private bool _hasLaunched;
public float _fallSpeed;
public float _secondsToLaunch;
public Transform _rayCastPosition;
public Vector2 _dir;
private RaycastHit2D _spikeRayCast;
public float _rayCastDistance;
public LayerMask _detectable;
public Vector3 _startingRotation;
public float DisappearTimer;
[Header("Switchable Spike Variables")]
[Range(0,10)]
public int _targetNum;
[Header("In between numbers")]
[Range(0, 9)]
public int _minNum;
[Range(0, 9)]
public int _maxNum;
private bool _isVisible;
public enum MathConditions
{
GreaterThan,
LessThan,
InBetween,
Equals,
GreaterThanSpike,
LessThanSpike
}
public MathConditions _mathCondition;
[Header("TextMeshes")]
[SerializeField]
private TextMesh[] _textMeshes;
[Header("Homing Spikes")]
public float _homingSpeed;
public float _rotateSpeed;
public GameObject _smokeParticle;
public ParticleSystem _jetParticle;
public GameObject _breakableWall;
private Transform _homingTarget;
public Rigidbody2D _rb2d;
public AudioClip _explosion;
[Header("Wind Variables")]
public bool _switchable;
public float _switchTime;
private float _timeTillSwitch;
private float _swtichTimeDuration;
public ParticleSystem [] _windParticleSystems;
private float ForceDirection;
public enum WindDirections
{
Right,
Up,
Left,
Down,
None
};
public WindDirections[] _windDirection;
private WindDirections _currentDirection;
private int _switchIndex;
private int _directionIndex;
private Animator _anim;
private void Start()
{
if (_anim == null)
{
_anim = GetComponent<Animator>();
}
if (_canFall || _obstacleType == ObstacleType.HomingSpikes)
{
_startingPos = transform.position;
}
if (_obstacleType == ObstacleType.HomingSpikes)
{
_startingRotation = new Vector3(transform.localEulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z);
//Debug.Log(transform.eulerAngles.z);
Invoke("GetMissileColor", 0.2f);
}
if (_obstacleType == ObstacleType.SwitchableSpikes)
{
_objectCollider = GetComponent<PolygonCollider2D>();
GetTextMesh();
}
_objectCollider = GetComponent<Collider2D>();
if (_obstacleType != ObstacleType.Wind) return;
SetWindDirection(0);
_timeTillSwitch = _switchTime;
_swtichTimeDuration = _timeTillSwitch;
}
private void GetMissileColor()
{
if (Camera.main.backgroundColor == Color.black)
{
//Debug.Log("White");
_anim.SetBool("White", true);
}
if (Camera.main.backgroundColor == Color.white)
{
_anim.SetBool("Black", true);
}
}
private void GetTextMesh()
{
switch (_mathCondition)
{
case MathConditions.GreaterThan:
{
_textMeshes[0].text = _targetNum.ToString();
_textMeshes[1].text = ">";
break;
}
case MathConditions.LessThan:
{
_textMeshes[0].text = _targetNum.ToString();
_textMeshes[1].text = "<";
break;
}
case MathConditions.InBetween:
{
_textMeshes[0].text = _maxNum.ToString();
_textMeshes[1].text = "-";
_textMeshes[2].text = _minNum.ToString();
break;
}
case MathConditions.Equals:
{
_textMeshes[0].text = _targetNum.ToString();
break;
}
case MathConditions.GreaterThanSpike:
{
_textMeshes[0].text = _targetNum.ToString();
_textMeshes[1].text = ">";
break;
}
case MathConditions.LessThanSpike:
{
_textMeshes[0].text = _targetNum.ToString();
_textMeshes[1].text = "<";
break;
}
}
}
private void Update()
{
if (_obstacleType == ObstacleType.HomingSpikes) return;
CheckObstacleType();
}
private void FixedUpdate()
{
if (_obstacleType == ObstacleType.HomingSpikes)
{
HomingSpikeBehaviour();
}
}
private void CheckObstacleType()
{
switch(_obstacleType)
{
case ObstacleType.Spikes:
{
SpikeBehaviour();
break;
}
case ObstacleType.SwitchableSpikes:
{
SwitchableSpikeBehaviour();
break;
}
case ObstacleType.HomingSpikes:
{
break;
}
case ObstacleType.Wind:
{
WindBehaviour();
break;
}
}
}
private void SpikeBehaviour()
{
if (!_canFall) return;
//if (!gameObject.activeInHierarchy) return;
_spikeRayCast = Physics2D.Raycast(_rayCastPosition.position, _dir ,_rayCastDistance, _detectable);
Debug.DrawRay(_rayCastPosition.position, _dir * _rayCastDistance, Color.red);
Moving();
if (_spikeRayCast.collider != null && transform.position == _startingPos)
{
if (!_spikeRayCast.collider.CompareTag("Player")) return;
if (!_hasHit)
{
_hasHit = true;
StartCoroutine(Launch(_secondsToLaunch));
_anim.SetBool("IsActivated", true);
if (transform.parent != null)
{
transform.parent = null;
}
//Debug.Log("Hit");
}
}
}
private void SwitchableSpikeBehaviour()
{
_anim.SetBool("IsVisible", _isVisible);
_objectCollider.enabled = _isVisible ? true : false;
CheckTextColor(_isVisible);
switch (_mathCondition)
{
case MathConditions.GreaterThan:
{
_isVisible = GameplayManager.instance._numOfJumps >= _targetNum ? true : false;
break;
}
case MathConditions.LessThan:
{
_isVisible = GameplayManager.instance._numOfJumps <= _targetNum ? true : false;
break;
}
case MathConditions.InBetween:
{
_isVisible = GameplayManager.instance._numOfJumps >= _minNum && GameplayManager.instance._numOfJumps <= _maxNum ? true : false;
break;
}
case MathConditions.Equals:
{
if (_targetNum != 0)
{
_isVisible = GameplayManager.instance._numOfJumps == _targetNum ? true : false;
}
else
{
//_isVisible = GameplayManager.instance._numOfJumps == 0 ? true : false;
}
break;
}
case MathConditions.GreaterThanSpike:
{
_isVisible = GameplayManager.instance._numOfJumps > _targetNum ? true : false;
break;
}
case MathConditions.LessThanSpike:
{
_isVisible = GameplayManager.instance._numOfJumps < _targetNum ? true : false;
break;
}
}
}
private void HomingSpikeBehaviour()
{
_spikeRayCast = Physics2D.Raycast(_rayCastPosition.position, _dir, _rayCastDistance, _detectable);
Debug.DrawRay(_rayCastPosition.position, _dir * _rayCastDistance, Color.red);
if (_spikeRayCast.collider != null && transform.position == _startingPos)
{
if (!_spikeRayCast.collider.CompareTag("Player")) return;
if (!_hasHit)
{
_hasHit = true;
//StartCoroutine(Launch(_secondsToLaunch));
//_anim.SetBool("IsActivated", true);
if (transform.parent != null)
{
transform.parent = null;
}
_homingTarget = _spikeRayCast.collider.gameObject.transform;
//Debug.Log("Hit");
}
}
if (transform.position != _startingPos)
{
if (_breakableWall != null)
{
float _distance = Vector3.Distance(transform.position, _breakableWall.transform.position);
if (_distance <= 6f)
{
_homingTarget = _breakableWall.transform;
}
}
}
if (_homingTarget != null && GetComponent<SpriteRenderer>().enabled)
{
Vector2 direction = (Vector2)_homingTarget.position - _rb2d.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, transform.up).z;
_rb2d.angularVelocity = -rotateAmount * _rotateSpeed;
_rb2d.velocity = transform.up * _homingSpeed;
//Debug.Log("Homing in");
_anim.SetBool("Launched", true);
if (!_jetParticle.isPlaying)
{
_jetParticle.Play();
//Debug.Log("Go");
}
}
}
public void ResetSpike()
{
if (_obstacleType == ObstacleType.Spikes)
{
if (!_canFall) return;
_hasLaunched = false;
_objectCollider.enabled = true;
GetComponent<SpriteRenderer>().enabled = true;
transform.position = _startingPos;
_anim.SetBool("IsActivated", false);
}
if (_obstacleType == ObstacleType.HomingSpikes)
{
GetComponent<SpriteRenderer>().enabled = true;
GetComponent<Collider2D>().enabled = true;
transform.position = _startingPos;
transform.eulerAngles = _startingRotation;
_homingTarget = null;
_jetParticle.Play();
//_rb2d.velocity = Vector3.zero;
_rb2d.Sleep();
_anim.SetBool("Launched", false);
}
_hasHit = false;
}
public void ResetWind()
{
if (!_switchable) return;
SetWindDirection(0);
_directionIndex = 0;
_timeTillSwitch = _swtichTimeDuration;
GetComponent<AreaEffector2D>().forceAngle = forceAngle();
_windParticleSystems[1].Stop();
for (int i = 0; i < _windParticleSystems.Length; i++)
{
_windParticleSystems[i].Clear();
}
}
private void WindBehaviour()
{
if (!_switchable) return;
_timeTillSwitch -= Time.deltaTime;
if (_timeTillSwitch < 0)
{
_timeTillSwitch = _swtichTimeDuration;
SetParticleWind();
}
}
private IEnumerator Launch(float _seconds)
{
yield return new WaitForSeconds(_seconds);
if (_anim.GetBool("IsActivated"))
{
_anim.SetBool("IsActivated", false);
_hasLaunched = true;
StartCoroutine(Disappear(DisappearTimer));
}
}
private IEnumerator Disappear(float _seconds)
{
yield return new WaitForSeconds(_seconds);
if (transform.position != _startingPos)
{
if (GetComponent<SpriteRenderer>().enabled)
{
transform.position = _startingPos;
_objectCollider.enabled = false;
GetComponent<SpriteRenderer>().enabled = false;
GetComponent<Collider2D>().enabled = false;
//gameObject.SetActive(false);
}
}
}
private void Moving()
{
if (!_hasLaunched) return;
if (GetComponent<SpriteRenderer>().enabled)
{
transform.position += ((Vector3)_dir) * _fallSpeed * Time.deltaTime;
}
}
private void SetParticleWind()
{
//ForceDirection = _windParticleSystem01.isPlaying ? ForceDirection * 1 : ForceDirection * -1;
_directionIndex++;
if (_directionIndex > _windDirection.Length - 1)
{
_directionIndex = 0;
}
SetWindDirection(_directionIndex);
GetComponent<AreaEffector2D>().forceAngle = forceAngle();
}
private void SetWindDirection(int _index)
{
/* if (_index > _windDirection.Length)
{
_directionIndex = 0;
Debug.Log("Back to zero");
_index = _directionIndex;
}*/
for (int i = 0; i < _windParticleSystems.Length; i++)
{
if (_index == 0)
{
_windParticleSystems[_index].Play();
break;
}
if (i < _index)
{
_windParticleSystems[i].Stop();
}
else if (i == _index)
{
_windParticleSystems[i].Play();
break;
}
}
_currentDirection = _windDirection[_index];
if (_currentDirection != WindDirections.None)
{
GetComponent<AreaEffector2D>().enabled = true;
if (_index != 0)
{
_windParticleSystems[1].Play();
}
}
else
{
for (int i = 0; i < _windParticleSystems.Length; i++)
{
_windParticleSystems[i].Stop();
}
}
}
private float forceAngle()
{
ForceDirection = 0f;
switch(_currentDirection)
{
case WindDirections.Right:
{
ForceDirection = 0f;
break;
}
case WindDirections.Up:
{
ForceDirection = 90f;
break;
}
case WindDirections.Left:
{
ForceDirection = 180f;
break;
}
case WindDirections.Down:
{
ForceDirection = 270f;
break;
}
case WindDirections.None:
{
GetComponent<AreaEffector2D>().enabled = false;
break;
}
}
return ForceDirection;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (_obstacleType == ObstacleType.Spikes || _obstacleType == ObstacleType.SwitchableSpikes || _obstacleType == ObstacleType.HomingSpikes)
{
if (collision.collider.CompareTag("Player"))
{
if (_obstacleType == ObstacleType.HomingSpikes)
{
GetComponent<SpriteRenderer>().enabled = false;
_rb2d.velocity = Vector3.zero;
_rb2d.freezeRotation = true;
Invoke("UnfreezeRotation", 0.5f);
}
StartCoroutine(GameplayManager.instance.ActivatePlayerDeath());
}
int _player = LayerMask.NameToLayer("Player");
int _geometry = LayerMask.NameToLayer("Geometry");
int _pushableGeometry = LayerMask.NameToLayer("Pushable Geometry");
//TODO: rework this for the homing missle
if (_hasLaunched && (collision.gameObject.layer == _player || collision.gameObject.layer == _geometry || collision.gameObject.layer == _pushableGeometry))
{
//Debug.Log(collision.gameObject.name);
StartCoroutine(Disappear(0.1f));
if (collision.gameObject.layer == _player)
{
if (collision.gameObject.activeInHierarchy)
{
//collision.gameObject.transform.parent = null;
//collision.gameObject.SetActive(false);
}
}
StartCoroutine(Disappear(0.5f));
}
if (collision.collider.tag == "Ground")
{
StartCoroutine(Disappear(0.1f));
}
}
if (_obstacleType == ObstacleType.HomingSpikes)
{
if(collision.collider.CompareTag("Breakable") || collision.collider.CompareTag("Pushable") || collision.collider.CompareTag("Player") || collision.collider.CompareTag("Ground") || collision.collider.CompareTag("Spike"))
{
//Debug.Log("Hit");
GameObject _smokeExplosion = Instantiate(_smokeParticle,transform.position,Quaternion.identity) as GameObject;
collision.gameObject.GetComponent<Collider2D>().enabled = false;
gameObject.GetComponent<Collider2D>().enabled = false;
if (collision.collider.CompareTag("Player") || collision.collider.CompareTag("Pushable"))
{
collision.gameObject.GetComponent<SpriteRenderer>().enabled = false;
GameplayManager.instance.RestCoins();
if (collision.collider.CompareTag("Pushable"))
{
GameplayManager.instance._inGamePlayer.GetComponent<PlayerScript>().ResetPushing();
}
}
if (collision.collider.CompareTag("Breakable"))
{
collision.gameObject.GetComponent<ObjectBehaviour>().DestroyBreakableWall();
}
gameObject.GetComponent<SpriteRenderer>().enabled = false;
gameObject.GetComponent<SpriteRenderer>().enabled = false;
_jetParticle.Stop();
AudioManager.instance.PlaySFX(_explosion);
GameplayManager.instance.ShakeCamera(1f, 1f);
ParticleSystem _explosionParticle = _smokeExplosion.GetComponent<ParticleSystem>();
var main = _explosionParticle;
main.startColor = Camera.main.backgroundColor == Color.black ? Color.white : Color.black;
}
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (_obstacleType == ObstacleType.Spikes || _obstacleType == ObstacleType.SwitchableSpikes || _obstacleType == ObstacleType.HomingSpikes)
{
if (collision.collider.CompareTag("Player"))
{
if (_obstacleType == ObstacleType.HomingSpikes)
{
GetComponent<SpriteRenderer>().enabled = false;
_rb2d.velocity = Vector3.zero;
_rb2d.freezeRotation = true;
Invoke("UnfreezeRotation", 0.5f);
}
StartCoroutine(GameplayManager.instance.ActivatePlayerDeath());
}
int _geometry = LayerMask.NameToLayer("Geometry");
int _pushableGeometry = LayerMask.NameToLayer("Pushable Geometry");
//TODO: rework this for the homing missle
if (_hasLaunched && (collision.gameObject.layer == _geometry || collision.gameObject.layer == _pushableGeometry))
{
//Debug.Log(collision.gameObject.name);
StartCoroutine(Disappear(0f));
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
/*if (collision.CompareTag("Player"))
{
GameplayManager.instance.ResetScene();
}*/
int _geometry = LayerMask.NameToLayer("Geometry");
int _pushableGeometry = LayerMask.NameToLayer("Pushable Geometry");
if (_hasLaunched && (collision.gameObject.layer == _geometry || collision.gameObject.layer == _pushableGeometry))
{
//Debug.Log(collision.gameObject.name);
StartCoroutine(Disappear(0f));
}
}
private void UnfreezeRotation()
{
if (_obstacleType != ObstacleType.HomingSpikes)
{
GetComponent<SpriteRenderer>().enabled = true;
}
_rb2d.freezeRotation = false;
}
private void CheckTextColor(bool isVisible)
{
if (GetComponent<CheckColor>()._camColor == Color.white)
{
switch (_textMeshes.Length)
{
case 1:
{
_textMeshes[0].color = isVisible ? Color.white : Color.black;
break;
}
case 2:
{
_textMeshes[0].color = isVisible ? Color.white : Color.black;
_textMeshes[1].color = isVisible ? Color.white : Color.black;
break;
}
case 3:
{
_textMeshes[0].color = isVisible ? Color.white : Color.black;
_textMeshes[1].color = isVisible ? Color.white : Color.black;
_textMeshes[2].color = isVisible ? Color.white : Color.black;
break;
}
}
}
else
{
switch (_textMeshes.Length)
{
case 1:
{
_textMeshes[0].color = isVisible ? Color.black : Color.white;
break;
}
case 2:
{
_textMeshes[0].color = isVisible ? Color.black : Color.white;
_textMeshes[1].color = isVisible ? Color.black : Color.white;
break;
}
case 3:
{
_textMeshes[0].color = isVisible ? Color.black : Color.white;
_textMeshes[1].color = isVisible ? Color.black : Color.white;
_textMeshes[2].color = isVisible ? Color.black : Color.white;
break;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.