text stringlengths 13 6.01M |
|---|
using GesCMS.Core.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GesCMS.Application.Common.Interfaces
{
public interface IApplicationDbContext
{
public DbSet<Core.Entities.Page> Page { get; set; }
public DbSet<Widget> Widget { get; set; }
public DbSet<WidgetInPagePriority> WidgetInPagePriority { get; set; }
public DbSet<WidgetsInPage> WidgetsInPage { get; set; }
public DbSet<WidgetValue> WidgetValue { get; set; }
public DbSet<WebTheme> WebTheme { get; set; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
}
|
using System.Drawing;
namespace Layout
{
public class Textbox : Box
{
/******** Variables ********/
public Anchor textAnchor;
public bool boxAdaptive;
public string text;
public Font font;
public Brush textBrush;
protected Point textPosition;
private int _padding;
private static Textbox savedStyle;
// Default values.
public static bool defaultBoxAdaptive = true;
public static int defaultPadding = 5;
public static Font defaultFont = new Font("ARIAL", 12);
public static Brush defaultTextBrush = Brushes.Black;
public static Brush defaultFill = (Brush)Layout.defaultFill.Clone();
public static Pen defaultBorderline = (Pen)Layout.defaultBorderLine.Clone();
public static Anchor defaultAnchor = Anchor.None;
public static Anchor defaultTextAnchor = Anchor.None;
/******** Getter & Setter ********/
// Padding must not become negative
public int padding
{
get { return (_padding); }
set
{
if (value < 0) _padding = 0;
else _padding = value;
}
}
/******** Functions ********/
/// <summary>
/// Constructs a Textbox object with the given parameters.
/// </summary>
/// <param name="text">The text to show within the textbox.</param>
/// <param name="area">The area the textbox should cover.</param>
/// <param name="fill">The brush used to fill the inner of the textbox.</param>
/// <param name="borderLine">The pen used to outline the textbox.</param>
/// <param name="identifier">Identifier string for element, defaults to empty string.</param>
public Textbox(string text, Rectangle area, Brush fill, Pen borderLine, string identifier = "")
: base(area, fill, borderLine, identifier)
{
this.text = text;
textPosition = area.Location;
boxAdaptive = defaultBoxAdaptive;
padding = defaultPadding;
anchor = defaultAnchor;
textAnchor = defaultTextAnchor;
textBrush = defaultTextBrush;
font = defaultFont;
}
/// <summary>
/// Constructor using standard layout values for box.
/// </summary>
/// <param name="text">The text to show within the textbox.</param>
/// <param name="area">The area the textbox should cover.</param>
/// <param name="identifier">Identifier string for element, defaults to empty string.</param>
public Textbox(string text, Rectangle area, string identifier = "")
: this(text, area, defaultFill, defaultBorderline, identifier)
{ }
/// <summary>
/// Standard constructor.
/// </summary>
/// <param name="identifier">Identifier string for element, defaults to empty string.</param>
public Textbox(string identifier = "")
: this("", new Rectangle(), identifier)
{ }
/// <summary>
/// Updates the textbox.
/// </summary>
public override void Update()
{
base.Update();
}
/// <summary>
/// Draws the box to the given graphics object.
/// </summary>
/// <param name="g">The graphics object to render to.</param>
public override void Draw(Graphics g)
{
if (!visible) return;
// Need to calculate the position of the text here,
// because the graphics object is needed.
if (boxAdaptive) AdaptToContent(g);
anchor = anchor;
base.Draw(g);
#warning Deal with it!
StringFormat format = StringFormat.GenericTypographic;
format.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
textPosition = area.Location;
textPosition.X += padding;
textPosition.Y += padding;
SetTextAnchor(g, textAnchor);
g.DrawString(text, font, textBrush, textPosition, format);
}
/// <summary>
/// Adapts the size of the box to its content.
/// </summary>
/// <param name="g">The graphics object used to determine the size of the box's content.</param>
/// <param name="content">Content to which the box should adapt. Defaults to null, which is interpreted as the currently displayed text.</param>
protected void AdaptToContent(Graphics g, string content = null)
{
if (content == null) content = text;
Size textSize = GetTextSize(g, content);
width = textSize.Width + 2 * padding;
height = textSize.Height + 2 * padding;
textPosition = area.Location;
textPosition.X += padding;
textPosition.Y += padding;
}
/// <summary>
/// You may center the text similar to the box itself.
/// You may combine the anchors using the | operator.
/// Combining the top, left, right and bottom anchor will result in centering the element.
/// </summary>
/// <param name="g">The graphics object used to determine the textsize.</param>
/// <param name="anchor">An anchor object determining the relative position of the text wihin the box.</param>
#warning Ambiguous to Textbox.textAnchor
private void SetTextAnchor(Graphics g, Anchor anchor)
{
Size textSize = GetTextSize(g);
// Aligned right.
if ((anchor & Anchor.Right) == Anchor.Right)
{
textPosition.X = absoluteX + width - textSize.Width - padding;
}
// Aligned Down.
if ((anchor & Anchor.Bottom) == Anchor.Bottom)
{
textPosition.Y = absoluteY + height - textSize.Height - padding;
}
// Aligned left.
if ((anchor & Anchor.Left) == Anchor.Left)
{
textPosition.X = absoluteX + padding;
}
// Aligned up.
if ((anchor & Anchor.Top) == Anchor.Top)
{
textPosition.Y = absoluteY + padding;
}
// Box centered on x axis.
if ((anchor & Anchor.CenterX) == Anchor.CenterX)
{
textPosition.X = (int)((float)absoluteX + ((float)width / 2.0) - ((float)textSize.Width / 2.0));
}
// Box centered on y axis.
if ((anchor & Anchor.CenterY) == Anchor.CenterY)
{
textPosition.Y = absoluteY + (height / 2) - (textSize.Height / 2);
}
this.textAnchor = anchor;
}
/// <summary>
/// Returns the size of the currently saved text.
/// </summary>
/// <param name="g">The graphics object used to determine the size of the given string.</param>
/// <param name="text">The string of interest. Defaults to null, which will get the size of the currently displayed text.</param>
/// <returns>The size of the specified text.</returns>
protected Size GetTextSize(Graphics g, string text = null)
{
if (text == null) text = this.text;
#warning Deal with it!
StringFormat format = StringFormat.GenericTypographic;
format.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
#warning Not independent of program
Size size = g.MeasureString(text, font, RectangleGame.Program.mainForm.ClientSize.Width, format).ToSize();
return (size);
}
/// <summary>
/// Saves the current default textbox style to restore it later on.
/// </summary>
public static void SaveDefaultStyle()
{
savedStyle = new Textbox();
savedStyle.boxAdaptive = defaultBoxAdaptive;
savedStyle.padding = defaultPadding;
savedStyle.font = defaultFont;
savedStyle.textBrush = defaultTextBrush;
savedStyle.fill = defaultFill;
savedStyle.borderLine = defaultBorderline;
savedStyle.anchor = defaultAnchor;
savedStyle.textAnchor = defaultTextAnchor;
}
/// <summary>
/// Restores the currently saved default textbox style, if there is one saved.
/// </summary>
/// <returns>Boolean variable indicating if the default style has been restored successfully.</returns>
public static bool RestoreDefaultStyle()
{
if (savedStyle == null) return (false);
defaultBoxAdaptive = savedStyle.boxAdaptive;
defaultPadding = savedStyle.padding;
defaultFont = savedStyle.font;
defaultTextBrush = savedStyle.textBrush;
defaultFill = savedStyle.fill;
defaultBorderline = savedStyle.borderLine;
defaultAnchor = savedStyle.anchor;
defaultTextAnchor = savedStyle.textAnchor;
return (true);
}
}
} |
using System;
using System.Data.Entity;
using System.Linq;
using ApartmentApps.Api.Modules;
using ApartmentApps.Data;
namespace ApartmentApps.Api
{
public class MaintenanceRepository : PropertyRepository<MaitenanceRequest>
{
private MaintenanceConfig _config;
public MaintenanceRepository(IModuleHelper moduleHelper, Func<IQueryable<MaitenanceRequest>, IDbSet<MaitenanceRequest>> includes, DbContext context, IUserContext userContext) : base(moduleHelper, includes, context, userContext)
{
}
public MaintenanceRepository(IModuleHelper moduleHelper, DbContext context, IUserContext userContext) : base(moduleHelper, context, userContext)
{
}
public MaintenanceConfig Config => _config ?? (_config = UserContext.GetConfig<MaintenanceConfig>());
public override IQueryable<MaitenanceRequest> GetAll()
{
var result = base.GetAll();
if (Config.SupervisorMode)
{
if (UserContext.IsInRole("Admin") || UserContext.IsInRole("MaintenanceSupervisor") || UserContext.IsInRole("PropertyAdmin"))
{
return result;
}
var id = UserContext.UserId;
return result.Where(x => x.WorkerAssignedId == id);
}
return result;
}
public override IQueryable<MaitenanceRequest> Includes(IDbSet<MaitenanceRequest> set)
{
return set.Include(p => p.User).Include(p=>p.MaitenanceRequestType).Include(p=>p.Unit);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PriestsAndDevils;
// 工厂模式
public class DiskFactory : MonoBehaviour, IActionManager
{
private List<Disk> toDelete = new List<Disk>();
private List<Disk> toUse = new List<Disk>();
public Color[] colors = {Color.white,Color.yellow,Color.red,Color.blue,Color.green,Color.black};//可选颜色
public GameObject GetDisk(int round,ActionMode mode){//根据回合数对飞碟设置属性并返回
GameObject newDisk = null;
if (toUse.Count > 0){
newDisk = toUse[0].gameObject;
toUse.Remove(toUse[0]);
}else{
newDisk = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Prefabs/disk"), Vector3.zero, Quaternion.identity);
newDisk.AddComponent<Disk>();
}
//commonProperities();
if (mode == ActionMode.PHYSICS){
newDisk.AddComponent<Rigidbody>();
newDisk.GetComponent<Rigidbody>().AddForce(Vector3.down * 9.8f, ForceMode.Acceleration);
}
// 飞碟的速度为round*7
newDisk.GetComponent<Disk>().speed = 7.0f * round;
// 飞碟随round越来越小
newDisk.GetComponent<Disk>().size = (1 - round*0.1f);
// 飞碟颜色随机
int color = UnityEngine.Random.Range(0, 6);//共有六种颜色
newDisk.GetComponent<Disk>().color = colors[color];
// 飞碟的发射方向
float RanX = UnityEngine.Random.Range(-1, 3) < 1 ? -1 : 1;//-1,0则为负方向,1,2则为正方向
newDisk.GetComponent<Disk>().direction = new Vector3(-RanX, UnityEngine.Random.Range(-2f, 2f), 0);
// 飞碟的初始位置
newDisk.GetComponent<Disk>().position = new Vector3(RanX*13, UnityEngine.Random.Range(-2f, 2f), UnityEngine.Random.Range(-1f, 1f));
toDelete.Add(newDisk.GetComponent<Disk>());
newDisk.SetActive(false);
newDisk.name = newDisk.GetInstanceID().ToString();
return newDisk;
}
public void FreeDisk(GameObject disk){
Disk cycledDisk = null;
foreach (Disk toCycle in toDelete){
if (disk.GetInstanceID() == toCycle.gameObject.GetInstanceID()){
cycledDisk = toCycle;
}
}
if (cycledDisk != null){
cycledDisk.gameObject.SetActive(false);
toUse.Add(cycledDisk);
toDelete.Remove(cycledDisk);
}
}
} |
using UnityAtoms.SceneMgmt;
namespace UnityAtoms.SceneMgmt
{
/// <summary>
/// Action of type `SceneField`. Inherits from `AtomAction<SceneField>`.
/// </summary>
[EditorIcon("atom-icon-purple")]
public abstract class SceneFieldAction : AtomAction<SceneField> { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplicationBlog_DejanSavanovic.Models
{
public class PocetnaViewModel
{
public List<SelectListItem> Drzave { get; set; }
public List<TopPetBlogovaViewModel> TopPetBlogova { get; set; }
public List<TopPetAutoraViewModel> TopPetAutora { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FRCTeam16TargetTracking
{
public static class GlobalConstants
{
public static int TargetXPosition = 320; // 640/2
public static int TargetYPosition = 240; // 480/2
}
}
|
using RomashkaBase.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace RomashkaBase.Model
{
public class Company : BasePropertyChanged
{
private int _id;
private string _name;
private ContractStatus _contractStatus;
public int Id {
get => _id;
set {
_id = value;
OnPropertyChanged();
} }
public string Name {
get => _name;
set {
_name = value;
OnPropertyChanged();
}
}
public ContractStatus ContractStatus {
get => _contractStatus;
set {
_contractStatus = value;
OnPropertyChanged();
}
}
public List<User> Users { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetHealth : MonoBehaviour {
public float health = 10f;
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
NPCRadius.passed = true;
}
health = 10;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BugTracker.Entities
{
class Venta
{
public int NroComprobante { get; set; }
public DateTime Fecha { get; set; }
public int Empleado { get; set; }
public override string ToString()
{
return "NroComprobante" + NroComprobante + "Fecha" + Fecha + "Empleado" + Empleado;
}
}
}
|
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Gissa ett hel tal mellan 1 till 101! ");
Random random = new Random();
int randomZ = random.Next(1 , 101);
int Gissa;
int Antalgissningar = 0;
do
{
Gissa = int.Parse(Console.ReadLine());
if (Gissa < randomZ)
{
Console.WriteLine("Du gissade för låg");
}
else if (Gissa > randomZ)
{
Console.WriteLine("Du gissade för hög");
}
Console.WriteLine(Antalgissningar++);
} while (Gissa != randomZ);
Console.WriteLine("Grattis du gissade rätt");
Console.WriteLine(Antalgissningar++);
Console.Write("Antal gissnigar! ");
}
}
}
|
namespace Puppeteer.Core.Helper
{
public class SingletonManager<T> where T : class, new()
{
public static T Instance
{
get
{
lock (INSTANCE_LOCK)
{
if (m_InstanceValue != null)
{
return m_InstanceValue;
}
if (m_InstanceValue == null)
{
m_InstanceValue = new T();
}
return m_InstanceValue;
}
}
set
{
m_InstanceValue = value;
}
}
private static readonly object INSTANCE_LOCK = new object();
private static T m_InstanceValue = null;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Dto.Dto.GetSettings.AgencyReasonCodes
{
public class AgencyReasonCodes
{
public string DisplayName { get; set; }
public List<Option> Options { get; set; }
}
}
|
using TAiMStore.Domain;
using TAiMStore.Model.ViewModels;
namespace TAiMStore.Model.Repository
{
public interface IOrderRepository : IRepository<Order>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MemberPortal.Models
{
public class MockDatabaseMember
{
public int MemberID { get; set; }
public string MemberName { get; set; }
public string MemberAddress1 { get; set; }
public string MemberAddress2 { get; set; }
public string MemberCity { get; set; }
public int MemberPhone { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
}
|
namespace DependencyInjectionTest.WithInjection
{
public interface IAddressObject
{
string Place { get; set; }
int Number { get; set; }
string PlaceType { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.CrossPlatformInput
{
public class FloorSelecterActivate : MonoBehaviour
{
public GameObject _floorSelecterButton;
// Use this for initialization
void Start()
{
_floorSelecterButton = GameObject.Find("Player/Canvas/FloorInput");
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider col)
{
if(col.gameObject.tag == "Player"){
_floorSelecterButton.SetActive(true);
}
}
private void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "Player")
{
_floorSelecterButton.SetActive(false);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_Empty
{
/*
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
}
public class Solution
{ }
}//public abstract class Problem_
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Newtonsoft.Json.Linq;
using ProjectBueno.Game.Spells;
using System;
using System.IO;
using System.Windows.Forms;
namespace ProjectBueno.Engine
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public sealed class Main : Microsoft.Xna.Framework.Game
{
//All really bad workaround. Do not use static!
public static GraphicsDeviceManager graphicsManager { get; private set; }
public static SpriteBatch spriteBatch { get; private set; }
public static ContentManager content { get; private set; }
public static GameWindow window { get; private set; }
private static IHandler _handler;
/// <summary>Assign to this to change current <see cref="IHandler"/> and bypass <see cref="IHandler.Initialize()"/> and <see cref="IHandler.Deinitialize()"/></summary>
public static IHandler HandlerBP
{
set
{
value.WindowResize();
_handler = value;
}
}
/// <summary>Assign to this to change current <see cref="IHandler"/></summary>
public static IHandler Handler
{
get { return _handler; }
set
{
_handler?.Deinitialize();
value.Initialize();
value.WindowResize();
_handler = value;
}
}
/// <summary>Main class singleton to access non-static members.</summary>
public static Viewport Viewport { get { return graphicsManager.GraphicsDevice.Viewport; } }
/// <summary>Main class singleton to access non-static members.</summary>
public static Main self { get; private set; }
public static KeyboardState oldKeyState { get; private set; }
public static KeyboardState newKeyState { get; private set; }
public static MouseState oldMouseState { get; private set; }
public static MouseState newMouseState { get; private set; }
public const int xRatio = 140;
public const int yRatio = 105;
public const float widthMult = (float)xRatio / yRatio;
public const float heightMult = (float)yRatio / xRatio;
public static int maxWidth;
public static int maxHeight;
private static Rectangle oldClientBounds;
public static bool graphicsDirty;
private static Form windowForm;
public static readonly JObject Config;
public static Texture2D boxel { get; private set; }
public static SpriteFont retroFont { get; private set; }
public static readonly RasterizerState AliasedRasterizer;
public static event EventHandler<EventArgs> exiting;
public Main()
{
AppDomain.CurrentDomain.UnhandledException += OnException;
//var output = new StreamWriter("Output.log", false);
//output.AutoFlush = true;
//Console.SetOut(output);
graphicsManager = new GraphicsDeviceManager(this) { SynchronizeWithVerticalRetrace = true }; //Bad workaround
content = Content; //Bad workaround
window = Window; //Bad workaround
content.RootDirectory = "Content";
window.AllowUserResizing = true;
window.Title = "Project Bueno " + PB.VERSION;
IsMouseVisible = true;
IsFixedTimeStep = true;
//TargetElapsedTime = TimeSpan.FromSeconds(1.0 / 5.0);
newKeyState = Keyboard.GetState();
newMouseState = Mouse.GetState();
graphicsManager.PreferMultiSampling = false;
graphicsManager.PreferredBackBufferWidth = xRatio * 5;
graphicsManager.PreferredBackBufferHeight = yRatio * 5;
oldClientBounds = window.ClientBounds;
self = this; //Bad workaround
}
static Main()
{
Config = JObject.Parse(File.ReadAllText("Content/Config.json"));
AliasedRasterizer = new RasterizerState() { MultiSampleAntiAlias = false };
}
private static void OnException(object sender, UnhandledExceptionEventArgs e)
{
var Error = new StreamWriter("Crash-" + DateTime.Now.ToString("dd.MM.yyyy-HH.mm.ss") + ".log", false);
Exception ex = (Exception)e.ExceptionObject;
Error.WriteLine(ex);
if (ex.InnerException != null)
{
Error.WriteLine();
Error.WriteLine(ex.InnerException);
}
Error.Flush();
}
private void WindowSizeChanged(object sender, EventArgs e)
{
if (window.ClientBounds.Width != 0)
{
if (windowForm.WindowState == FormWindowState.Maximized)
{
WindowMaximized();
}
else if (window.ClientBounds.Width < xRatio || window.ClientBounds.Height < yRatio)
{
graphicsManager.PreferredBackBufferWidth = xRatio;
graphicsManager.PreferredBackBufferHeight = yRatio;
}
else if (oldClientBounds.Width != window.ClientBounds.Width && graphicsManager.PreferredBackBufferWidth != window.ClientBounds.Width)
{
graphicsManager.PreferredBackBufferWidth = window.ClientBounds.Width;
graphicsManager.PreferredBackBufferHeight = (int)(window.ClientBounds.Width * heightMult);
if ((float)GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width / xRatio < (float)GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height / yRatio)
{
maxWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
maxHeight = (int)(maxWidth * heightMult);
}
else
{
maxHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
maxWidth = (int)(maxHeight * widthMult);
}
if (graphicsManager.PreferredBackBufferWidth > maxWidth || graphicsManager.PreferredBackBufferHeight > maxHeight)
{
graphicsManager.PreferredBackBufferWidth = maxWidth;
graphicsManager.PreferredBackBufferHeight = maxHeight;
}
}
else if (oldClientBounds.Height != window.ClientBounds.Height && graphicsManager.PreferredBackBufferHeight != window.ClientBounds.Height)
{
graphicsManager.PreferredBackBufferHeight = window.ClientBounds.Height;
graphicsManager.PreferredBackBufferWidth = (int)(window.ClientBounds.Height * widthMult);
if ((float)GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width / xRatio < (float)GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height / yRatio)
{
maxWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
maxHeight = (int)(maxWidth * heightMult);
}
else
{
maxHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
maxWidth = (int)(maxHeight * widthMult);
}
if (graphicsManager.PreferredBackBufferWidth > maxWidth || graphicsManager.PreferredBackBufferHeight > maxHeight)
{
graphicsManager.PreferredBackBufferWidth = maxWidth;
graphicsManager.PreferredBackBufferHeight = maxHeight;
}
}
oldClientBounds = window.ClientBounds;
if (Handler != null)
{
Handler.WindowResize();
}
graphicsDirty = true;
}
}
private void WindowMaximized()
{
graphicsManager.PreferredBackBufferHeight = window.ClientBounds.Height;
graphicsManager.PreferredBackBufferWidth = window.ClientBounds.Width;
Viewport viewport = graphicsManager.GraphicsDevice.Viewport;
if ((float)window.ClientBounds.Width / window.ClientBounds.Height < widthMult)
{
viewport.Height = (int)(window.ClientBounds.Width * heightMult);
viewport.Y = (window.ClientBounds.Height - viewport.Height) / 2;
}
else
{
viewport.Width = (int)(window.ClientBounds.Height * widthMult);
viewport.X = (window.ClientBounds.Width - viewport.Width) / 2;
}
graphicsManager.GraphicsDevice.Viewport = viewport;
}
//Call static workaround exiting event
protected override void OnExiting(object sender, EventArgs args)
{
//base.OnExiting(sender, args);
Handler?.Deinitialize();
if (exiting != null)
{
exiting(sender, args);
}
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
windowForm = (Form)Control.FromHandle(window.Handle);
window.ClientSizeChanged += new EventHandler<EventArgs>(WindowSizeChanged);
WindowSizeChanged(null, null);
EnemyManager.Initialize();
Handler = new StartMenuHandler();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice); //Bad workaround
boxel = new Texture2D(spriteBatch.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
boxel.SetData(new[] { Color.White });
retroFont = Content.Load<SpriteFont>("Font");
EmptySkill.initEmpty();
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
oldKeyState = newKeyState;
oldMouseState = newMouseState;
newKeyState = Keyboard.GetState();
newMouseState = Mouse.GetState();
newMouseState = new MouseState(newMouseState.X - graphicsManager.GraphicsDevice.Viewport.X, newMouseState.Y - graphicsManager.GraphicsDevice.Viewport.Y, newMouseState.ScrollWheelValue, newMouseState.LeftButton, newMouseState.MiddleButton, newMouseState.RightButton, newMouseState.XButton1, newMouseState.XButton2);
_handler.Update();
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
if (graphicsDirty)
{
graphicsManager.ApplyChanges();
graphicsDirty = false;
//Console.WriteLine(graphicsManager.PreferredBackBufferWidth + " " + graphicsManager.PreferredBackBufferHeight + " " + window.ClientBounds);
}
graphicsManager.GraphicsDevice.Clear(Color.Black);
_handler.Draw();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConFutureNce.Models
{
public class ProgrammeCommitteeMember : UserType
{
public string EmployeePosition { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DTO
{
public class MealDto
{
public int MealCode { get; set; }
public string MealName { get; set; }
public string Instructions { get; set; }
public int? NumberOfDiners { get; set; }
public string Discription { get; set; }
public int? MealCategoryCode { get; set; }
public int? UserCode { get; set; }
public int? NumberOfViews { get; set; }
public List<ProductDto> Products { get; set; }
public String UserName { get; set; }
}
}
|
using UnityEngine;
public class CharacterSheet : MonoBehaviour {
[SerializeField] protected float _speed;
[SerializeField] protected float _jumpForce;
public float speed => _speed;
public float jumpForce => _jumpForce;
} |
using Banco.Contas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Banco.Filtros
{
class FiltroMesCorrente : Filtro
{
public FiltroMesCorrente(Filtro f) : base(f) { }
public FiltroMesCorrente() : base() { }
public override IEnumerable<Conta> Filtra(IList<Conta> contas)
{
IEnumerable<Conta> filtradas = contas.Where(c => c.DataDeCriacao.Month == DateTime.Now.Month).ToList();
IEnumerable<Conta> filtradasDoOutroFiltro = AplicaOutroFiltro(contas);
IEnumerable<Conta> todas = filtradas.Concat(filtradasDoOutroFiltro);
return todas;
}
}
}
|
using Tomelt.Autoroute.Models;
namespace Tomelt.Autoroute.Services {
public interface IPathResolutionService : IDependency {
AutoroutePart GetPath(string path);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZY.OA.Model.SearchModel
{
public class RoleSearchParms:BaseParms
{
public string RoleName { get; set; }
public string Remark { get; set; }
}
}
|
using System.Collections.Generic;
using Proxynet.Models;
using UsersLib.Entity;
namespace Proxynet.Service.Converters
{
public class UserDtoConverter : IUserDtoConverter
{
private readonly IGroupDtoConverter _groupDtoConverter;
public UserDtoConverter( IGroupDtoConverter groupDtoConverter )
{
_groupDtoConverter = groupDtoConverter;
}
public List<UserDto> Convert( List<User> users )
{
return users.ConvertAll( Convert );
}
public UserDto Convert( User user )
{
return new UserDto
{
Id = user.UserId,
Name = user.DisplayName
};
}
public User Convert( UserDto user )
{
return new User
{
DisplayName = user.Name,
UserId = user.Id
};
}
public List<UserDto> ConvertFromUsersWithGroups( Dictionary<User, List<Group>> users )
{
List<UserDto> result = new List<UserDto>();
foreach ( KeyValuePair<User, List<Group>> pair in users )
{
UserDto user = Convert( pair.Key );
user.Groups = _groupDtoConverter.Convert( pair.Value );
result.Add( user );
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevExpress.Xpf.Map;
namespace TrackAnalyzer2
{
/// <summary>
/// Klasa obsługująca wczytywanie przejadów z plików txt.
/// </summary>
public class TxtFileGpsReader : IGpsSignalReader
{
/// <summary>
/// Odczytuje dane nt. współrzędnych geograficznych oraz chwil czasu z pliku *.txt.
/// Wczytane dane dodaje do listy punktów (klasa TrackPoint) zwracanego przejazdu.
/// Zwraca utworzony przejazd (klasa Ride).
/// </summary>
/// <param name="inFileName"></param>
/// <returns></returns>
public Ride ReadFile(string inFileName)
{
string tempReadData = System.IO.File.ReadAllText(inFileName);
tempReadData.Replace(",", ".");
string[] tempSplit = tempReadData.Split(new char[] { ';', '\n' });
Ride tempRide = new Ride();
if ((tempSplit.Length - 1) % 3 == 0)
{
for (int i = 0; i + 3 < tempSplit.Length; i = i + 3)
{
try
{
tempRide.trackPoints.Add(new TrackPoint { location = new GeoPoint(double.Parse(tempSplit[i]), double.Parse(tempSplit[i + 1])), time = DateTime.Parse(tempSplit[i + 2]).ToUniversalTime() });
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.ToString());
}
}
tempRide.TrackPointToSections();
}
if (tempRide.trackPoints.Count > 1)
return tempRide;
else
return null;
}
}
}
|
/***********************************************************************
* Module: UserStrategy.cs
* Author: Sladjana Savkovic
* Purpose: Definition of the Interface Controller.Users&WorkingTimeController.UserStrategy
***********************************************************************/
using Model.Users;
using System;
using System.Collections.Generic;
namespace Controller.UsersAndWorkingTime
{
public interface IUserStrategy
{
User SignIn(string username, string password);
User Register(User user);
User EditProfile(User user);
User ViewProfile(string jmbg);
bool DeleteProfile(string jmbg);
List<User> ViewAllUsers();
}
} |
using System.Collections.Generic;
namespace Zesty.Core.Business
{
class Role
{
private static IStorage storage = StorageManager.Storage;
internal static List<Entities.Role> List()
{
return storage.GetRoles();
}
internal static void Add(Entities.Role role)
{
storage.Add(role);
}
}
}
|
using DevanshAssociate_API.Models;
using DevanshAssociate_API.Models.ENUM;
using MagathApi.DAL;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace DevanshAssociate_API.DAL
{
public class EmpDataDAL : BaseDAL
{
public List<EmpData> getAllCustomerData()
{
string response = JsonConvert.SerializeObject(null);
MySqlDataReader dr = CallEmpDetail_USP(response, OperationType.GET_All);
List<EmpData> customersData = new List<EmpData>();
while (dr.Read())
{
EmpData customerData = ConvertDataReaderIntoModel(dr);
customersData.Add(customerData);
}
dr.Close();
return customersData;
}
public string addEmpData(EmpData emp)
{
string request = JsonConvert.SerializeObject(emp);
string response = "";
MySqlDataReader dr = CallEmpDetail_USP(request, OperationType.SAVE);
while (dr.Read())
{
response = Convert.ToString(dr["_errorOutput"]);
}
dr.Close();
return response;
}
private MySqlDataReader CallEmpDetail_USP(string empDataJson, OperationType operationType)
{
MySqlDataReader dr = null;
var errorOutput = "";
try
{
MySqlParameter empDetailParam = new MySqlParameter("@empData", empDataJson);
empDetailParam.Direction = ParameterDirection.Input;
MySqlParameter operationTypeParam = new MySqlParameter("@operationType", operationType);
operationTypeParam.Direction = ParameterDirection.Input;
MySqlParameter outputParam = new MySqlParameter("@_errorOutput", errorOutput);
outputParam.Direction = ParameterDirection.Output;
MySqlCommand cmd = BaseDAL.GetSqlCommandProcedure(Get_All_Emp_Data_USP);
cmd.Parameters.Add(empDetailParam);
cmd.Parameters.Add(operationTypeParam);
cmd.Parameters.Add(outputParam);
dr = cmd.ExecuteReader();
}
catch (MySqlException execption)
{
throw new Exception("Internal Error occurred: " + execption.Message);
}
return dr;
}
private EmpData ConvertDataReaderIntoModel(MySqlDataReader dr)
{
EmpData obj = new EmpData();
obj.employeeName = Convert.ToString(dr["UserName"]);
return obj;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using Moq;
namespace PayByPhoneTwitter.Tests
{
/// <summary>
/// All methods of the Twitter Service that interact with Twitter need to authenticate each
/// WebRequest; these tests verify that the authenticator is called
/// </summary>
[TestClass]
public class TwitterServiceAuthenticationTests
{
public TwitterService twitterService;
public Mock<IAuthenticator> authMock;
[TestInitialize]
public void SetupTests()
{
authMock = SetupHelperMethods.SetupMockAuthenticator();
var parserMock = SetupHelperMethods.SetupMockJSonParser();
var requestFactory = new MockWebRequestFactory();
requestFactory.ResponseData = Encoding.Default.GetBytes("test data");
twitterService = new TwitterService(SetupHelperMethods.GetTestToken());
twitterService.Authenticator = authMock.Object;
twitterService.WebRequestFactory = requestFactory;
twitterService.Parser = parserMock.Object;
}
[TestMethod]
public void GetMostRecentTweets_ShouldAuthenticateWebRequest()
{
twitterService.GetMostRecentTweets("test_user");
authMock.VerifyAll();
}
[TestMethod]
public void GetTweetsOlderThanId_ShouldAuthenticateWebRequest()
{
twitterService.GetTweetsOlderThanId("test_user", 1);
authMock.VerifyAll();
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Repository.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ArticlesProject.Repository.Interfaces;
using ArticlesProject.DatabaseEntities;
using System.Threading.Tasks;
namespace ArticlesProject.Repository.Implementations
{
public class UserRepository : Repository<User>, IUserRepository
{
private DatabaseContext context
{
get
{
return _db as DatabaseContext;
}
}
public UserRepository(DbContext db) : base(db)
{
}
public IEnumerable<User> UsersWhoNeverReplied()
{
List<User> users = new List<User>();
return context.Users.Where(user => !context.Replys.Any(obj => obj.UserId == user.UserId))?.Select(user => user);
}
public IEnumerable<User> UsersWhoRepliedAlteastOnce()
{
return (from user in context.Users
join reply in context.Replys on user.UserId equals reply.UserId
select user).ToList();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Script encargado de detectar si el jugador se acerca al Trigger del objeto para abrir la puerta asignada en <see cref="door"/>
/// </summary>
public class Door : MonoBehaviour
{
public GameObject door;
public Sprite doorOpenSprite;
public Sprite doorCloseSprite;
private void Start()
{
if(door == null)
{
Debug.LogError("No se asigno la puerta correspondiente en door");
return;
}
door.GetComponent<SpriteRenderer>().sprite = doorCloseSprite;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag != "Player") return;
door.GetComponent<SpriteRenderer>().sprite = doorOpenSprite;
door.GetComponent<Collider2D>().enabled = false;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NS_Personal.DAL;
using NS_Personal.Basicas;
namespace NS_Personal.Forms
{
public partial class Teste : Form
{
public Teste()
{
InitializeComponent();
//lock column width
listPolish.ColumnWidthChanging += new ColumnWidthChangingEventHandler(listPolish_ColumnWidthChanging);
LoadBrands();
LoadFinish();
LoadPolish();
}
private void btnInsert_Click(object sender, EventArgs e)
{
if (comboBrands.SelectedIndex == -1)
{
MessageBox.Show("Select a BRAND");
}
else if (comboFinish.SelectedIndex == -1)
{
MessageBox.Show("Select a FINISH");
}
else
{
DAL_Polish dao = DAL_Polish.getInstancia();
Polish p = new Polish();
p.Name = txtName.Text;
p.Color = txtColor.Text;
p.Brand = comboBrands.SelectedValue.ToString();
p.Finish = comboFinish.SelectedValue.ToString();
dao.InsertPolish(p);
MessageBox.Show("Inserted!");
txtName.Text = "";
txtColor.Text = "";
comboBrands.SelectedIndex = -1;
comboFinish.SelectedIndex = -1;
LoadPolish();
}
}
private void btnFormBrand_Click(object sender, EventArgs e)
{
new NewBrand(this).ShowDialog();
}
private void btnFormFinish_Click(object sender, EventArgs e)
{
new NewFinish(this).ShowDialog();
}
public void LoadBrands()
{
DAL_Brand dao = DAL_Brand.getInstancia();
comboBrands.DisplayMember = "Brand";
comboBrands.ValueMember = "ID";
comboFilterBrand.DisplayMember = "Brand";
comboFilterBrand.ValueMember = "ID";
comboBrands.DataSource = dao.GetBrands();
comboFilterBrand.DataSource = dao.GetBrands();
comboBrands.SelectedIndex = -1;
comboFilterBrand.SelectedIndex = -1;
}
public void LoadFinish()
{
DAL_Finish dao = DAL_Finish.getInstancia();
comboFinish.ValueMember = "ID";
comboFinish.DisplayMember = "Finish";
comboFilterFinish.ValueMember = "ID";
comboFilterFinish.DisplayMember = "Finish";
comboFinish.DataSource = dao.GetFinish();
comboFilterFinish.DataSource = dao.GetFinish();
comboFinish.SelectedIndex = -1;
comboFilterFinish.SelectedIndex = -1;
}
public void LoadPolish()
{
DAL_Polish dao = DAL_Polish.getInstancia();
// gridPolish.DataSource = dao.GetPolish();
listPolish.Items.Clear();
DataTable _dt = new DataTable();
try
{
_dt = dao.GetPolish();
if (_dt == null)
{
throw new Exception("No polish to display");
}
else
{
foreach (DataRow item in _dt.Rows)
{
ListViewItem polish = new ListViewItem();
polish.Text = item["ID"].ToString();//0
polish.SubItems.Add(item["Name"].ToString()); //1
polish.SubItems.Add(item["Color"].ToString()); //2
polish.SubItems.Add(item["Brand"].ToString()); //3
polish.SubItems.Add(item["Finish"].ToString()); //4
listPolish.Items.Add(polish);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void listPolish_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
e.Cancel = true;
e.NewWidth = listPolish.Columns[e.ColumnIndex].Width;
}
private void btnFind_Click(object sender, EventArgs e)
{
DAL_Polish dao = DAL_Polish.getInstancia();
// gridPolish.DataSource = dao.GetPolish();
listPolish.Items.Clear();
DataTable _dt = new DataTable();
try
{
string brand = comboFilterBrand.SelectedValue.ToString();
string finish = comboFilterFinish.SelectedValue.ToString();
if (string.IsNullOrEmpty(brand) && string.IsNullOrEmpty(finish))
{
_dt = dao.FindPolish(null, null);
}
else if (!string.IsNullOrEmpty(brand) && string.IsNullOrEmpty(finish))
{
_dt = dao.FindPolish(brand, null);
}
else if (string.IsNullOrEmpty(brand) && !string.IsNullOrEmpty(finish))
{
_dt = dao.FindPolish(null, finish);
}
else
{
_dt = dao.FindPolish(brand, finish);
}
if (_dt == null)
{
throw new Exception("No polish to display");
}
else
{
foreach (DataRow item in _dt.Rows)
{
ListViewItem polish = new ListViewItem();
polish.Text = item["ID"].ToString();//0
polish.SubItems.Add(item["Name"].ToString()); //1
polish.SubItems.Add(item["Color"].ToString()); //2
polish.SubItems.Add(item["Brand"].ToString()); //3
polish.SubItems.Add(item["Finish"].ToString()); //4
listPolish.Items.Add(polish);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace digitRecognizerAndroidTrain
{
class NeuralNetwork
{
List<NetworkLayer> network;
String[] path;
/*functions*/
public NeuralNetwork(int nLayer, int[] nNeuronForLayer, int[] nInputForNeuron, String[] path)
{
this.path = path;
network = new List<NetworkLayer>();
for (int i = 0; i < nLayer; i++)
{
network.Add(new NetworkLayer(nNeuronForLayer[i], nInputForNeuron[i]));
}
}
public void loadInput(float[] value)
{
//normalize data
value = normalizeInput(value);
//loading data into network
for (int i = 0; i < value.Length; i++)
{
network[0].getNeuron(i).Output = value[i];
}
}
public float[] normalizeInput(float[] values)
{
//preparing data in range 0.01 to 0.99
for (int i = 0; i < values.Length; i++)
{
values[i] = (float)((0.98 * values[i]) / 255 + 0.01);
}
return values;
}
public void runNetwork()
{
for (int i = 0; i < network.Count - 1; i++)
{
for (int j = 0; j < network[i + 1].nNeuron; j++)
{
for (int k = 0; k < network[i + 1].getNeuron(j).nInput; k++)
{
network[i + 1].getNeuron(j).setinputValue(k, network[i].getNeuron(k).Output);
}
network[i + 1].getNeuron(j).processInput();
}
}
}
public void train(int nEpoch, float learningRate, int nTrainingSet)
{
float[] desiderateOutput;
TrainingExample trainingExample;
for (int i = 0; i < nEpoch; i++)
{
for (int j = 0; j < nTrainingSet; j++)
{
//forward data
trainingExample = readTrainingSet(j);
loadInput(trainingExample.getData());
runNetwork();
//MessageBox.Show(path[j] + "=" + trainingExample.Target.ToString());
//calculate errors
desiderateOutput = new float[network[network.Count - 1].nNeuron];
for (int k = 0; k < desiderateOutput.Length; k++)
{
desiderateOutput[k] = 0;
}
if(trainingExample.Target<=9)
desiderateOutput[trainingExample.Target] = 1;
updateErrors(desiderateOutput);
//fix weights
adjustsWeights(learningRate);
//save net
saveNet();
}
}
}
public void adjustsWeights(float learningRate)
{
float newValue;
float partialDerivate;
for (int i = network.Count - 1; i > 0; i--)
{
for (int j = 0; j < network[i].nNeuron; j++)
{
for (int k = 0; k < network[i].getNeuron(j).nInput; k++)
{
float sum = 0;
for (int z = 0; z < network[i].getNeuron(j).nInput; z++)
{
sum += network[i].getNeuron(j).getWeightValue(z) * network[i - 1].getNeuron(z).Output;
}
partialDerivate = -network[i].getNeuron(j).Error *
derivedActivationFunction(sum) *
network[i - 1].getNeuron(k).Output;
newValue = network[i].getNeuron(j).getWeightValue(k) - (learningRate * partialDerivate);
network[i].getNeuron(j).setInputWeight(k, newValue);
}
}
}
}
public void updateErrors(float[] desiderateOutput)
{
float sumWeightsNeuron;
//calculating output layer errors
for (int i = 0; i < network[network.Count - 1].nNeuron; i++)
{
network[network.Count - 1].getNeuron(i).Error = (float)desiderateOutput[i] - network[network.Count - 1].getNeuron(i).Output;
}
//calculating other layers errors
for (int i = network.Count - 2; i > 0; i--)
{
for (int j = 0; j < network[i].nNeuron; j++)
{
network[i].getNeuron(j).Error = 0;
//loop to sum all weights neuron
sumWeightsNeuron = 0;
for (int z = 0; z < network[i + 1].nNeuron; z++)
{
sumWeightsNeuron += network[i + 1].getNeuron(z).getWeightValue(j);
}
//loop per prendere i singoli pesi
for (int z = 0; z < network[i + 1].nNeuron; z++)
{
network[i].getNeuron(j).Error += (network[i + 1].getNeuron(z).getWeightValue(j) / sumWeightsNeuron) * network[i + 1].getNeuron(z).Error;
}
}
}
}
private float derivedActivationFunction(float outputValue)
{
return ((float)(1 / (1 + (1 / Math.Pow(Math.E, outputValue))))
* (1 - (float)(1 / (1 + (1 / Math.Pow(Math.E, outputValue))))));
}
public TrainingExample readTrainingSet(int index)
{
TrainingExample trainingExample;
float[] values;
Bitmap bmp = new Bitmap("png/" + path[index]);
values = new float[28 * 28];
for (int i = 0; i < 28; i++)
{
for (int j = 0; j < 28; j++)
{
values[i * 28 + j] = float.Parse(bmp.GetPixel(i, j).R.ToString());
}
}
trainingExample = new TrainingExample(values, int.Parse(path[index].Split(new char[] { '_','.'})[1].ToString()));
return trainingExample;
}
public TrainingExample readTrainingSet(String path)
{
TrainingExample trainingExample;
float[] values;
Bitmap bmp = new Bitmap("png/" + path);
values = new float[28 * 28];
for (int i = 0; i < 28; i++)
{
for (int j = 0; j < 28; j++)
{
values[i * 28 + j] = float.Parse(bmp.GetPixel(i, j).R.ToString());
}
}
trainingExample = new TrainingExample(values, int.Parse(path.Split(new char[] { '_', '.' })[1].ToString()));
return trainingExample;
}
public float[] softmaxFunction(float[] values)
{
float denominator = 0;
float[] outputProbalities = new float[values.Length];
//calculate denominator
for (int i = 0; i < values.Length; i++)
{
denominator += (float)Math.Exp(values[i]);
}
//calculate function
for (int i = 0; i < values.Length; i++)
{
outputProbalities[i] = (float)Math.Exp(values[i]) / (denominator);
}
return outputProbalities;
}
public void saveNet()
{
//creo la cartella salvataggi
Directory.CreateDirectory("netBackup");
String[] files = Directory.GetFiles("netBackup");
using (FileStream fs = new FileStream("./netBackup/rete" + files.Length.ToString() + ".csv", FileMode.Create, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
//stampo tutti i pesi
for (int i = 0; i < network.Count; i++)
{
for (int j = 0; j < network[i].nNeuron; j++)
{
for (int k = 0; k < network[i].getNeuron(j).nInput; k++)
{
sw.Write(network[i].getNeuron(j).getWeightValue(k) + ";");
}
}
}
}
}
public void loadSavedNet(String path)
{
//carica la rete da salvataggio precedente
using (FileStream fs = new FileStream("./netBackup/" + path, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
{
string app;
app = sr.ReadLine();
String[] split = app.Split(';');
int sum = 0;
for (int i = 0; i < network.Count; i++)
{
for (int j = 0; j < network[i].nNeuron; j++)
{
for (int k = 0; k < network[i].getNeuron(j).nInput; k++)
{
network[i].getNeuron(j).setInputWeight(k, float.Parse(split[sum]));
sum++;
}
}
}
}
}
public int[] getPrediction()
{
int[] prediction = new int[network[network.Count - 1].nNeuron];
List<Neuron> list = new List<Neuron>();
for (int i = 0; i < network[network.Count - 1].nNeuron; i++)
{
list.Add(network[network.Count - 1].getNeuron(i));
}
list = list.OrderBy(output => output.Output).ToList();
list.Reverse();
for (int i = 0; i < network[network.Count - 1].nNeuron; i++)
{
prediction[i] = list[i].getIndex();
}
return prediction;
}
/*get and set method*/
public NetworkLayer getLayer(int index) { return network[index]; }
public int getNLayer() { return network.Count; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Logs_Aggregator
{
class Program
{
static void Main(string[] args)
{
var logs = new Dictionary<string, Dictionary<string, int>>();
int n = int.Parse(Console.ReadLine());
while (n-- > 0)
{
string line = Console.ReadLine();
var commandArgs = line.Split(' ');
string ip = commandArgs[0];
string name = commandArgs[1];
int logsCount = int.Parse(commandArgs[2]);
if (!logs.ContainsKey(name))
{
logs.Add(name, new Dictionary<string, int>());
}
if (!logs[name].ContainsKey(ip))
{
logs[name].Add(ip, logsCount);
}
else
{
logs[name][ip] = logs[name][ip] + logsCount;
}
}
foreach (var name in logs.OrderBy(x => x.Key))
{
Console.Write($"{name.Key}: {name.Value.Values.Sum()} ");
StringBuilder print = new StringBuilder();
print.Append("[");
foreach (var log in name.Value.OrderBy(i => i.Key))
{
print.Append(log.Key).Append(", ");
}
print.Remove(print.Length - 2, 2);
print.Append("]");
Console.Write(print.ToString());
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ex2
{
/*2) Написать программу, принимающую на вход строку — набор чисел,
разделенных пробелом, и возвращающую число — сумму всех чисел
в строке.Ввести данные с клавиатуры и вывести результат на экран.*/
class Program
{
static double StringToNumber(string numbers)
{
double sum = 0;
string[] arrayString = numbers.Split();
for(int i = 0;i < arrayString.Length; i++)
{
sum += Double.Parse(arrayString[i]);
}
return sum;
}
static void Main(string[] args)
{
double sum = StringToNumber("1,2 3,8 5,0 4,1 5,9");
Console.WriteLine(sum);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace BankAppCore.Models
{
public partial class Client
{
[MaxLength(13)]
[Key]
public string SocialSecurityNumber { get; set; }
[Required]
[MaxLength(250)]
public string Address { get; set; }
[Required]
[MaxLength(100)]
public string FirstName { get; set; }
[Required]
[MaxLength(100)]
public string LastName { get; set; }
[Required]
[MaxLength(100)]
public string IdentityCardNumber { get; set; }
public ICollection<Account> Accounts { get; set; }
public ICollection<Bill> Bills { get; set; }
}
} |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;
namespace WebApplication1
{
public class XContext:DbContext
{
public XContext(DbContextOptions<XContext>options): base(options)
{
}
public DbSet<User> users { get; set; }
}
}
|
using NumSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Tensorflow;
using static Tensorflow.Binding;
using static SharpCV.Binding;
using SharpCV;
namespace TensorFlowNET.Examples.ImageProcessing.YOLO
{
public class Dataset
{
string annot_path;
int[] input_sizes;
int batch_size;
bool data_aug;
int train_input_size;
int[] train_input_sizes;
NDArray train_output_sizes;
NDArray strides;
NDArray anchors;
Dictionary<int, string> classes;
int num_classes;
int anchor_per_scale;
int max_bbox_per_scale;
string[] annotations;
int num_samples;
int num_batchs;
int batch_count;
public int Length = 0;
public Dataset(string dataset_type, Config cfg)
{
annot_path = dataset_type == "train" ? cfg.TRAIN.ANNOT_PATH : cfg.TEST.ANNOT_PATH;
input_sizes = dataset_type == "train" ? cfg.TRAIN.INPUT_SIZE : cfg.TEST.INPUT_SIZE;
batch_size = dataset_type == "train" ? cfg.TRAIN.BATCH_SIZE : cfg.TEST.BATCH_SIZE;
data_aug = dataset_type == "train" ? cfg.TRAIN.DATA_AUG : cfg.TEST.DATA_AUG;
train_input_sizes = cfg.TRAIN.INPUT_SIZE;
strides = np.array(cfg.YOLO.STRIDES);
classes = Utils.read_class_names(cfg.YOLO.CLASSES);
num_classes = classes.Count;
anchors = np.array(Utils.get_anchors(cfg.YOLO.ANCHORS));
anchor_per_scale = cfg.YOLO.ANCHOR_PER_SCALE;
max_bbox_per_scale = 150;
annotations = load_annotations();
num_samples = len(annotations);
num_batchs = Convert.ToInt32(Math.Ceiling(num_samples / Convert.ToDecimal(batch_size)));
batch_count = 0;
}
string[] load_annotations()
{
return File.ReadAllLines(annot_path);
}
public IEnumerable<NDArray[]> Items()
{
train_input_size = train_input_sizes[new Random().Next(0, train_input_sizes.Length - 1)];
train_output_sizes = train_input_size / strides;
var batch_image = np.zeros((batch_size, train_input_size, train_input_size, 3));
var batch_label_sbbox = np.zeros((batch_size, train_output_sizes[0], train_output_sizes[0],
anchor_per_scale, 5 + num_classes));
var batch_label_mbbox = np.zeros((batch_size, train_output_sizes[1], train_output_sizes[1],
anchor_per_scale, 5 + num_classes));
var batch_label_lbbox = np.zeros((batch_size, train_output_sizes[2], train_output_sizes[2],
anchor_per_scale, 5 + num_classes));
var batch_sbboxes = np.zeros((batch_size, max_bbox_per_scale, 4));
var batch_mbboxes = np.zeros((batch_size, max_bbox_per_scale, 4));
var batch_lbboxes = np.zeros((batch_size, max_bbox_per_scale, 4));
int num = 0;
while (batch_count < num_batchs)
{
while (num < batch_size)
{
var index = batch_count * batch_size + num;
if (index >= num_samples)
index -= num_samples;
var annotation = annotations[index];
var (image, bboxes) = parse_annotation(annotation);
var (label_sbbox, label_mbbox, label_lbbox, sbboxes, mbboxes, lbboxes) = preprocess_true_boxes(bboxes);
batch_image[num, Slice.All, Slice.All, Slice.All] = image;
batch_label_sbbox[num, Slice.All, Slice.All, Slice.All, Slice.All] = label_sbbox;
batch_label_mbbox[num, Slice.All, Slice.All, Slice.All, Slice.All] = label_mbbox;
batch_label_lbbox[num, Slice.All, Slice.All, Slice.All, Slice.All] = label_lbbox;
batch_sbboxes[num, Slice.All, Slice.All] = sbboxes;
batch_mbboxes[num, Slice.All, Slice.All] = mbboxes;
batch_lbboxes[num, Slice.All, Slice.All] = lbboxes;
num += 1;
}
batch_count += 1;
yield return new[]
{
batch_image,
batch_label_sbbox,
batch_label_mbbox,
batch_label_lbbox,
batch_sbboxes,
batch_mbboxes,
batch_lbboxes
};
}
batch_count = 0;
np.random.shuffle(annotations);
}
private (NDArray, NDArray) parse_annotation(string annotation)
{
var line = annotation.Split();
var image_path = line[0];
if (!File.Exists(image_path))
throw new KeyError($"{image_path} does not exist ... ");
var image = cv2.imread(image_path);
var bboxes = np.stack(line
.Skip(1)
.Select(box => np.array(box
.Split(',')
.Select(x => int.Parse(x))
.ToArray()))
.ToArray());
if (data_aug)
{
(image, bboxes) = random_horizontal_flip(image, bboxes);
(image, bboxes) = random_crop(image, bboxes);
(image, bboxes) = random_translate(image, bboxes);
}
NDArray image1;
(image1, bboxes) = Utils.image_preporcess(image, new[] { train_input_size, train_input_size }, bboxes);
return (image1, bboxes);
}
private(NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) preprocess_true_boxes(NDArray bboxes)
{
var label = range(3).Select(i => np.zeros(train_output_sizes[i], train_output_sizes[i], anchor_per_scale, 5 + num_classes)).ToArray();
var bboxes_xywh = range(3).Select(x => np.zeros(max_bbox_per_scale, 4)).ToArray();
var bbox_count = np.zeros(3);
foreach(var bbox in bboxes.GetNDArrays())
{
var bbox_coor = bbox[":4"];
int bbox_class_ind = bbox[4];
var onehot = np.zeros(new Shape(num_classes), dtype: np.float32);
onehot[bbox_class_ind] = 1.0f;
var uniform_distribution = np.full(new Shape(num_classes), 1.0 / num_classes);
var deta = 0.01f;
var smooth_onehot = onehot * (1 - deta) + deta * uniform_distribution;
var bbox_xywh = np.concatenate(((bbox_coor["2:"] + bbox_coor[":2"]) * 0.5, bbox_coor["2:"] - bbox_coor[":2"]), axis: -1);
var bbox_xywh_scaled = 1.0 * bbox_xywh[np.newaxis, Slice.All] / strides[Slice.All, np.newaxis];
var iou = new List<NDArray>();
var exist_positive = false;
foreach(var i in range(3))
{
var anchors_xywh = np.zeros((anchor_per_scale, 4));
anchors_xywh[Slice.All, new Slice(0, 2)] = np.floor(bbox_xywh_scaled[i, new Slice(0, 2)]).astype(np.int32) + 0.5;
anchors_xywh[Slice.All, new Slice(2, 4)] = anchors[i];
var iou_scale = bbox_iou(bbox_xywh_scaled[i][np.newaxis, Slice.All], anchors_xywh);
iou.Add(iou_scale);
var iou_mask = iou_scale > 0.3;
if (np.any(iou_mask))
{
var floors = np.floor(bbox_xywh_scaled[i, new Slice(0, 2)]).astype(np.int32);
var (xind, yind) = (floors.GetInt32(0), floors.GetInt32(1));
var ndTmp = label[i][yind, xind][iou_mask];
ndTmp[Slice.All] = 0;
ndTmp[Slice.All, new Slice(0, 4)] = bbox_xywh;
ndTmp[Slice.All, new Slice(4, 5)] = 1.0f;
ndTmp[Slice.All, new Slice(5)] = smooth_onehot;
var bbox_ind = (int)(bbox_count[i] % max_bbox_per_scale);
bboxes_xywh[i][bbox_ind, new Slice(0, 4)] = bbox_xywh;
bbox_count[i] += 1;
exist_positive = true;
}
}
if (!exist_positive)
{
throw new NotImplementedException("");
}
}
var (label_sbbox, label_mbbox, label_lbbox) = (label[0], label[1], label[2]);
var (sbboxes, mbboxes, lbboxes) = (bboxes_xywh[0], bboxes_xywh[1], bboxes_xywh[2]);
return (label_sbbox, label_mbbox, label_lbbox, sbboxes, mbboxes, lbboxes);
}
private NDArray bbox_iou(NDArray boxes1, NDArray boxes2)
{
var boxes1_area = boxes1[Slice.Ellipsis, 2] * boxes1[Slice.Ellipsis, 3];
var boxes2_area = boxes2[Slice.Ellipsis, 2] * boxes2[Slice.Ellipsis, 3];
boxes1 = np.concatenate((boxes1[Slice.Ellipsis, new Slice(":2")] - boxes1[Slice.Ellipsis, new Slice("2:")] * 0.5,
boxes1[Slice.Ellipsis, new Slice(":2")] + boxes1[Slice.Ellipsis, new Slice("2:")] * 0.5),
axis: -1);
boxes2 = np.concatenate((boxes2[Slice.Ellipsis, new Slice(":2")] - boxes2[Slice.Ellipsis, new Slice("2:")] * 0.5,
boxes2[Slice.Ellipsis, new Slice(":2")] + boxes2[Slice.Ellipsis, new Slice("2:")] * 0.5),
axis: -1);
var left_up = np.maximum(boxes1[Slice.Ellipsis, new Slice(":2")], boxes2[Slice.Ellipsis, new Slice(":2")]);
var right_down = np.minimum(boxes1[Slice.Ellipsis, new Slice("2:")], boxes2[Slice.Ellipsis, new Slice("2:")]);
var inter_section = np.maximum(right_down - left_up, NDArray.Scalar(0.0f));
var inter_area = inter_section[Slice.Ellipsis, 0] * inter_section[Slice.Ellipsis, 1];
var union_area = boxes1_area + boxes2_area - inter_area;
return inter_area / union_area;
}
private (Mat, NDArray) random_horizontal_flip(Mat image, NDArray bboxes)
{
return (image, bboxes);
}
private (Mat, NDArray) random_crop(Mat image, NDArray bboxes)
{
return (image, bboxes);
}
private (Mat, NDArray) random_translate(Mat image, NDArray bboxes)
{
return (image, bboxes);
}
}
}
|
using Dictionary;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Problem_01
{
class Program
{
static void Main()
{
var dragons = new Dictionary<string, SortedDictionary<string, DragonStats>>();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
ReadDragons(dragons);
}
PrintDragons(dragons);
}
private static void PrintDragons(Dictionary<string, SortedDictionary<string, DragonStats>> dragons)
{
foreach (var kvp in dragons)
{
var maxDamage = dragons[kvp.Key].Select(x => x.Value.Damage).ToList();
var maxHealth = dragons[kvp.Key].Select(x => x.Value.Health).ToList();
var maxArmor = dragons[kvp.Key].Select(x => x.Value.Armor).ToList();
Console.WriteLine($"{kvp.Key}::({maxDamage.Average():F2}/{maxHealth.Average():F2}/{maxArmor.Average():F2})");
foreach (var (name, stats) in kvp.Value)
{
Console.WriteLine($"-{name} -> damage: {stats.Damage}, health: {stats.Health}, armor: {stats.Armor}");
}
}
}
private static void ReadDragons(Dictionary<string, SortedDictionary<string, DragonStats>> dragons)
{
var typeOfDragon = Console.ReadLine().Split();
var type = typeOfDragon[0];
var name = typeOfDragon[1];
var damage = typeOfDragon[2];
var health = typeOfDragon[3];
var armor = typeOfDragon[4];
if (damage == "null")
{
damage = "45";
}
if (health == "null")
{
health = "250";
}
if (armor == "null")
{
armor = "10";
}
if (!dragons.ContainsKey(type))
{
dragons.Add(type, new SortedDictionary<string, DragonStats>());
}
var stats = new DragonStats(int.Parse(damage), int.Parse(health), int.Parse(armor));
if (!dragons[type].ContainsKey(name))
{
dragons[type].Add(name, stats);
}
else
{
dragons[type][name] = stats;
}
}
}
}
|
using Elmah;
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.Data.SqlClient;
using Microsoft.Reporting.WebForms;
namespace CreamBell_DMS_WebApps
{
public partial class frmAreaMonthMaterialSale : System.Web.UI.Page
{
CreamBell_DMS_WebApps.App_Code.Global baseObj = new CreamBell_DMS_WebApps.App_Code.Global();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USERID"] == null || Session["USERID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx");
return;
}
if (!IsPostBack)
{
try
{
FillCategory();
baseObj.FillSaleHierarchy();
fillHOS();
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
// DataView DtSaleHierarchy = (DataTable)HttpContext.Current.Session["SaleHierarchy"];
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
if (dt.Rows.Count > 0)
{
var dr_row = dt.AsEnumerable();
var test = (from r in dr_row
select r.Field<string>("SALEPOSITION")).First<string>();
if (test == "VP")
{
chkListHOS.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
}
else if (test == "GM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
}
else if (test == "DGM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
}
else if (test == "RM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
}
else if (test == "ZM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkListRM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
CheckBox4.Enabled = false;
CheckBox4.Checked = true;
}
else if (test == "ASM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkListRM.Enabled = false;
chkListZM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
CheckBox4.Enabled = false;
CheckBox4.Checked = true;
CheckBox5.Enabled = false;
CheckBox5.Checked = true;
// chkAll_CheckedChanged(null, null);
}
else if (test == "EXECUTIVE")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkListRM.Enabled = false;
chkListZM.Enabled = false;
chkListEXECUTIVE.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
CheckBox4.Enabled = false;
CheckBox4.Checked = true;
CheckBox5.Enabled = false;
CheckBox5.Checked = true;
CheckBox6.Enabled = false;
CheckBox6.Checked = true;
}
}
}
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
tclink.Width = "10%";
tclabel.Width = "90%";
Panel1.Visible = true;
LinkButton1.Visible = true;
}
else
{
tclink.Width = "0%";
tclabel.Width = "100%";
Panel1.Visible = false;
LinkButton1.Visible = false;
LinkButton1.Enabled = false;
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void FillState(DataTable dt)
{
string sqlstr = "";
try{
if (Convert.ToString(Session["ISDISTRIBUTOR"]) == "Y")
{
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
DataTable dtState = dt.DefaultView.ToTable(true, "STATE", "STATEWNAME");
// dtState.Columns.Add("STATENAMES", typeof(string), "STATE + ' - ' + STATENAME");
drpSTATE.Items.Clear();
DataRow dr = dtState.NewRow();
dr[0] = "--Select--";
dr[1] = "--Select--";
dtState.Rows.InsertAt(dr, 0);
drpSTATE.DataSource = dtState;
drpSTATE.DataTextField = "STATEWNAME";
drpSTATE.DataValueField = "STATE";
drpSTATE.DataBind();
}
else
{
DataTable dt2 = new DataTable();
sqlstr = "Select Distinct I.StateCode Code,I.StateCode+'-'+LS.Name Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' AND I.SITEID='" + Convert.ToString(Session["SiteCode"]) + "'";
//drpSTATE.Items.Add("Select...");
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = baseObj.GetConnection();
cmd1.CommandText = sqlstr;
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
sda.Fill(dt2);
//dt2.Load(cmd1.ExecuteReader());
drpSTATE.DataSource = dt2;
drpSTATE.DataTextField = "name";
drpSTATE.DataValueField = "code";
drpSTATE.DataBind();
}
}
else
{
DataTable dt1 = new DataTable();
sqlstr = "Select Distinct I.StateCode Code,LS.Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' ";
drpSTATE.Items.Add("Select...");
//only name and code have to be insertd in a new datatable according to this sqlstr
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection= baseObj.GetConnection();
cmd1.CommandText = sqlstr;
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
sda.Fill(dt1);
drpSTATE.DataSource = dt1;
drpSTATE.DataTextField = "name";
drpSTATE.DataValueField = "code";
drpSTATE.DataBind();
}
if (drpSTATE.Items.Count == 1)
{
drpSTATE.Items[0].Selected = true;
drpSTATE_SelectedIndexChanged(null, null);
// ddlCountry_SelectedIndexChanged(null, null);
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void FillSite()
{
string StateList = "";
foreach (ListItem item in drpSTATE.Items)
{
if (item.Selected)
{
if (StateList == "")
{
StateList += "'" + item.Value.ToString() + "'";
}
else
{
StateList += ",'" + item.Value.ToString() + "'";
}
}
}
if (StateList.Length > 0)
{
try{
string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'";
object objcheckSitecode = baseObj.GetScalarValue(sqlstr);
if (objcheckSitecode != null)
{
ddlSiteId.Items.Clear();
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID+'-'+Name Name from [ax].[INVENTSITE] where STATECODE in (" + StateList + ") Order by Name";
// ddlSiteId.Items.Add("All...");
DataTable dt1 = new DataTable();
dt1 = baseObj.GetData(sqlstr1);
ddlSiteId.DataSource = dt1;
ddlSiteId.DataTextField = "Name";
ddlSiteId.DataValueField = "Code";
ddlSiteId.Items.Insert(0, "All...");
ddlSiteId.DataBind();
}
else
{
ddlSiteId.Items.Clear();
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols = dt.DefaultView.ToTable(true, "Distributor", "DistributorName");
uniqueCols.Columns.Add("Name", typeof(string), "Distributor + ' - ' + DistributorName");
ddlSiteId.DataSource = uniqueCols;
ddlSiteId.DataTextField = "Name";
ddlSiteId.DataValueField = "Distributor";
ddlSiteId.DataBind();
ddlSiteId.Items.Insert(0, "All...");
}
else
{
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID+'-'+NAME Name from [ax].[INVENTSITE] where SITEID = '" + Session["SiteCode"].ToString() + "'";
//ddlSiteId.Items.Add("All...");
DataTable dt1 = new DataTable();
dt1 = baseObj.GetData(sqlstr1);
ddlSiteId.DataSource = dt1;
ddlSiteId.DataTextField = "name";
ddlSiteId.DataValueField = "code";
//ddlSiteId.Items.Insert(0, "All...");
ddlSiteId.DataBind();
ddlSiteId_SelectedIndexChanged(null, null);
}
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}
protected void FillCategory()
{
try{
DataTable dt = new DataTable();
string sqlstr11 = "select distinct(Product_Group) from ax.inventtable order by Product_Group";
dt = new DataTable();
dt = baseObj.GetData(sqlstr11);
drpCAT.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
drpCAT.DataSource = dt;
drpCAT.DataTextField = "Product_Group";
drpCAT.DataValueField = "Product_Group";
drpCAT.DataBind();
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void FillSubCategory()
{
string CategoryList = "";
try{
foreach (ListItem item in drpCAT.Items)
{
if (item.Selected)
{
if (CategoryList == "")
{
CategoryList += "" + item.Value.ToString() + "";
}
else
{
CategoryList += "," + item.Value.ToString() + "";
}
}
}
if (CategoryList.Length > 0)
{
DataTable dt = new DataTable();
string sqlstr1 = string.Empty;
sqlstr1 = @"select distinct(Product_Subcategory) from ax.inventtable where Product_Group in ('" + drpCAT.SelectedItem.Text + "') order by Product_Subcategory";
dt = new DataTable();
dt = baseObj.GetData(sqlstr1);
drpSUBCAT.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
drpSUBCAT.DataSource = dt;
drpSUBCAT.DataTextField = "Product_Subcategory";
drpSUBCAT.DataValueField = "Product_Subcategory";
drpSUBCAT.DataBind();
}
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void btnGenerateExcel_Click(object sender, EventArgs e)
{
//try
//{
bool b = ValidateInput();
if (b==true)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new CreamBell_DMS_WebApps.App_Code.Global();
string FilterQuery = string.Empty;
DataTable dtSetHeader = null;
//DataTable dtDataByfilter = null;
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
string query1 = "Select NAME from ax.inventsite where SITEID='" + Session["SiteCode"].ToString() + "'";
dtSetHeader = new DataTable();
dtSetHeader = obj.GetData(query1);
string query = string.Empty;
conn = new SqlConnection(obj.GetConnectionString());
conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
query = "ACX_USP_AREAMONTHMATERIALSALE";
cmd.CommandText = query;
DateTime stDate = Convert.ToDateTime(txtCurrentDate.Text);
DateTime firstDayOfMonth = new DateTime(stDate.Year, stDate.Month, 1);
cmd.Parameters.AddWithValue("@CURRENTSTDATE", firstDayOfMonth);
stDate = Convert.ToDateTime(txtBaseDate.Text);
firstDayOfMonth = new DateTime(stDate.Year, stDate.Month, 1);
cmd.Parameters.AddWithValue("@BASESTDATE", firstDayOfMonth);
cmd.Parameters.AddWithValue("@UserType", Convert.ToString(Session["LOGINTYPE"]));
cmd.Parameters.AddWithValue("@UserCode", Convert.ToString(Session["USERID"]));
//state
string StateList = "";
foreach (ListItem item in drpSTATE.Items)
{
if (item.Selected)
{
if (StateList == "")
{
StateList += "" + item.Value.ToString() + "";
}
else
{
StateList += "," + item.Value.ToString() + "";
}
}
}
if (StateList.Length > 0)
{
cmd.Parameters.AddWithValue("@StateId", StateList);
}
else
{
cmd.Parameters.AddWithValue("@StateId", "");
}
// site
if (ddlSiteId.SelectedIndex < 0)
{
cmd.Parameters.AddWithValue("@SITEID", "");
}
else if (ddlSiteId.SelectedIndex > 0)
{
cmd.Parameters.AddWithValue("@SITEID", ddlSiteId.SelectedItem.Value);
}
else if (ddlSiteId.SelectedItem.Text != "All...")
{
cmd.Parameters.AddWithValue("@SITEID", ddlSiteId.SelectedItem.Value);
}
else
{
cmd.Parameters.AddWithValue("@SITEID", "");
}
//category
string CategoryList = "";
foreach (ListItem item in drpCAT.Items)
{
if (item.Selected)
{
if (CategoryList == "")
{
CategoryList += "" + item.Value.ToString() + "";
}
else
{
CategoryList += "," + item.Value.ToString() + "";
}
}
}
if (CategoryList.Length > 0)
{
cmd.Parameters.AddWithValue("@PRODUCTGROUP", CategoryList);
}
else
{
cmd.Parameters.AddWithValue("@PRODUCTGROUP", "");
}
//Subcategory
string SubCategoryList = "";
foreach (ListItem item in drpSUBCAT.Items)
{
if (item.Selected)
{
if (SubCategoryList == "")
{
SubCategoryList += "" + item.Value.ToString() + "";
}
else
{
SubCategoryList += "," + item.Value.ToString() + "";
}
}
}
if (SubCategoryList.Length > 0)
{
cmd.Parameters.AddWithValue("@PRODUCTSUBCATEGORY", SubCategoryList);
}
else
{
cmd.Parameters.AddWithValue("@PRODUCTSUBCATEGORY", "");
}
if (DDLBusinessUnit.SelectedIndex >= 1)
{
cmd.Parameters.AddWithValue("@BUCODE", DDLBusinessUnit.SelectedItem.Value.ToString());
}
else
{
cmd.Parameters.AddWithValue("@BUCODE", "");
}
DataTable dtDataByfilter = new DataTable();
dtDataByfilter = new DataTable();
dtDataByfilter.Load(cmd.ExecuteReader());
//=================Create Excel==========
//DataTable dt = new DataTable();
//dt = dtDataByfilter;
string attachment = "attachment; filename=AreaMonthMaterialSale.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dtDataByfilter.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dtDataByfilter.Rows)
{
tab = "";
for (i = 0; i < dtDataByfilter.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
// HttpContext.Current.ApplicationInstance.CompleteRequest();
//Response.End();
}
catch (Exception ex)
{
LblMessage.Text = ex.Message.ToString();
ErrorSignal.FromCurrentContext().Raise(ex);
}
finally
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
}
}
}
//ShowData_ForExcel();
}
//}
//catch (Exception ex)
//{
// LblMessage.Text = ex.Message.ToString();
//}
}
protected void drpCAT_SelectedIndexChanged(object sender, EventArgs e)
{
FillSubCategory();
}
protected void drpSUBCAT_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void drpSTATE_SelectedIndexChanged(object sender, EventArgs e)
{
FillSite();
}
private bool ValidateInput()
{
bool b;
if (txtCurrentDate.Text == string.Empty || txtBaseDate.Text == string.Empty)
{
b = false;
//LblMessage.Text = "Please Provide Current Date and Base Date";
}
else
{
b = true;
//LblMessage.Text = string.Empty;
}
if (txtCurrentDate.Text == txtBaseDate.Text)
{
b = false;
}
string StateList = "";
foreach (ListItem item in drpSTATE.Items)
{
if (item.Selected)
{
if (StateList == "")
{
StateList += "" + item.Value.ToString() + "";
}
else
{
StateList += "," + item.Value.ToString() + "";
}
}
}
if (StateList.Length > 0)
{
b = true;
}
else
{
b = false;
}
return b;
}
protected void ShowData_ForExcel()
{
CreamBell_DMS_WebApps.App_Code.Global obj = new CreamBell_DMS_WebApps.App_Code.Global();
string FilterQuery = string.Empty;
DataTable dtSetHeader = null;
//DataTable dtDataByfilter = null;
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
string query1 = "Select NAME from ax.inventsite where SITEID='" + Session["SiteCode"].ToString() + "'";
dtSetHeader = new DataTable();
dtSetHeader = obj.GetData(query1);
string query = string.Empty;
conn = new SqlConnection(obj.GetConnectionString());
conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
query = "ACX_USP_AREAMONTHMATERIALSALE";
cmd.CommandText = query;
DateTime stDate = Convert.ToDateTime(txtCurrentDate.Text);
DateTime firstDayOfMonth = new DateTime(stDate.Year, stDate.Month, 1);
cmd.Parameters.AddWithValue("@CURRENTSTDATE", firstDayOfMonth);
stDate = Convert.ToDateTime(txtBaseDate.Text);
firstDayOfMonth = new DateTime(stDate.Year, stDate.Month, 1);
cmd.Parameters.AddWithValue("@BASESTDATE", firstDayOfMonth);
cmd.Parameters.AddWithValue("@UserType", Convert.ToString(Session["LOGINTYPE"]));
cmd.Parameters.AddWithValue("@UserCode", Convert.ToString(Session["USERID"]));
//state
string StateList = "";
foreach (ListItem item in drpSTATE.Items)
{
if (item.Selected)
{
if (StateList == "")
{
StateList += "" + item.Value.ToString() + "";
}
else
{
StateList += "," + item.Value.ToString() + "";
}
}
}
if (StateList.Length > 0)
{
cmd.Parameters.AddWithValue("@StateId", StateList);
}
else
{
cmd.Parameters.AddWithValue("@StateId", "");
}
// site
if (ddlSiteId.SelectedIndex < 0)
{
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
string siteid = "";
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
foreach (DataRow row in dt.Rows)
{
if (siteid == "")
siteid = Convert.ToString(row["DISTRIBUTOR"]);
else
siteid += "," + row["DISTRIBUTOR"];
}
}
else
cmd.Parameters.AddWithValue("@SiteId", "");
}
else if (ddlSiteId.SelectedIndex > 0)
{
cmd.Parameters.AddWithValue("@SITEID", ddlSiteId.SelectedItem.Value);
}
else if (ddlSiteId.SelectedItem.Text != "All...")
{
cmd.Parameters.AddWithValue("@SITEID", ddlSiteId.SelectedItem.Value);
}
else
{
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
string siteid = "";
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
foreach (DataRow row in dt.Rows)
{
if (siteid == "")
siteid = Convert.ToString(row["DISTRIBUTOR"]);
else
siteid += "," + row["DISTRIBUTOR"];
}
cmd.Parameters.AddWithValue("@SiteId", siteid);
}
else
{
cmd.Parameters.AddWithValue("@SITEID", "");
}
//category
string CategoryList = "";
foreach (ListItem item in drpCAT.Items)
{
if (item.Selected)
{
if (CategoryList == "")
{
CategoryList += "" + item.Value.ToString() + "";
}
else
{
CategoryList += "," + item.Value.ToString() + "";
}
}
}
if (CategoryList.Length > 0)
{
cmd.Parameters.AddWithValue("@PRODUCTGROUP", CategoryList);
}
else
{
cmd.Parameters.AddWithValue("@PRODUCTGROUP", "");
}
//Subcategory
string SubCategoryList = "";
foreach (ListItem item in drpSUBCAT.Items)
{
if (item.Selected)
{
if (SubCategoryList == "")
{
SubCategoryList += "" + item.Value.ToString() + "";
}
else
{
SubCategoryList += "," + item.Value.ToString() + "";
}
}
}
if (SubCategoryList.Length > 0)
{
cmd.Parameters.AddWithValue("@PRODUCTSUBCATEGORY", SubCategoryList);
}
else
{
cmd.Parameters.AddWithValue("@PRODUCTSUBCATEGORY", "");
}
DataTable dtDataByfilter = new DataTable();
dtDataByfilter = new DataTable();
dtDataByfilter.Load(cmd.ExecuteReader());
//=================Create Excel==========
//DataTable dt = new DataTable();
//dt = dtDataByfilter;
string attachment = "attachment; filename=Test.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dtDataByfilter.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dtDataByfilter.Rows)
{
tab = "";
for (i = 0; i < dtDataByfilter.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
// HttpContext.Current.ApplicationInstance.CompleteRequest();
//Response.End();
}
}
catch (Exception ex)
{
LblMessage.Text = ex.Message.ToString();
ErrorSignal.FromCurrentContext().Raise(ex);
}
finally
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
if (Panel1.Visible == true)
{
Panel1.Visible = false;
LinkButton1.Text = "Show sales person filter";
}
else if (Panel1.Visible == false)
{
Panel1.Visible = true;
LinkButton1.Text = "hide sales person filter";
}
}
protected void fillHOS()
{
chkListHOS.Items.Clear();
DataTable dtHOS = (DataTable)Session["SaleHierarchy"];
DataTable uniqueCols = dtHOS.DefaultView.ToTable(true, "HOSNAME", "HOSCODE");
chkListHOS.DataSource = uniqueCols;
chkListHOS.DataTextField = "HOSNAME";
chkListHOS.DataValueField = "HOSCODE";
chkListHOS.DataBind();
if (uniqueCols.Rows.Count == 1)
{
chkListHOS.Items[0].Selected = true;
lstHOS_SelectedIndexChanged(null, null);
}
FillState(dtHOS);
}
protected void lstHOS_SelectedIndexChanged(object sender, EventArgs e)
{
chkListVP.Items.Clear();
chkListGM.Items.Clear();
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListHOS))
{
try{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
//chkListVP.Items.Clear();
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "VPNAME", "VPCODE");
chkListVP.DataSource = uniqueCols2;
chkListVP.DataTextField = "VPNAME";
chkListVP.DataValueField = "VPCODE";
chkListVP.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListVP.Items[0].Selected = true;
lstVP_SelectedIndexChanged(null, null);
}
else
{
chkListVP.Items[0].Selected = false;
}
FillState(dt);
uppanel.Update();
// chkListGM.Items.Clear();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void lstVP_SelectedIndexChanged(object sender, EventArgs e)
{
chkListGM.Items.Clear();
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListVP))
{
try
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "GMNAME", "GMCODE");
chkListGM.DataSource = uniqueCols2;
chkListGM.DataTextField = "GMNAME";
chkListGM.DataValueField = "GMCODE";
chkListGM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListGM.Items[0].Selected = true;
lstGM_SelectedIndexChanged(null, null);
}
else
{
chkListGM.Items[0].Selected = false;
}
FillState(dt);
uppanel.Update();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void lstGM_SelectedIndexChanged(object sender, EventArgs e)
{
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListGM))
{
try{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "DGMNAME", "DGMCODE");
chkListDGM.DataSource = uniqueCols2;
chkListDGM.DataTextField = "DGMNAME";
chkListDGM.DataValueField = "DGMCODE";
chkListDGM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListDGM.Items[0].Selected = true;
lstDGM_SelectedIndexChanged(null, null);
}
else
{
chkListDGM.Items[0].Selected = false;
}
FillState(dt);
uppanel.Update();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void lstDGM_SelectedIndexChanged(object sender, EventArgs e)
{
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListDGM))
{
try{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "RMNAME", "RMCODE");
chkListRM.DataSource = uniqueCols2;
chkListRM.DataTextField = "RMNAME";
chkListRM.DataValueField = "RMCODE";
chkListRM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListRM.Items[0].Selected = true;
lstRM_SelectedIndexChanged(null, null);
}
else
{
chkListRM.Items[0].Selected = false;
}
FillState(dt);
uppanel.Update();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
drpSTATE_SelectedIndexChanged(null, null);
//upsale.Update()
}
public Boolean CheckSelect(ref CheckBoxList ChkList)
{
foreach (System.Web.UI.WebControls.ListItem litem in ChkList.Items)
{
if (litem.Selected)
{
return true;
}
}
return false;
}
protected void lstRM_SelectedIndexChanged(object sender, EventArgs e)
{
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListRM))
{
try{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "ZMNAME", "ZMCODE");
chkListZM.DataSource = uniqueCols2;
chkListZM.DataTextField = "ZMNAME";
chkListZM.DataValueField = "ZMCODE";
chkListZM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListZM.Items[0].Selected = true;
lstZM_SelectedIndexChanged(null, null);
}
else
{
}
FillState(dt);
uppanel.Update();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void lstZM_SelectedIndexChanged(object sender, EventArgs e)
{
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
try{
if (CheckSelect(ref chkListZM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
chkListASM.Items.Clear();
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "ASMNAME", "ASMCODE");
chkListASM.DataSource = uniqueCols2;
chkListASM.DataTextField = "ASMNAME";
chkListASM.DataValueField = "ASMCODE";
chkListASM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListASM.Items[0].Selected = true;
lstASM_SelectedIndexChanged(null, null);
}
FillState(dt);
uppanel.Update();
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void lstASM_SelectedIndexChanged(object sender, EventArgs e)
{
//chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
try{
if (CheckSelect(ref chkListASM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
chkListEXECUTIVE.Items.Clear();
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "EXECUTIVENAME", "EXECUTIVECODE");
chkListEXECUTIVE.DataSource = uniqueCols2;
chkListEXECUTIVE.DataTextField = "EXECUTIVENAME";
chkListEXECUTIVE.DataValueField = "EXECUTIVECODE";
chkListEXECUTIVE.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListEXECUTIVE.Items[0].Selected = true;
}
FillState(dt);
uppanel.Update();
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void lstEXECUTIVE_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
FillState(dt);
uppanel.Update();
drpSTATE_SelectedIndexChanged(null, null);
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
try{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(chkAll, chkListHOS);
lstHOS_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(chkAll, chkListHOS);
chkListVP.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox1, chkListVP);
lstVP_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox1, chkListVP);
// chkListVP.Items.Clear();
chkListGM.Items.Clear();
//chkListRM.Items.Clear();
//chkListZM.Items.Clear();
//chkListASM.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox2, chkListGM);
lstGM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox2, chkListGM);
// chkListGM.Items.Clear();
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
try{
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox3, chkListDGM);
lstDGM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox3, chkListDGM);
//chkListGM.Items.Clear();
// chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void CheckBox4_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
try{
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox4, chkListRM);
lstRM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox4, chkListRM);
//chkListGM.Items.Clear();
// chkListDGM.Items.Clear();
//chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void CheckBox5_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
try{
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox5, chkListZM);
// chkListASM.Items.Clear();
lstZM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox5, chkListZM);
chkListASM.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void CheckBox6_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
try{
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox6, chkListASM);
// chkListASM.Items.Clear();
lstASM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox6, chkListASM);
//chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
}
drpSTATE_SelectedIndexChanged(null, null);
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void CheckBox7_CheckedChanged(object sender, EventArgs e)
{
CheckAll_CheckedChanged(CheckBox7, chkListEXECUTIVE);
drpSTATE_SelectedIndexChanged(null, null);
// chkListASM.DataSource = null;
}
protected void CheckAll_CheckedChanged(CheckBox CheckAll, CheckBoxList ChkList)
{
if (CheckAll.Checked == true)
{
for (int i = 0; i < ChkList.Items.Count; i++)
{
ChkList.Items[i].Selected = true;
}
}
else
{
for (int i = 0; i < ChkList.Items.Count; i++)
{
ChkList.Items[i].Selected = false;
}
}
}
protected void ddlSiteId_SelectedIndexChanged(object sender, EventArgs e)
{
try{
if (ddlSiteId.SelectedItem.Text != "All...")
{
string query = "select bm.bu_code,bu_desc from ax.acxsitebumapping sbp join ax.ACXBUMASTER bm on bm.bu_code = sbp.BU_CODE where SITEID = '" + ddlSiteId.SelectedValue.ToString() + "'";
DDLBusinessUnit.Items.Clear();
DDLBusinessUnit.Items.Add("All...");
baseObj.BindToDropDown(DDLBusinessUnit, query, "bu_desc", "bu_code");
}
else
{
DDLBusinessUnit.Items.Clear();
DDLBusinessUnit.Items.Add("All...");
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}
} |
using Grillisoft.FastCgi.Protocol;
namespace Grillisoft.FastCgi.Owin
{
public class OwinChannel : SimpleFastCgiChannel
{
Microsoft.Owin.OwinMiddleware pipeline;
public OwinChannel(ILowerLayer layer, ILoggerFactory loggerFactory, Microsoft.Owin.OwinMiddleware pipeline)
: base(layer, loggerFactory)
{
this.pipeline = pipeline;
}
protected override Request CreateRequest(ushort requestId, BeginRequestMessageBody body)
{
return new OwinRequest(requestId, body, pipeline);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace My_News
{
class Source
{
public int Id { get; set; }
public string Name { get; set; }
public string Homepage { get; set; }
public string Logo { get; set; }
public Source(int id=0, string name="", string hp ="", string logo="")
{
Id = id;
Name = name;
Homepage = hp;
Logo = logo;
}
}
}
|
using Plugin.Geolocator;
using SQLite;
using System;
using System.Collections.Generic;
using TravelApp.Model;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace TravelApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MapPage : ContentPage
{
public MapPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
var locator = CrossGeolocator.Current;
locator.PositionChanged += Locator_PositionChanged;
await locator.StartListeningAsync(TimeSpan.Zero, 100);
var position = await locator.GetPositionAsync();
var center = new Position(position.Latitude, position.Longitude);
var span = new MapSpan(center, 2, 2);
MyMap.MoveToRegion(span);
var postList = Post.GetPosts();
DisplayInMap(postList);
}
protected override async void OnDisappearing()
{
base.OnDisappearing();
var locator = CrossGeolocator.Current;
locator.PositionChanged -= Locator_PositionChanged;
await locator.StopListeningAsync();
}
private void DisplayInMap(List<Post> postList)
{
//Create pin for every post
foreach (var post in postList)
{
try
{
var position = new Position(post.Latitude, post.Longtitude);
var pin = new Pin()
{
Type = PinType.SavedPin,
Position = position,
Label = post.VenueName,
Address = post.Address
};
MyMap.Pins.Add(pin);
}
catch (NullReferenceException nre)
{
}
catch (Exception ex)
{
}
}
}
private void Locator_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
var center = new Position(e.Position.Latitude, e.Position.Longitude);
var span = new MapSpan(center, 2, 2);
MyMap.MoveToRegion(span);
}
}
} |
using MoneyWeb.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MoneyWeb.Models
{
public class OrcamentoModel
{
public int Id { get; set; }
public int IdPeriodo { get; set; }
public int IdItem { get; set; }
public decimal Valor { get; set; }
public TipoEnum Tipo { get; set; }
public string TipoNome
{
get { return Tipo.ToDisplayName(); }
}
public virtual PeriodoModel Periodo { get; set; }
public virtual ItemModel Item { get; set; }
public enum TipoEnum : byte
{
[Display(Name = "Orçamento Entrada")]
OrcamentoEntrada = 1,
[Display(Name = "Orçamento Saída")]
OrcamentoSaida = 2
}
}
public class OrcamentoClassificacaoModel
{
public int IdPeriodo { get; set; }
public int IdClassificacao { get; set; }
public decimal Total { get; set; }
}
public class OrcamentoCategoriaModel
{
public int IdPeriodo { get; set; }
public int IdCategoria { get; set; }
public decimal Total { get; set; }
}
public class OrcamentoItemModel
{
public int IdPeriodo { get; set; }
public int IdItem { get; set; }
public decimal Total { get; set; }
}
}
|
using Discord.Commands;
using JhinBot.Enums;
using JhinBot.Translator;
using System;
namespace JhinBot.Utils.Exceptions
{
public class BotException : Exception
{
public ICommandContext Context { get; }
public string Title { get; }
public string ModuleName { get; }
public new string StackTrace { get; set; }
public BotException(ICommandContext context, string title, string moduleName, string exceptionMsg, string stackTrace, Exception inner) : base(exceptionMsg, inner)
{
Context = context;
Title = title;
ModuleName = moduleName;
StackTrace = stackTrace;
}
public ExceptionType GetExceptionTypeFromInner()
{
var translator = new ExceptionTypeTranslator();
var ex = InnerException ?? new Exception();
return translator.Translate(ex);
}
}
}
|
namespace FKFormBase
{
public class ErrorItems
{
public string ControlID { get; set; }
public string ValidateType { get; set; }
public string ErrorStr { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ToDoListApplication.BusinessLayer.Entities;
namespace ToDoListApplication.BusinessLayer.Repositories.Data
{
public interface IEntityData
{
}
}
|
using Puppeteer.Core;
using Puppeteer.Core.Configuration;
using System;
using System.Collections.Generic;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UIElements;
namespace Puppeteer.UI
{
internal class GoalView : PuppeteerView
{
public GoalView(VisualElement _rootElement, VisualElement _leftPanel, VisualElement _rightPanel, Action<Guid> _updateLastSelectedCallback)
: base(_rootElement, _leftPanel, _rightPanel)
{
m_Label = "Goals";
tooltip = "Create and configure the goals that agents want to achieve.";
var visualTreeAsset = Resources.Load<VisualTreeAsset>("LayoutGoalConfigurator");
visualTreeAsset.CloneTree(m_ConfiguratorElement);
PuppeteerManager.Instance.LoadDescriptionsOfType<GoalDescription>();
m_SerialisedGoals = PuppeteerManager.Instance.GetGoalDescriptions();
for (int i = 0; i < m_SerialisedGoals.Count; ++i)
{
CreateGoalListItem(m_SerialisedGoals[i]);
}
m_ContextMenuScrollView = new ContextualMenuManipulator(_menubuilder =>
{
_menubuilder.menu.AppendAction("Create New Goal", _dropDownMenuAction => { AddNewGoalListItem(); }, DropdownMenuAction.Status.Normal);
});
m_OnUpdateSerialisedLastSelected = _updateLastSelectedCallback;
OnListItemSelectedOrRemoved = ListItemSelectedOrRemoved;
}
public override void AddNewBasedOnSelection()
{
if (m_SelectedGoalPartItem != null)
{
AddNewGoalPartItem();
}
else if (m_SelectedWorkingMemoryUtilityItem != null)
{
AddNewUtilityItem();
}
else if (m_SelectedListItem != null)
{
AddNewGoalListItem();
}
}
public override void ClearSelection()
{
if (m_SelectedGoalPartItem != null)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, null);
}
else if (m_SelectedWorkingMemoryUtilityItem != null)
{
UpdateSelectedUtilityItem(null);
}
else
{
base.ClearSelection();
}
}
public override void CloseView()
{
base.CloseView();
m_AddButton.clickable.clicked -= AddNewGoalListItem;
m_ListItemScrollView.RemoveManipulator(m_ContextMenuScrollView);
}
public override void DeleteSelection()
{
if (m_SelectedGoalPartItem != null)
{
PuppeteerEditorHelper.DeleteWorldStateItem(this, m_SelectedListItem as GoalListItem,
ref (m_SelectedListItem as GoalListItem).GetDescription().GoalParts, m_SelectedGoalPartItem, SelectNeighbourGoalPartItemIfNeeded);
}
else if (m_SelectedWorkingMemoryUtilityItem != null)
{
DeleteUtilityItem(m_SelectedWorkingMemoryUtilityItem);
}
else
{
base.DeleteSelection();
}
}
public override void DuplicateSelection()
{
if (m_SelectedGoalPartItem != null)
{
AddNewGoalPartItem(new WorldStateDescription(m_SelectedGoalPartItem.GetWorldStateDescription()));
}
else if (m_SelectedWorkingMemoryUtilityItem != null)
{
AddNewUtilityItem(new UtilityDescription(m_SelectedWorkingMemoryUtilityItem.GetUtilityDescription()));
}
else if (m_SelectedListItem != null)
{
AddNewGoalListItem((m_SelectedListItem as GoalListItem).GetDescription());
}
}
public override void EnterSelection()
{
if (m_SelectedGoalPartItem != null)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, null);
}
else if (m_SelectedWorkingMemoryUtilityItem != null)
{
UpdateSelectedUtilityItem(m_SelectedWorkingMemoryUtilityItem);
}
else if (m_SelectedListItem != null)
{
if (m_GoalConfigurator != null && m_GoalConfigurator.GoalPartsContainer.childCount > 0)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, m_GoalConfigurator.GoalPartsContainer[0] as WorldStateItem);
}
}
}
public override void MoveSelection(MoveDirection _direction)
{
if (m_SelectedGoalPartItem != null)
{
SelectNeighbourGoalPartItem(_direction);
}
else if (m_SelectedWorkingMemoryUtilityItem != null)
{
SelectNeighbourUtilityItem(_direction);
}
else
{
base.MoveSelection(_direction);
}
}
public override void OpenView(SerialisedConfiguratorState _serialisedConfiguratorStates)
{
base.OpenView(_serialisedConfiguratorStates);
m_ListItemScrollViewHeader.text = "Available Goals";
m_ListItemScrollViewHeaderIcon.image = PuppeteerEditorResourceLoader.GoalIcon32.texture;
m_AddButton.clickable.clicked += AddNewGoalListItem;
m_AddButton.tooltip = "Create a new goal.";
m_ListItemScrollView.AddManipulator(m_ContextMenuScrollView);
for (int i = 0; i < m_ListItems.Count; ++i)
{
m_ListItemScrollView.Add(m_ListItems[i]);
}
if (m_SelectedListItem != null)
{
UpdateConfigurator();
}
else if (!_serialisedConfiguratorStates.LastOpenedGoal.Equals(Guid.Empty))
{
TryOpenEntry(_serialisedConfiguratorStates.LastOpenedGoal.Value);
}
else
{
DisableRightPanelContent();
}
}
public override void SaveAllChanges()
{
bool shouldSaveToFile = PuppeteerEditorHelper.RemoveDeletedItems<GoalListItem, GoalDescription>(m_SerialisedGoals, m_ListItems) > 0;
for (int i = 0; i < m_ListItems.Count; ++i)
{
shouldSaveToFile |= PuppeteerEditorHelper.AddOrUpdateInList<GoalListItem, GoalDescription>(m_SerialisedGoals, m_ListItems[i]);
}
bool successful = !shouldSaveToFile || PuppeteerManager.Instance.SaveGoals();
if (successful)
{
for (int i = 0; i < m_ListItems.Count; ++i)
{
m_ListItems[i].MarkUnsavedChanges(false);
TryClearUnsavedMarker();
}
}
}
public override void SaveSelectedChange()
{
bool shouldSaveToFile = PuppeteerEditorHelper.AddOrUpdateInList<GoalListItem, GoalDescription>(m_SerialisedGoals, m_SelectedListItem);
bool successful = !shouldSaveToFile || PuppeteerManager.Instance.SaveGoals();
if (successful)
{
m_SelectedListItem.MarkUnsavedChanges(false);
TryClearUnsavedMarker();
}
}
public override bool TryOpenEntry(Guid _guid)
{
var matchingItem = m_ListItems.Find(_entry => (_entry as GoalListItem).GetDescription().GUID == _guid);
if (matchingItem != null)
{
UpdateSelectedListItem(matchingItem);
return true;
}
else
{
return base.TryOpenEntry(_guid);
}
}
protected override void LazyInitConfigurator()
{
if (m_GoalConfigurator != null)
{
return;
}
m_GoalConfigurator = new GoalConfigurator
{
AddButton = m_ConfiguratorElement.Q<Button>(name: "addButton"),
DisplayName = m_ConfiguratorElement.Q<TextField>(name: "displayName"),
GoalPartsContainer = m_ConfiguratorElement.Q<VisualElement>(name: "goalParts"),
BaseUtility = m_ConfiguratorElement.Q<FloatField>(name: "baseUtility"),
UtilityContainer = m_ConfiguratorElement.Q<VisualElement>(name: "utilityParts"),
AddUtilityButton = m_ConfiguratorElement.Q<Button>(name: "addUtilityButton"),
GUIDLabel = m_RightPanelContent.Q<Label>(name: "GUIDLabel"),
};
m_GoalConfigurator.AddButton.clickable.clicked += AddNewGoalPartItem;
m_GoalConfigurator.AddUtilityButton.clickable.clicked += AddNewUtilityItem;
RegisterConfiguratorCallbacks();
}
protected override void UpdateConfigurator()
{
if (m_SelectedListItem is GoalListItem selectedGoalListItem)
{
EnableRightPanelContent();
LazyInitConfigurator();
GoalDescription selectedDescription = selectedGoalListItem.GetDescription();
m_GoalConfigurator.DisplayName.value = selectedDescription.DisplayName;
m_GoalConfigurator.GoalPartsContainer.Clear();
m_GoalConfigurator.BaseUtility.value = selectedDescription.BaseUtility;
m_GoalConfigurator.UtilityContainer.Clear();
m_GoalConfigurator.GUIDLabel.text = selectedDescription.GUID.ToString();
m_SelectedGoalPartItem = null;
m_SelectedWorkingMemoryUtilityItem = null;
for (int i = 0; i < selectedDescription.GoalParts.Length; ++i)
{
CreateGoalPartItem(selectedDescription.GoalParts[i]);
}
if (selectedDescription.UtilityParts != null)
{
for (int i = 0; i < selectedDescription.UtilityParts.Length; ++i)
{
CreateUtilityItem(selectedDescription.UtilityParts[i]);
}
}
}
}
private void AddNewGoalListItem()
{
GoalDescription goalDescription = new GoalDescription
{
DisplayName = "New Goal",
GoalParts = new WorldStateDescription[] { new WorldStateDescription() { Key = "New Goal Part", Value = false } },
UtilityParts = new UtilityDescription[] { },
BaseUtility = 5,
};
AddNewGoalListItem(goalDescription);
}
private void AddNewGoalListItem(GoalDescription _goalDescription)
{
GoalDescription newGoalDescription = new GoalDescription
{
GUID = Guid.NewGuid(),
DisplayName = _goalDescription.DisplayName,
GoalParts = new WorldStateDescription[_goalDescription.GoalParts.Length],
UtilityParts = new UtilityDescription[_goalDescription.UtilityParts.Length],
BaseUtility = _goalDescription.BaseUtility,
};
for (int i = 0; i < _goalDescription.GoalParts.Length; ++i)
{
newGoalDescription.GoalParts[i] = new WorldStateDescription(_goalDescription.GoalParts[i]);
}
for (int i = 0; i < _goalDescription.UtilityParts.Length; ++i)
{
newGoalDescription.UtilityParts[i] = new UtilityDescription(_goalDescription.UtilityParts[i]);
}
GoalListItem item = CreateGoalListItem(newGoalDescription);
m_ListItemScrollView.Add(item);
item.MarkUnsavedChanges(true);
AddUnsavedMarker();
UpdateSelectedListItem(item);
}
private void AddNewGoalPartItem()
{
AddNewGoalPartItem(new WorldStateDescription() { Key = "New Goal Part", Value = false });
}
private void AddNewGoalPartItem(WorldStateDescription _goalPart)
{
if (m_SelectedListItem is GoalListItem selectedGoalListItem)
{
GoalDescription selectedDescription = selectedGoalListItem.GetDescription();
int newIndex = PuppeteerEditorHelper.Append(ref selectedDescription.GoalParts, _goalPart);
WorldStateItem goalPartItem = CreateGoalPartItem(selectedDescription.GoalParts[newIndex]);
m_SelectedListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, goalPartItem);
}
}
private void AddNewUtilityItem()
{
AddNewUtilityItem(new UtilityDescription()
{
WorldStateName = "New Utility Curve",
UtilityCurve = AnimationCurve.Linear(0, 0, 1, 1),
CurveMultiplier = 1
});
}
private void AddNewUtilityItem(UtilityDescription _utilityDescription)
{
if (m_SelectedListItem is GoalListItem selectedGoalListItem)
{
GoalDescription selectedDescription = selectedGoalListItem.GetDescription();
int newIndex = PuppeteerEditorHelper.Append(ref selectedDescription.UtilityParts, _utilityDescription);
WorkingMemoryUtilityItem utilityItem = CreateUtilityItem(selectedDescription.UtilityParts[newIndex]);
m_SelectedListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
UpdateSelectedUtilityItem(utilityItem);
}
}
private void AnyUtilityItemValueChanged()
{
m_SelectedListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
}
private GoalListItem CreateGoalListItem(GoalDescription _goalDescription)
{
GoalListItem item = new GoalListItem(_goalDescription);
item.OnMouseDown += UpdateSelectedListItem;
item.OnDelete += DeleteListItem;
item.OnDuplicate += _item => AddNewGoalListItem((_item as GoalListItem).GetDescription());
m_ListItems.Add(item);
return item;
}
private WorldStateItem CreateGoalPartItem(WorldStateDescription _goalpart)
{
WorldStateItem goalPartItem = new WorldStateItem(_goalpart);
goalPartItem.OnMouseDown += _item =>
{
if (m_SelectedWorkingMemoryUtilityItem != null)
{
UpdateSelectedUtilityItem(null);
}
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, _item);
};
goalPartItem.OnDelete += _item =>
{
PuppeteerEditorHelper.DeleteWorldStateItem(this, m_SelectedListItem as GoalListItem,
ref (m_SelectedListItem as GoalListItem).GetDescription().GoalParts, _item, SelectNeighbourGoalPartItemIfNeeded);
};
goalPartItem.OnDuplicate += _item => AddNewGoalPartItem(new WorldStateDescription(_item.GetWorldStateDescription()));
goalPartItem.OnValueChanged += _item =>
{
m_SelectedListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
};
m_GoalConfigurator.GoalPartsContainer.Add(goalPartItem);
return goalPartItem;
}
private WorkingMemoryUtilityItem CreateUtilityItem(UtilityDescription _utilityDescription)
{
WorkingMemoryUtilityItem utilityItem = new WorkingMemoryUtilityItem(
_utilityDescription,
AnyUtilityItemValueChanged,
_item =>
{
if (m_SelectedGoalPartItem != null)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, null);
}
UpdateSelectedUtilityItem(_item);
},
DeleteUtilityItem,
DuplicateUtilityItem
);
m_GoalConfigurator.UtilityContainer.Add(utilityItem);
return utilityItem;
}
private void DeleteUtilityItem(WorkingMemoryUtilityItem _utilityItem)
{
SelectNeighbourUtilityItemIfNeeded(_utilityItem);
_utilityItem.RemoveFromHierarchy();
PuppeteerEditorHelper.Remove(ref (m_SelectedListItem as GoalListItem).GetDescription().UtilityParts, _utilityItem.GetUtilityDescription());
m_SelectedListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
}
private void DuplicateUtilityItem(WorkingMemoryUtilityItem _utilityItem)
{
AddNewUtilityItem(new UtilityDescription(_utilityItem.GetUtilityDescription()));
}
private void ListItemSelectedOrRemoved(ListItem _listItem)
{
if (_listItem == null)
{
m_OnUpdateSerialisedLastSelected?.Invoke(Guid.Empty);
}
else
{
m_OnUpdateSerialisedLastSelected?.Invoke((_listItem as GoalListItem).GetDescription().GUID);
}
}
private void RegisterConfiguratorCallbacks()
{
m_GoalConfigurator.DisplayName.RegisterCallback<FocusOutEvent>(_eventTarget =>
{
if (PuppeteerEditorHelper.UpdateDescriptionIfNecessary((_eventTarget.target as TextField), ref (m_SelectedListItem as GoalListItem).GetDescription().DisplayName))
{
m_SelectedListItem.ChangeText((_eventTarget.target as TextField).value);
m_SelectedListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
}
});
m_GoalConfigurator.BaseUtility.RegisterCallback<FocusOutEvent>(_eventTarget =>
{
if (m_SelectedListItem is GoalListItem selectedGoalListItem)
{
float currentUtility = selectedGoalListItem.GetDescription().BaseUtility;
float newUtility = (_eventTarget.target as FloatField).value;
if (currentUtility != newUtility)
{
selectedGoalListItem.GetDescription().BaseUtility = newUtility;
selectedGoalListItem.MarkUnsavedChanges(true);
AddUnsavedMarker();
}
}
});
}
private bool SelectNeighbourGoalPartItem(MoveDirection _direction)
{
if (_direction != MoveDirection.Up && _direction != MoveDirection.Down)
{
return false;
}
if (m_SelectedListItem is GoalListItem selectedGoalListItem)
{
GoalDescription description = selectedGoalListItem.GetDescription();
int index = m_GoalConfigurator.GoalPartsContainer.IndexOf(m_SelectedGoalPartItem);
if (index > 0 && _direction == MoveDirection.Up)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, m_GoalConfigurator.GoalPartsContainer[--index] as WorldStateItem);
return true;
}
else if (_direction == MoveDirection.Down)
{
if (index < description.GoalParts.Length - 1)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, m_GoalConfigurator.GoalPartsContainer[++index] as WorldStateItem);
}
else
{
if (m_GoalConfigurator.UtilityContainer.childCount > 0)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, null);
UpdateSelectedUtilityItem(m_GoalConfigurator.UtilityContainer[0] as WorkingMemoryUtilityItem);
}
}
return true;
}
}
return false;
}
private void SelectNeighbourGoalPartItemIfNeeded(WorldStateItem _goalPartItem)
{
if (_goalPartItem != m_SelectedGoalPartItem)
{
return;
}
bool neighbourSelected = SelectNeighbourGoalPartItem(MoveDirection.Up);
if (!neighbourSelected)
{
neighbourSelected |= SelectNeighbourGoalPartItem(MoveDirection.Down);
}
if (!neighbourSelected)
{
m_SelectedGoalPartItem = null;
}
}
private bool SelectNeighbourUtilityItem(MoveDirection _direction)
{
if (_direction != MoveDirection.Up && _direction != MoveDirection.Down)
{
return false;
}
if (m_SelectedListItem is GoalListItem selectedGoalListItem)
{
GoalDescription description = selectedGoalListItem.GetDescription();
int index = m_GoalConfigurator.UtilityContainer.IndexOf(m_SelectedWorkingMemoryUtilityItem);
if (_direction == MoveDirection.Up)
{
if (index > 0)
{
UpdateSelectedUtilityItem(m_GoalConfigurator.UtilityContainer[--index] as WorkingMemoryUtilityItem);
}
else if (index == 0)
{
int goalPartsChildCount = m_GoalConfigurator.GoalPartsContainer.childCount;
if (goalPartsChildCount > 0)
{
PuppeteerEditorHelper.UpdateSelectedWorldStateItem(ref m_SelectedGoalPartItem, m_GoalConfigurator.GoalPartsContainer[--goalPartsChildCount] as WorldStateItem);
UpdateSelectedUtilityItem(null);
}
}
return true;
}
else if (_direction == MoveDirection.Down && index < description.UtilityParts.Length - 1)
{
UpdateSelectedUtilityItem(m_GoalConfigurator.UtilityContainer[++index] as WorkingMemoryUtilityItem);
return true;
}
}
return false;
}
private void SelectNeighbourUtilityItemIfNeeded(WorkingMemoryUtilityItem _utilityItem)
{
if (_utilityItem != m_SelectedWorkingMemoryUtilityItem)
{
return;
}
bool neighbourSelected = SelectNeighbourUtilityItem(MoveDirection.Up);
if (!neighbourSelected)
{
neighbourSelected |= SelectNeighbourUtilityItem(MoveDirection.Down);
}
if (!neighbourSelected)
{
m_SelectedWorkingMemoryUtilityItem = null;
}
}
private void UpdateSelectedUtilityItem(WorkingMemoryUtilityItem _utilityItem)
{
if (m_SelectedWorkingMemoryUtilityItem != null)
{
m_SelectedWorkingMemoryUtilityItem.RemoveFromClassList("selectedWorldStateItem");
if (_utilityItem == m_SelectedWorkingMemoryUtilityItem)
{
m_SelectedWorkingMemoryUtilityItem = null;
return;
}
}
m_SelectedWorkingMemoryUtilityItem = _utilityItem;
_utilityItem?.AddToClassList("selectedWorldStateItem");
}
private readonly ContextualMenuManipulator m_ContextMenuScrollView;
private readonly Action<Guid> m_OnUpdateSerialisedLastSelected;
private readonly List<GoalDescription> m_SerialisedGoals;
private GoalConfigurator m_GoalConfigurator = null;
private WorldStateItem m_SelectedGoalPartItem = null;
private WorkingMemoryUtilityItem m_SelectedWorkingMemoryUtilityItem = null;
private class GoalConfigurator
{
public Button AddButton;
public Button AddUtilityButton;
public FloatField BaseUtility;
public TextField DisplayName;
public VisualElement GoalPartsContainer;
public Label GUIDLabel;
public VisualElement UtilityContainer;
}
}
} |
using System;
using System.IO;
using PacmanServiceLibrary.Model;
using PacmanServiceLibrary.Model.Enum;
using PacmanServiceLibrary.Service;
namespace Pacman
{
class MainClass
{
public static void Main(string[] args)
{
Location current = new Location();
bool inputChoiceMade = false;
Console.WriteLine(Constants.WELCOME);
Console.WriteLine(Constants.SELECT_INPUT_METHOD);
Console.WriteLine(Constants.INPUT_MANUAL);
Console.WriteLine(Constants.INPUT_IMPORT);
do
{
//step1. select input methond, manually enter or import file
Console.WriteLine(Constants.MAKE_A_SELECTION);
string InputChoice = Console.ReadLine();
if (Int32.TryParse(InputChoice, out int i))
{
inputChoiceMade = true;
if (i == 1)
{
//manually enter command
MannalEnterCommand(current);
}
if (i == 2)
{
//import file
ImportCommandFromFile(current);
Console.WriteLine(Constants.EXIT);
Console.ReadLine();
}
}
} while (!inputChoiceMade);
}
private static bool IsValid(Location loc)
{
return !(loc.X < Constants.MIN_X || loc.X > Constants.MAX_X || loc.Y < Constants.MIN_Y || loc.Y > Constants.MAX_Y);
}
private static void MannalEnterCommand(Location current)
{
bool exitNextLoop = false;
Console.WriteLine(Constants.READY_TO_ENTER);
//user can continue enter command until they enter EXIT to exit
do
{
string commandLine = Console.ReadLine();
if (commandLine.Trim().ToUpper().Equals(CommandEnum.EXIT.ToString().ToUpper()))
{
//enter EXIT to exit
exitNextLoop = true;
}
else
{
current = runCommand(current, commandLine);
}
} while (!exitNextLoop);
}
private static void ImportCommandFromFile(Location current)
{
bool fileExist = false;
string text = string.Empty;
//user need to input a valid file path to continue
do
{
Console.WriteLine(Constants.READY_TO_ENTER_PATH);
string filePath = Console.ReadLine();
if (File.Exists(filePath))
{
text = File.ReadAllText(filePath);
fileExist = true;
}
else{
Console.WriteLine(Constants.ERROR_FILE_NOT_EXIST);
}
} while (!fileExist);
//read file and run every command. (Environment.NewLine is to get line break for different systems, e.g.Mac or Windows)
var lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
//suppose each line has only one command
foreach (var commandLine in lines)
{
if (!String.IsNullOrEmpty(commandLine))
{
current = runCommand(current, commandLine);
}
}
//display final result
Console.WriteLine(CommandService.Report(current));
}
private static Location runCommand(Location current, string commandLine)
{
Command cmd = CommandService.GenerateCommand(commandLine);
if (cmd != null)
{
bool isValid = true;
Location newLoc = new Location();
switch (cmd.Operation)
{
case CommandEnum.PLACE:
newLoc = CommandService.Place(cmd.Parameter);
//check new location is valid or not
isValid = IsValid(newLoc);
current = isValid ? newLoc : current;
break;
case CommandEnum.MOVE:
newLoc = CommandService.Move(current);
//check new location is valid or not
isValid = IsValid(newLoc);
current = isValid ? newLoc : current;
break;
case CommandEnum.LEFT:
current = CommandService.Left(current);
break;
case CommandEnum.RIGHT:
current = CommandService.Right(current);
break;
case CommandEnum.REPORT:
Console.WriteLine(CommandService.Report(current));
break;
}
if ((cmd.Operation == CommandEnum.PLACE || cmd.Operation == CommandEnum.MOVE) && !isValid)
{
//prevent out of range
Console.WriteLine(Constants.ERROR_OUT_OF_RANGE);
}
}
else
{
//handle invalid command
Console.WriteLine(Constants.ERROR_INVALID_COMMAND);
}
return current;
}
}
}
|
using System;
using System.Collections.Generic;
namespace ServiceDeskSVC.DataAccess.Models
{
public partial class HelpDesk_TicketDocuments
{
public int Id { get; set; }
public string DocumentPath { get; set; }
public int TicketID { get; set; }
public virtual HelpDesk_Tickets HelpDesk_Tickets { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Euler_Logic.Problems.AdventOfCode.Y2016 {
public class Problem07 : AdventOfCodeBase {
public override string ProblemName => "Advent of Code 2016: 7";
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private int Answer1(List<string> input) {
return CountTLS(input);
}
private int Answer2(List<string> input) {
return CountSSL(input);
}
private int CountTLS(List<string> input) {
int count = 0;
foreach (var line in input) {
bool inBrackets = false;
bool isGood = false;
for (int index = 0; index < line.Length - 3; index++) {
if (line[index] == '[') {
inBrackets = true;
} else if (line[index] == ']') {
inBrackets = false;
} else if (line[index] == line[index + 3] && line[index + 1] == line[index + 2] && line[index] != line[index + 1]) {
if (inBrackets) {
isGood = false;
break;
} else {
isGood = true;
}
}
}
if (isGood) {
count++;
}
}
return count;
}
private int CountSSL(List<string> input) {
int count = 0;
foreach (var line in input) {
bool inBrackets = false;
var inRef = new HashSet<Tuple<char, char>>();
var outRef = new HashSet<Tuple<char, char>>();
for (int index = 0; index < line.Length - 2; index++) {
if (line[index] == '[') {
inBrackets = true;
} else if (line[index] == ']') {
inBrackets = false;
} else if (line[index] == line[index + 2] && line[index] != line[index + 1]) {
if (inBrackets) {
inRef.Add(new Tuple<char, char>(line[index], line[index + 1]));
} else {
outRef.Add(new Tuple<char, char>(line[index], line[index + 1]));
}
}
}
foreach (var isIn in inRef) {
var isOut = new Tuple<char, char>(isIn.Item2, isIn.Item1);
if (outRef.Contains(isOut)) {
count++;
break;
}
}
}
return count;
}
}
}
|
using Castle.MicroKernel.Registration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using MyFirstGitProject.Interfaces;
using MyFirstGitProject.Services;
namespace MyFirstGitProject.Interceptor
{
public class ServiceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For(typeof(IEmailService))
.ImplementedBy(typeof(EmailService))
.Interceptors(typeof(LoggingInterceptor)));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameOver : MonoBehaviour
{
private void Start()
{
Time.timeScale = 0;
}
public void QuitButton()
{
Time.timeScale = 1;
Destroy(gameObject);
SceneManager.LoadScene("MainMenu");
AudioManager.Play(AudioClipName.ClickButton);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PinchZoom : MonoBehaviour {
public float zoomSpeed = .0005f;
void Update()
{
Zoom();
}
void Zoom()
{
if(Input.touchCount == 2)
{
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
float deltaMagnitudediff = touchDeltaMag - prevTouchDeltaMag;
transform.localScale += Vector3.one * deltaMagnitudediff * zoomSpeed;
transform.localScale = Vector3.Max(transform.localScale, new Vector3 (0.0001f,0.0001f,0.0001f));
}
if (Input.GetAxis("Mouse ScrollWheel") > 0f ) // forward
{
transform.localScale += Vector3.one * zoomSpeed;
transform.localScale = Vector3.Max(transform.localScale, new Vector3 (0.0001f,0.0001f,0.0001f));
}
if (Input.GetAxis("Mouse ScrollWheel") < 0f ) // forward
{
transform.localScale += Vector3.one * -zoomSpeed;
transform.localScale = Vector3.Max(transform.localScale, new Vector3 (0.0001f,0.0001f,0.0001f));
}
}
}
|
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using System.Xml;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using BrightFuture.OilPrice;
using Newtonsoft.Json;
using System.Linq;
using System.Threading.Tasks;
using hap = HtmlAgilityPack;
using System.Net;
namespace BrightFuture.OilPrice
{
public static class OilPriceFeed
{
[FunctionName("OilPriceFeed")]
public static void Run(
[TimerTrigger("%cronScheduleExpressionSetting%")]TimerInfo myTimer,
[CosmosDB("oilprice", "oilpricecontainer", ConnectionStringSetting = "connectionStringSetting")] out dynamic document,
[CosmosDB("oilprice", "oilpricecontainer", ConnectionStringSetting = "connectionStringSetting", SqlQuery = "SELECT TOP 1 * FROM c ORDER BY c._ts DESC")] IEnumerable<OilPricePoint> latestOilPricePointsInput,
ILogger log)
{
log.LogInformation($"OilPriceFeed function executed at: {DateTime.Now}");
var latestOilPricePoint = GetLatestPricePoint(latestOilPricePointsInput);
var currentPricePoint = GetCurrentPricePoint();
var areEqual = currentPricePoint.DataEquals(latestOilPricePoint);
document = null;
var logMessage = string.Empty;
if (!areEqual)
{
document = currentPricePoint;
logMessage = "not ";
}
log.LogInformation($"Latest and current price points are {logMessage}equal");
}
private static OilPricePoint GetCurrentPricePoint()
{
// Replaces BuildOilPricePoint("https://www.jerseyfuelwatch.com/feeds/heating-oil-({0}-litrespence-per-litre).rss");
var dataList = GetDataList();
var currentPricePoint = new OilPricePoint();
currentPricePoint.Date = DateTime.Today;
currentPricePoint.litres500 = dataList.Select(d => new SupplierPrice { SupplierName = d[0], Price = d[1] }).ToList();
currentPricePoint.litres700 = dataList.Select(d => new SupplierPrice { SupplierName = d[0], Price = d[2] }).ToList();
currentPricePoint.litres900 = dataList.Select(d => new SupplierPrice { SupplierName = d[0], Price = d[3] }).ToList();
return currentPricePoint;
}
private static List<List<string>> GetDataList()
{
var webClient = new WebClient();
string page = webClient.DownloadString("https://pricecomparison.je/HeatingOil.aspx");
var doc = new hap.HtmlDocument();
doc.LoadHtml(page);
var fuelTable = doc.DocumentNode.SelectSingleNode("//div[@class='fuel_table']");
if (fuelTable is null)
throw new Exception("Cannot find HTML table");
var headers = fuelTable
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() == 4)
.Select(tr => tr.Elements("th").Select(td => td.InnerText.Trim()).ToList())
.ToList();
if (headers.Count != 1)
throw new Exception($"Unexpected number of headers {headers.Count}");
var headerData = headers[0];
if (headerData[1] != "500 Litres" || headerData[2] != "700 Litres" || headerData[3] != "900 Litres")
throw new Exception($"Malformed headers");
var dataList = fuelTable
.Descendants("tr")
.Skip(2)
.Where(tr => tr.Elements("td").Count() == 4)
.Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())
.ToList();
if (dataList is null)
throw new Exception("Malformed data");
return dataList;
}
private static OilPricePoint GetLatestPricePoint(IEnumerable<OilPricePoint> latestOilPricePointsInput)
{
var latestOilPricePoints = latestOilPricePointsInput.ToList();
if (latestOilPricePoints.Count > 1)
throw new Exception($"Should not retrieve more than one latest price point, got {latestOilPricePoints.Count}");
OilPricePoint LatestOilPricePoint = latestOilPricePoints.Count == 1 ? latestOilPricePoints[0] : null;
return LatestOilPricePoint;
}
// private static void RunOld(ILogger log, out dynamic document, IEnumerable<OilPricePoint> latestOilPricePointsInput)
// {
// log.LogInformation($"OilPriceFeed function executed at: {DateTime.Now}");
// var latestOilPricePoint = GetLatestPricePoint(latestOilPricePointsInput);
// var currentPricePoint = BuildOilPricePoint("https://www.jerseyfuelwatch.com/feeds/heating-oil-({0}-litrespence-per-litre).rss");
// var areEqual = currentPricePoint.DataEquals(latestOilPricePoint);
// document = null;
// var logMessage = string.Empty;
// if (!areEqual)
// {
// document = currentPricePoint;
// logMessage = "not ";
// }
// log.LogInformation($"Latest and current price points are {logMessage}equal");
// }
// private static OilPricePoint BuildOilPricePoint(string baseUrl)
// {
// var op = new OilPricePoint();
// op.Date = DateTime.Today;
// op.litres500 = GetAndConvertPrices(baseUrl, "500");
// op.litres700 = GetAndConvertPrices(baseUrl, "700");
// op.litres900 = GetAndConvertPrices(baseUrl, "900");
// return op;
// }
// private static List<SupplierPrice> GetAndConvertPrices(string baseUrl, string litres)
// {
// return ConvertToSupplierPriceList(GetPriceDictionaryFromUrl(string.Format(baseUrl, litres)));
// }
// private static List<SupplierPrice> ConvertToSupplierPriceList(Dictionary<string,string> prices)
// {
// var supplierPrices = new List<SupplierPrice>();
// foreach (var price in prices)
// {
// supplierPrices.Add(new SupplierPrice{SupplierName = price.Key, Price = price.Value});
// }
// return supplierPrices;
// }
private static Dictionary<string,string> GetPriceDictionaryFromUrl(string url)
{
var document = new XmlDocument();
var dictionary = new Dictionary<string,string>();
document.Load(url);
var titles = document.SelectNodes("rss/channel/item/title");
foreach (XmlNode title in titles)
{
//Each title should look something like this
//49.8p ATF Fuels
var pieces = title.InnerText.Split(new[] { ' ' }, 2);
dictionary.Add(pieces[1], pieces[0]);
}
return dictionary;
}
}
}
|
#nullable enable
using System;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Microsoft.Maui.TestUtils.DeviceTests.Runners.VisualRunner;
public class TestCaseViewModel : ViewModelBase
{
string? _message;
string? _output;
TestState _result;
RunStatus _runStatus;
string? _stackTrace;
TestResultViewModel _testResult;
internal TestCaseViewModel(string assemblyFileName, ITestCase testCase)
{
AssemblyFileName = assemblyFileName ?? throw new ArgumentNullException(nameof(assemblyFileName));
TestCase = testCase ?? throw new ArgumentNullException(nameof(testCase));
Result = TestState.NotRun;
RunStatus = RunStatus.NotRun;
Message = "🔷 not run";
// Create an initial result representing not run
_testResult = new TestResultViewModel(this, null);
}
public string AssemblyFileName { get; }
public string DisplayName => TestCase.DisplayName;
public string? Message
{
get => _message;
private set => Set(ref _message, value);
}
public string? Output
{
get => _output;
private set => Set(ref _output, value);
}
public TestState Result
{
get => _result;
private set => Set(ref _result, value);
}
public RunStatus RunStatus
{
get => _runStatus;
set => Set(ref _runStatus, value);
}
public string? StackTrace
{
get => _stackTrace;
private set => Set(ref _stackTrace, value);
}
public ITestCase TestCase { get; }
public TestResultViewModel TestResult
{
get => _testResult;
private set => Set(ref _testResult, value);
}
internal void UpdateTestState(TestResultViewModel message)
{
TestResult = message;
Output = message.TestResultMessage?.Output ?? string.Empty;
if (message.TestResultMessage is ITestPassed)
{
Result = TestState.Passed;
Message = $"✔ Success! {TestResult.Duration.TotalMilliseconds} ms";
RunStatus = RunStatus.Ok;
}
else if (message.TestResultMessage is ITestFailed failedMessage)
{
Result = TestState.Failed;
Message = $"⛔ {ExceptionUtility.CombineMessages(failedMessage)}";
StackTrace = ExceptionUtility.CombineStackTraces(failedMessage);
RunStatus = RunStatus.Failed;
}
else if (message.TestResultMessage is ITestSkipped skipped)
{
Result = TestState.Skipped;
Message = $"⚠ {skipped.Reason}";
RunStatus = RunStatus.Skipped;
}
else
{
Message = string.Empty;
StackTrace = string.Empty;
RunStatus = RunStatus.NotRun;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/**
* Tên Đề Tài; Phần Mền Quản Lý Biển Số Xe và Vi Phạm Giao Thông(VLNM (Vehicle license number management))
* Ho tên sinh viên:
* 1. Phan Nhật Tiến 0812515
* 2. Huỳnh Công Toàn 0812527
*
* GVHD. Trần Minh Triết
**/
namespace QLBSX_DAL_WS
{
public class ChiTietHVVPDTO
{
private int _MaChiTiet;
private HanhViViPhamDTO _HanhVi;
private object _BienSo;
private DateTime _ThoiGian;
private string _NguoiLapBienBan;
private double _TienPhat;
public int MaChiTiet
{
get { return _MaChiTiet; }
set { _MaChiTiet = value; }
}
public HanhViViPhamDTO HanhVi
{
get { return _HanhVi; }
set { _HanhVi = value; }
}
public object BienSo
{
get { return _BienSo; }
set { _BienSo = value; }
}
public DateTime ThoiGian
{
get { return _ThoiGian; }
set { _ThoiGian = value; }
}
public string NguoiLapBienBan
{
get { return _NguoiLapBienBan; }
set { _NguoiLapBienBan = value; }
}
public double TienPhat
{
get { return _TienPhat; }
set { _TienPhat = value; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable once CheckNamespace
namespace Microsoft.OpenApi.Models
{
public static class OpenApiPathsExtensions
{
public static List<KeyValuePair<string, OpenApiPathItem>> GetPathsStartingWithSegmentName(this OpenApiPaths urlPaths, string segmentName)
{
if (segmentName == null)
{
throw new ArgumentNullException(nameof(segmentName));
}
return urlPaths
.Where(x => x.IsPathStartingSegmentName(segmentName))
.ToList();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZC_IT_TimeTracking.BusinessEntities;
using ZC_IT_TimeTracking.DataAccess.Interfaces.GoalRepository;
using ZC_IT_TimeTracking.Services.Interfaces;
namespace ZC_IT_TimeTracking.Services.GoalRuleServices
{
public class GoalRuleService : ServiceBase,IGoalRuleServices
{
private IGoalRuleRepository _goalruleRepository;
public GoalRuleService()
{
_goalruleRepository = ZC_IT_TimeTracking.DataAccess.Factory.RepositoryFactory.GetInstance().GetGoalRuleRepository();
this.ValidationErrors = _goalruleRepository.ValidationErrors;
}
public List<GoalRule> GetGoalRules(int Goalid)
{
try
{
var GGRD = _goalruleRepository.GoalRuleDetailByIDDB(Goalid).ToList();
if (GGRD.Count != 0)
return GGRD;
else
{
this.ValidationErrors.Add("NO_RUL_DEF", "No Rules Define for Goal!");
return null;
}
}
catch
{
this.ValidationErrors.Add("ERR_FETCH_DATA", "Error While fetching Goal Rule!");
return null;
}
}
public bool InsertGoalRules(GoalRule gr)
{
GoalRule goalrule = new GoalRule();
goalrule.Performance_RangeFrom = gr.Performance_RangeFrom;
goalrule.Performance_RangeTo = gr.Performance_RangeTo;
goalrule.Rating = gr.Rating;
goalrule.GoalId = gr.GoalId;
return this._goalruleRepository.InsertGoalRuleDB(goalrule);
}
public bool DeleteAllGoalRule(int goalid)
{
try
{
var delete_rule = _goalruleRepository.DeleteAllRulesOfGoalByGoalID(goalid);
return true;
}
catch
{
this.ValidationErrors.Add("ERR_DEL_GOAL", "Error Ocurred while Deleting Goal Rule!");
return false;
}
}
}
}
|
namespace HEnCasa.App.Dominio{
public class SignoVital{
public int Id {get; set;}
public string FechaHora {get; set;}
public string Dolor {get; set;}
public string Temperatura {get; set;}
public string Saturacion {get; set;}
public string RitmoCardiaco {get; set;}
public string PresionArterial {get; set;}
}
} |
using UnityEngine;
using System.Collections;
using TNet;
public class TerminalControl : ShipControl {
[SerializeField]
protected Terminal shipCore;
void Update() {
//Resolve Docking Request
if( GetInput.Dock() ) {
tno.Send( "RequestDock", Target.Host );
}
#region Attitude Control
//Get input to update lookVector
if( PlayerSettings.currentProfile.interceptorLookMode == InterceptorLookMode.Free ) {
//Camera Changes
lookRotation = RotationProcess( lookRotation, transform.up );
targetLookDirectionToSync = lookRotation;
} else {
//TODO Flight input for Locked type
//Probably something to do with Screen Spaces
}
#endregion
#region Station Control
//Input Direction
inputDirectionSync = new Vector3( GetInput.ThrustX(), GetInput.ThrustY(), GetInput.ThrustZ() );
//Boost and Break
boostSync = GetInput.Boost();
breakButtonSync = GetInput.Break();
#endregion Station Control
//TODO Weapon Selection needs to be overhauled
WeaponSwitch();
WeaponFire();
UpdateCamera();
}
#region Weapon Switching and Firing
private bool isSelectingWeapons = false;
private TerminalWeaponStat weapon1 { get { return shipCore.status.weapon1; } }
private TerminalWeaponStat weapon2 { get { return shipCore.status.weapon2; } }
private TerminalWeaponStat weapon3 { get { return shipCore.status.weapon3; } }
protected virtual void WeaponFire() {
if( GetInput.Fire() ) {
if( weapon1.selected ) fireWeapon1ToSync = true;
if( weapon2.selected ) fireWeapon2ToSync = true;
if( weapon3.selected ) fireWeapon3ToSync = true;
} else {
fireWeapon1ToSync = false;
fireWeapon2ToSync = false;
fireWeapon3ToSync = false;
}
}
protected virtual void WeaponSwitch() {
//If any of the select button is released, and none of the buttons are currently being pressed, we can assume the player's finished selecting
if( GetInput.SelectWeaponKeyUp( 1 ) || GetInput.SelectWeaponKeyUp( 2 ) || GetInput.SelectWeaponKeyUp( 3 ) ) {
if( !GetInput.SelectWeaponKeyHeld( 1 ) && !GetInput.SelectWeaponKeyHeld( 2 ) && !GetInput.SelectWeaponKeyHeld( 3 ) ) {
isSelectingWeapons = false;
}
}
if( GetInput.SelectWeaponKeyDown( 1 ) || GetInput.SelectWeaponKeyDown( 2 ) || GetInput.SelectWeaponKeyDown( 3 ) ) {
if( !isSelectingWeapons ) {
weapon1.selected = false;
weapon2.selected = false;
weapon3.selected = false;
isSelectingWeapons = true;
}
if( GetInput.SelectWeaponKeyDown( 1 ) ) weapon1.selected = true;
if( GetInput.SelectWeaponKeyDown( 2 ) ) weapon2.selected = true;
if( GetInput.SelectWeaponKeyDown( 3 ) ) weapon3.selected = true;
}
}
#endregion Weapon Switching and Firing
#region Sync To Host
protected override void OnEnable() {
base.OnEnable();
targetLookDirectionToSync = transform.rotation;
StartCoroutine( SyncToHost() );
}
//Sync Variables
private Quaternion targetLookDirectionToSync = Quaternion.identity; //Our vector to rotate towards, which happens to also be our free look vector
private Vector3 inputDirectionSync = Vector3.zero;
private bool breakButtonSync = false;
private bool boostSync = false;
private bool fireWeapon1ToSync = false, fireWeapon2ToSync = false, fireWeapon3ToSync = false;
private IEnumerator SyncToHost() {
while( true ) {
tno.SendQuickly( 2, Target.Host, targetLookDirectionToSync, inputDirectionSync, breakButtonSync, boostSync, fireWeapon1ToSync, fireWeapon2ToSync, fireWeapon3ToSync );
yield return new WaitForSeconds( 1f / SessionManager.instance.maxNetworkUpdatesPerSecond );
}
}
protected override void OnDisable() {
base.OnDisable();
//Reset all variables on disable
targetLookDirectionToSync = Quaternion.identity;
inputDirectionSync = Vector3.zero;
breakButtonSync = false;
boostSync = false;
fireWeapon1ToSync = false;
fireWeapon2ToSync = false;
fireWeapon3ToSync = false;
}
#endregion Sync To Host
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MonitorLibrary
{
public class MonitorClass
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, int lParam);
private const uint WM_SYSCOMMAND = 0x0112;
private const uint SC_MONITORPOWER = 0xF170;
public void Close()
{
using (Form2 f2 = new Form2())
{
SendMessage(f2.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
}
return;
}
}
}
|
/*
* Created by SharpDevelop.
* User: admin
* Date: 8/7/2016
* Time: 2:11 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Configuration;
using System.Windows.Forms;
namespace Robot
{
/// <summary>
/// Description of GlobalVariables.
/// </summary>
public class GV
{
private static readonly GV _inst = new GV();
private const string SerialPortComKey = "SerialPortComKey";
public static GV Instance
{
get
{
return _inst;
}
}
public readonly WeightValue TotalBalanceWeight = new WeightValue();
public const int NB_INGREDIENTS = 7;
public const int NB_GROUPS = 8;
public GV()
{
}
public string GetSerialPortCom()
{
string comPort = ConfigurationManager.AppSettings[SerialPortComKey];
if (String.IsNullOrEmpty(comPort))
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add(SerialPortComKey, "COM3");
config.Save(ConfigurationSaveMode.Minimal);
return "COM3";
}
else
{
return comPort;
}
}
public void SetSerialPortCom(string COM)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove(SerialPortComKey);
config.AppSettings.Settings.Add(SerialPortComKey, COM);
config.Save(ConfigurationSaveMode.Minimal);
}
// public void UpdateWeight(double newWeight)
// {
// CurrentWeight.Set(newWeight);
// if (WeightChangedDel != null)
// {
// WeightChangedDel(CurrentWeight);
// }
// }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace MisskeyDotNet
{
public class Note
{
public string Id { get; set; } = "";
public DateTime CreatedAt { get; set; }
public string UserId { get; set; } = "";
public User User { get; set; } = null!;
public string? Text { get; set; }
public string? Cw { get; set; }
public string Visibility { get; set; } = "public";
public bool LocalOnly { get; set; }
public string[]? VisibleUserIds { get; set; }
public bool ViaMobile { get; set; }
public int RenoteCount { get; set; }
public int RepliesCount { get; set; }
public Dictionary<string, int> Reactions { get; set; } = new Dictionary<string, int>();
public string[]? Tags { get; set; }
public Emoji[] Emojis { get; set; } = Array.Empty<Emoji>();
public string[]? FileIds { get; set; }
public DriveFIle[]? Files { get; set; }
public string? ReplyId { get; set; }
public string? RenoteId { get; set; }
// channelId { get; set; }
// channel { get; set; }
// id { get; set; }
// name { get; set; }
// } { get; set; }
public string[]? Mentions { get; set; }
public string? Uri { get; set; }
public string? Url { get; set; }
public string? _featuredId_ { get; set; }
public string? _prId_ { get; set; }
public Note? Reply { get; set; }
public Note? Renote { get; set; }
}
} |
namespace Sentry.Internal.Extensions;
internal static class StreamExtensions
{
public static async Task<byte[]> ReadLineAsync(
this Stream stream,
CancellationToken cancellationToken = default)
{
// This approach avoids reading one byte at a time.
const int size = 128;
using var buffer = new PooledBuffer<byte>(size);
using var result = new MemoryStream(capacity: size);
var overreach = 0;
var found = false;
while (!found)
{
var bytesRead = await stream.ReadAsync(buffer.Array, 0, size, cancellationToken).ConfigureAwait(false);
if (bytesRead <= 0)
{
break;
}
for (var i = 0; i < bytesRead; i++)
{
if (buffer.Array[i] != '\n')
{
continue;
}
found = true;
overreach = bytesRead - i - 1;
bytesRead = i;
break;
}
result.Write(buffer.Array, 0, bytesRead);
}
stream.Position -= overreach;
return result.ToArray();
}
public static async Task SkipNewlinesAsync(this Stream stream, CancellationToken cancellationToken = default)
{
// We probably have very few newline characters to skip, so reading one byte at a time is fine here.
using var buffer = new PooledBuffer<byte>(1);
while (await stream.ReadAsync(buffer.Array, 0, 1, cancellationToken).ConfigureAwait(false) > 0)
{
if (buffer.Array[0] != '\n')
{
stream.Position--;
return;
}
}
}
public static async Task<byte[]> ReadByteChunkAsync(
this Stream stream,
int expectedLength,
CancellationToken cancellationToken = default)
{
using var buffer = new PooledBuffer<byte>(expectedLength);
var bytesRead = await stream.ReadAsync(buffer.Array, 0, expectedLength, cancellationToken)
.ConfigureAwait(false);
// The buffer is rented so we can't return it, plus it may be larger than needed.
// So we copy everything to a new buffer.
var result = new byte[bytesRead];
Array.Copy(buffer.Array, result, bytesRead);
return result;
}
// pre-creating this buffer leads to an optimized path when writing
private static readonly byte[] NewlineBuffer = {(byte)'\n'};
public static Task WriteNewlineAsync(this Stream stream, CancellationToken cancellationToken = default) =>
#pragma warning disable CA1835 // the byte-array implementation of WriteAsync is more direct than using ReadOnlyMemory<byte>
stream.WriteAsync(NewlineBuffer, 0, 1, cancellationToken);
#pragma warning restore CA1835
public static void WriteNewline(this Stream stream) => stream.Write(NewlineBuffer, 0, 1);
public static long? TryGetLength(this Stream stream)
{
try
{
return stream.Length;
}
catch
{
return null;
}
}
public static bool IsFileStream(this Stream? stream) =>
stream is FileStream || stream?.GetType().Name == "MockFileStream";
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PartStore.Services
{
public interface IVansService
{
IEnumerable<Van> GetVans();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ORM.Models
{
public static class Role
{
public const string Admin = "Admin";
public const string User = "User";
public const string AdminOrUser = Admin + ", " + User;
}
}
|
using Xunit;
using Rhino.Mocks.Exceptions;
namespace Rhino.Mocks.Tests.FieldsProblem
{
public class FieldProblem_RepeatsWithGenerate
{
[Fact]
public void RepeatTimes_Fails_When_Called_More_Then_Expected()
{
var interfaceMock = MockRepository.GenerateStrictMock<IRepeatsWithGenerate>();
interfaceMock.Expect(x => x.GetMyIntValue()).Repeat.Times(1).Return(4);
interfaceMock.GetMyIntValue();
var ex = Assert.Throws<ExpectationViolationException>(() => interfaceMock.GetMyIntValue());
Assert.Equal("IRepeatsWithGenerate.GetMyIntValue(); Expected #1, Actual #2.", ex.Message);
}
[Fact]
public void RepeatTimes_Works_When_Called_Less_Then_Expected()
{
var interfaceMock = MockRepository.GenerateStrictMock<IRepeatsWithGenerate>();
interfaceMock.Expect(x => x.GetMyIntValue()).Repeat.Times(2).Return(4);
interfaceMock.GetMyIntValue();
var ex = Assert.Throws<ExpectationViolationException>(() => interfaceMock.VerifyAllExpectations());
Assert.Equal("IRepeatsWithGenerate.GetMyIntValue(); Expected #2, Actual #1.", ex.Message);
}
}
public interface IRepeatsWithGenerate
{
int GetMyIntValue();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Services.Interfaces
{
public interface IErrorMessageService<T>
{
string AddSuccessMessage();
string UpdateSuccess();
string CrudFailureFailure();
string BadRequest(Exception ex);
string DeleteSuccess(object id);
string NullParameter();
string NotFound();
string ValidationError();
string DateValidation();
string TimeSlotTaken();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grenade : MonoBehaviour
{
public GameObject meshObj;
public GameObject effectObj;
public Rigidbody rigid;
void Start() {
StartCoroutine(Explosion());
}
IEnumerator Explosion() {
yield return new WaitForSeconds(3f); // 시간차 폭발을 위해 코루틴 선언
rigid.velocity = Vector3.zero;
rigid.angularVelocity = Vector3.zero;
meshObj.SetActive(false);
effectObj.SetActive(true);
RaycastHit[] rayHits =
Physics.SphereCastAll(transform.position,
15,
Vector3.up,
0f,
LayerMask.GetMask("Enemy"));
foreach(RaycastHit hitObj in rayHits) {
hitObj.transform.GetComponent<Enemy>().HitByGrenade(transform.position);
}
Destroy(gameObject, 5);
}
}
|
using UnityEngine;
using System.Collections;
public class SceneLobby : SceneBase
{
public override void Update()
{
}
public override void Restart()
{
}
public override void Terminate()
{
UIManager.Instance.CloseUI(eUIType.GameLobby);
}
public override void Enter()
{
StartCourotine(Loading());
}
IEnumerator Loading()
{
AsyncOperation cLoadLevelAsync = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync("2.GameLobby");
yield return cLoadLevelAsync;
UIManager.Instance.OpenUI(eUIType.GameLobby);
//UIManager.Instance.OpenUI(eUIType.ChapterSelector);
//UI_Title temp = UIManager.Instance.GetUI<UI_Title>(eUIType.GameLobby);
//temp.Initialize();
}
}
|
namespace cyrka.api.domain.projects
{
public class PaymentsState
{
public decimal EditorPayment { get; set; }
public decimal TranslatorPayment { get; set; }
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GameTimer : MonoBehaviour {
public static bool stop;
public static bool isDone;
public static string result;
public bool reverse;
public enum TimerMode {minutes = 0, seconds = 1};
public TimerMode timerMode = TimerMode.minutes;
public int startValue;
public int endValue;
public TextMesh textOutput;
public bool startAwake = true;
private int min, sec;
private string m,s;
[SerializeField] GameObject gameOver;
[SerializeField] translate trsrpt;
[SerializeField] translate trscrpt;
void Awake ()
{
isDone = false;
if(startAwake) stop = false; else stop = true;
if(timerMode == TimerMode.minutes)
{
if(reverse) sec = 60;
min = startValue;
}
else
{
sec = startValue;
}
if(!reverse)
{
if(endValue < startValue)
{
Debug.Log("Game Timer: В этом режиме, параметр 'End Value' не может быть меньше, чем 'Start Value'");
stop = true;
}
}
else
{
if(endValue > startValue)
{
Debug.Log("Game Timer: В этом режиме, параметр 'End Value' не может быть больше, чем 'Start Value'");
stop = true;
}
}
}
void Start ()
{
StartCoroutine (RepeatingFunction ());
trsrpt.GetComponent<translate> ();
}
IEnumerator RepeatingFunction ()
{
while(true)
{
if(!stop && !isDone) TimeCount();
yield return new WaitForSeconds(1);
}
}
void TimeCount ()
{
if(reverse)
{
if(timerMode == TimerMode.minutes)
{
if (sec < 0)
{
sec = 59;
min--;
}
if (min == endValue)
{
isDone = true;
}
}
else
{
if (sec == endValue)
{
isDone = true;
}
}
CurrentTime();
sec--;
}
else
{
if(timerMode == TimerMode.minutes)
{
if (sec > 59)
{
sec = 0;
min++;
}
if (min == endValue)
{
isDone = true;
}
}
else
{
if (sec == endValue)
{
isDone = true;
}
}
CurrentTime();
sec++;
}
}
void CurrentTime()
{
if (sec < 10) s = "0" + sec; else s = sec.ToString();
if (min < 10) m = "0" + min; else m = min.ToString();
}
void OnGUI()
{
switch(timerMode)
{
case TimerMode.minutes:
result = m;
break;
case TimerMode.seconds:
result = s;
break;
}
textOutput.text = result;
}
void Update()
{
if (isDone) {
gameOver.SetActive (true);
trsrpt.GameOver ();
trscrpt.GameOver ();
}
}
} |
using Autofac;
using Microsoft.AspNetCore.Identity;
using RestDDD.Application;
using RestDDD.Application.Interfaces;
using RestDDD.Application.Interfaces.Mappers;
using RestDDD.Application.Mappers;
using RestDDD.Domain.Core.Interfaces.Repositories;
using RestDDD.Domain.Core.Interfaces.Services;
using RestDDD.Domain.Services;
using RestDDD.Infraestructure.Data.Repositories;
namespace RestDDD.Infraestructure.CrossCutting.IOC
{
public class ConfigurationIOC
{
public static void Load(ContainerBuilder builder)
{
#region IOC
//apllications Services
builder.RegisterType<ApplicationServiceContato>().As<IApplicationServiceContato>();
builder.RegisterType<ApplicationServiceUsuario>().As<IApplicationServiceUsuario>();
builder.RegisterType<IdentityUser>();
//Services
builder.RegisterType<ServiceContato>().As<IServiceContato>();
builder.RegisterType<ServiceUsuario>().As<IServiceUsuario>();
//Repositories
builder.RegisterType<RepositoryContato>().As<IRepositoryContato>();
builder.RegisterType<RepositoryUsuario>().As<IRepositoryUsuario>();
//Mappers
builder.RegisterType<MapperContato>().As<IMappersContato>();
builder.RegisterType<MapperUsuario>().As<IMapperUsuario>();
#endregion
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
using Ninject;
using SportsStore.Domain.Entities;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Concrete;
using SportsStore.WebUI.Infrastructure.Abstract;
using SportsStore.WebUI.Infrastructure.Concrete;
namespace SportsStore.WebUI.Infrastructure
{
// реализация пользовательской фабрики контроллеров,
// наследуясь от фабрики используемой по умолчанию
public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel _ninjectKernel;
public NinjectControllerFactory()
{
// создание контейнера
_ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
// получение объекта контроллера из контейнера
// используя его тип
return controllerType == null
? null
: (IController)_ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
// конфигурирование контейнера
_ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>();
EmailSettings emailSettings = new EmailSettings
{
WriteAsFile = bool.Parse(ConfigurationManager
.AppSettings["Email.WriteAsFile"] ?? "false")
};
_ninjectKernel.Bind<IOrderProcessor>()
.To<EmailOrderProcessor>()
.WithConstructorArgument("settings", emailSettings);
_ninjectKernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
}
}
} |
using System;
namespace EssentialLesson16Task2
{
// Задание 2
//Создайте класс Block с 4-мя полями сторон, переопределите в нем методы:
//Equals – способный сравнивать блоки между собой,
//ToString – возвращающий информацию о полях блока.
class Program
{
static void Main(string[] args)
{
Block b1 = new Block(1,2,3,4);
Block b2 = new Block(1,2,4,3);
Block b3 = b1;
Console.WriteLine(b1.GetHashCode());
Console.WriteLine(b2.GetHashCode());
Console.WriteLine(b3.GetHashCode());
Console.WriteLine(b1.Equals(b2));
Console.WriteLine(b3.Equals(b2));
Console.WriteLine(b3.Equals(b1));
}
}
}
|
using UnityEditor;
using UnityEditor.EditorTools;
using UnityEditor.ShortcutManagement;
using UnityEngine;
public static class CentredToolManager
{
public static Quaternion TransformRotation { get => Selection.transforms.Length == 1 ? Selection.activeTransform.rotation : Quaternion.identity; }
public static Vector3 HandlePos
{
get => HandleUtility.GUIPointToWorldRay(new Vector2(SceneView.lastActiveSceneView.camera.pixelWidth, SceneView.lastActiveSceneView.camera.pixelHeight) / 2).GetPoint(10f);
}
public static bool ObjectsSelected { get => Selection.transforms.Length > 0 ? true : false; }
public static int SelectionLength { get => Selection.transforms.Length; }
[Shortcut("Centred Tools/Move Tool", KeyCode.W, ShortcutModifiers.Shift)]
static void SelectMoveTool()
{
EditorTools.SetActiveTool(typeof(MoveToolCentred));
}
[Shortcut("Centred Tools/Rotate Tool", KeyCode.E, ShortcutModifiers.Shift)]
static void SelectRotateTool()
{
EditorTools.SetActiveTool(typeof(RotateToolCentred));
}
[Shortcut("Centred Tools/Scale Tool", KeyCode.R, ShortcutModifiers.Shift)]
static void SelectScaleTool()
{
EditorTools.SetActiveTool(typeof(ScaleToolCentred));
}
} |
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
using Sentry.AspNetCore;
// ReSharper disable once CheckNamespace
namespace Microsoft.AspNetCore.Hosting;
/// <summary>
/// Extension methods to <see cref="IWebHostBuilder"/>
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class SentryWebHostBuilderExtensions
{
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
public static IWebHostBuilder UseSentry(this IWebHostBuilder builder)
=> UseSentry(builder, (Action<SentryAspNetCoreOptions>?)null);
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="dsn">The DSN.</param>
public static IWebHostBuilder UseSentry(this IWebHostBuilder builder, string dsn)
=> builder.UseSentry(o => o.Dsn = dsn);
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureOptions">The configure options.</param>
public static IWebHostBuilder UseSentry(
this IWebHostBuilder builder,
Action<SentryAspNetCoreOptions>? configureOptions)
=> builder.UseSentry((_, options) => configureOptions?.Invoke(options));
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureOptions">The configure options.</param>
public static IWebHostBuilder UseSentry(
this IWebHostBuilder builder,
Action<WebHostBuilderContext, SentryAspNetCoreOptions>? configureOptions)
=> builder.UseSentry((context, sentryBuilder) =>
{
sentryBuilder.AddSentryOptions(options =>
{
configureOptions?.Invoke(context, options);
options.SetEnvironment(context.HostingEnvironment);
});
});
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureSentry">The Sentry builder.</param>
public static IWebHostBuilder UseSentry(
this IWebHostBuilder builder,
Action<ISentryBuilder>? configureSentry) =>
builder.UseSentry((_, sentryBuilder) => configureSentry?.Invoke(sentryBuilder));
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureSentry">The Sentry builder.</param>
public static IWebHostBuilder UseSentry(
this IWebHostBuilder builder,
Action<WebHostBuilderContext, ISentryBuilder>? configureSentry)
{
// The earliest we can hook the SDK initialization code with the framework
// Initialization happens at a later time depending if the default MEL backend is enabled or not.
// In case the logging backend was replaced, init happens later, at the StartupFilter
_ = builder.ConfigureLogging((context, logging) =>
{
logging.AddConfiguration();
var section = context.Configuration.GetSection("Sentry");
_ = logging.Services.Configure<SentryAspNetCoreOptions>(section);
_ = logging.Services
.AddSingleton<IConfigureOptions<SentryAspNetCoreOptions>, SentryAspNetCoreOptionsSetup>();
_ = logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreLoggerProvider>();
_ = logging.AddFilter<SentryAspNetCoreLoggerProvider>(
"Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware",
LogLevel.None);
var sentryBuilder = logging.Services.AddSentry();
configureSentry?.Invoke(context, sentryBuilder);
});
_ = builder.ConfigureServices(c => _ =
c.AddTransient<IStartupFilter, SentryStartupFilter>()
.AddTransient<SentryMiddleware>()
);
return builder;
}
/// <summary>
/// Adds and configures the Sentry tunneling middleware.
/// </summary>
/// <param name="services">The service collection</param>
/// <param name="hostnames">
/// The extra hostnames to be allowed for the tunneling.
/// Hosts ending in <c>.sentry.io</c> are always allowed, and do not need to be included in this list.
/// Add your own domain if you use a self-hosted Sentry or Relay.
/// </param>
public static void AddSentryTunneling(this IServiceCollection services, params string[] hostnames) =>
services.AddScoped(_ => new SentryTunnelMiddleware(hostnames));
/// <summary>
/// Adds the <see cref="SentryTunnelMiddleware"/> to the pipeline.
/// </summary>
/// <param name="builder">The app builder.</param>
/// <param name="path">The path to listen for Sentry envelopes.</param>
public static void UseSentryTunneling(this IApplicationBuilder builder, string path = "/tunnel") =>
builder.Map(path, applicationBuilder =>
applicationBuilder.UseMiddleware<SentryTunnelMiddleware>());
}
|
using System;
using IoTManager.Model;
namespace IoTManager.Utility.Serializers
{
public class SeveritySerializer
{
public SeveritySerializer()
{
this.id = 0;
this.severityName = null;
this.createTime = null;
this.updateTime = null;
}
public SeveritySerializer(SeverityModel severityModel)
{
this.id = severityModel.Id;
this.severityName = severityModel.SeverityName;
this.createTime = severityModel.CreateTime
.ToString(Constant.getDateFormatString());
this.updateTime = severityModel.UpdateTime
.ToString(Constant.getDateFormatString());
}
public int id { get; set; }
public String severityName { get; set; }
public String createTime { get; set; }
public String updateTime { get; set; }
}
} |
using System.Collections.Generic;
namespace Compiler.TreeStructure
{
public class GenericClass : Class
{
public GenericClass(ClassName name) : base(name)
{
SelfClassName = name;
name.Parent = this;
}
public GenericClass(Class @class) : base(@class)
{
}
public GenericClass(GenericClass @class) : base(@class)
{
GenericParams = @class.GenericParams;
}
public List<string> GenericParams { get; set; } = new List<string>();
public Dictionary<ClassName, List<ICommonTreeInterface>> References { get; set; } =
new Dictionary<ClassName, List<ICommonTreeInterface>>();
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MeriMudra.Models.ViewModels
{
public class FeesAndCharge
{
[Required]
public string HeadingText { get; set; }
[Required]
public List<KeyValuePair<string, string>> Points { get; set; }
}
} |
using System.Collections.Generic;
namespace ShoppingListApi.Models.ResponseModels
{
public class ShoppingList
{
public int Count{ get; set; }
public List<ShoppingListItem> Data { get; set; }
}
} |
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestProject1.Pages
{
public class Page
{
protected IWebDriver driver;
protected WebDriverWait wait;
public string url = ConfigurationSettings.AppSettings["url"];
byte timeWait = Convert.ToByte(ConfigurationSettings.AppSettings["timeWait"]);
internal Page(IWebDriver Driver)
{
driver = Driver;
}
public Page(IWebDriver Driver, WebDriverWait wait) : this(Driver)
{
this.wait = wait;
}
public void WaitForAllScriptsLoaded()
{
var jsexe = (IJavaScriptExecutor)driver;
bool watcher = false;
while (watcher)
{
var status = jsexe.ExecuteScript("return document.readyState");
if (status == "complete") { watcher = true; }
}
}
public void WaitUntilTagAppear()
{
var select = wait.Until(ExpectedConditions.ElementExists(By.TagName("tag")));
}
public void WaitUntilElementClicable(string selector)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(selector)));
}
public void WaitForTextOnPage(String selector)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(d =>
{
try
{
driver.FindElement(By.CssSelector(selector));
}
catch (NoSuchElementException e)
{
return false;
}
return true;
});
}
public void WaitForTextOnPageByClassName(String classname)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
var element = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(classname)));
}
public void MoveTheSubmenu(string selector)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
var element = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(selector)));
Actions action = new Actions(driver);
action.MoveToElement(element).Perform();
}
public void ClickOn(String element)
{
driver.FindElement(By.CssSelector(element)).Click();
}
public void RightClickOn(String selector)
{
Actions action = new Actions(driver);
IWebElement element = driver.FindElement(By.CssSelector(selector));
action.ContextClick(element).Perform();
}
public void ClickOnById(String element)
{
driver.FindElement(By.Id(element)).Click();
}
public void ClickByXpath(String element)
{
driver.FindElement(By.XPath(element)).Click();
}
public void ClearAndFillField(string field, string text)
{
ClearField(field);
SendKeys(field, text);
}
public void FillField(string field, string text)
{
SendKeys(field, text);
}
public void ClearField(String field)
{
driver.FindElement(By.CssSelector(field)).Clear();
}
public void SendKeys(String keySelector, String keys)
{
driver.FindElement(By.CssSelector(keySelector)).SendKeys(keys);
}
public void NavigateTo(string url)
{
driver.Navigate().GoToUrl(url);
}
public void AssertFieldTextIsEqualTo(string expectedText, string cssSelector)
{
var fiu = driver.FindElement(By.CssSelector(cssSelector));
Assert.AreEqual(expectedText, fiu.Text);
}
public void CheckIfContainsText(string expectedText, string cssSelector)
{
string text = driver.FindElement(By.CssSelector(cssSelector)).Text;
if (text.Contains(expectedText)) { }
else
{
throw new Exception("Actual text doesn't match with expected.");
}
}
public void SelectElement(string elementSelector, string text)
{
new SelectElement(driver.FindElement(By.CssSelector(elementSelector))).SelectByText(text);
}
public void Submit()
{
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
public void WindowsSenKeys(string text)
{
System.Windows.Forms.SendKeys.SendWait(text);
}
public bool isClickable(IWebElement selector, IWebDriver driver)
{
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.ElementToBeClickable(selector));
return true;
}
catch (Exception e)
{
return false;
}
}
public void PageGoDownWhenClickable(string selector)
{
if(!isClickable(driver.FindElement(By.CssSelector(selector)),driver))
{
System.Windows.Forms.SendKeys.SendWait("{DOWN}");
StaticWait(500);
}
}
public void PageGoDown(string selector, string key, int downStep)
{
for (int i = 1; i < downStep; i++)
{
System.Windows.Forms.SendKeys.SendWait(key);
// StaticWait(100);
}
}
public void SwitchToWindow(Expression<Func<IWebDriver, bool>> predicateExp)
{
var predicate = predicateExp.Compile();
foreach (var handle in driver.WindowHandles)
{
driver.SwitchTo().Window(handle);
if (predicate(driver))
{
return;
}
}
throw new ArgumentException(string.Format("Unable to find window with condition: '{0}'", predicateExp.Body));
}
public void CheckIsElementNotDisplayed(string notExpectedObject)
{
Assert.AreEqual(false, driver.FindElement(By.CssSelector(notExpectedObject)).Displayed);
}
public void ClickByPartialHref(string partialHref)
{
driver.FindElement(By.XPath("//a[contains(@href,'" + partialHref + "')]")).Click();
}
public void SelectElementEnabled(string elementselector, string text)
{
var zmienna = driver.FindElement(By.CssSelector(elementselector));
if (zmienna != null)
{
IWebElement element = zmienna;
if (element.Displayed && element.Enabled)
{
SelectElement(elementselector, text);
}
}
}
public void SetCheckboxChecked(string elementSelector, bool isChecked)
{
if (GetCheckboxChecked(elementSelector) != isChecked)
{
driver.FindElement(By.CssSelector(elementSelector)).Click();
}
}
public bool GetCheckboxChecked(string elementSelector)
{
return driver.FindElement(By.CssSelector(elementSelector)).Selected;
}
public void SlideSlider(string Selector)
{
IWebElement slider = driver.FindElement(By.CssSelector(Selector));
Actions action = new Actions(driver);
action.ClickAndHold(slider);
StaticWait(500);
action.MoveByOffset(100, 0).Perform();
StaticWait(500);
action.Release().Build().Perform();
}
public void StaticWait(int time)
{
System.Threading.Thread.Sleep(time);
}
}
}
|
using Xunit;
namespace DotNetCross.Memory.Tests
{
public class Unsafe_Write_Test
{
public struct Bgr { public byte B; public byte G; public byte R; }
[Fact]
public unsafe void Int()
{
var ptr = stackalloc int[1];
*ptr = 17;
Unsafe.Write<int>(ptr, 42);
Assert.Equal(42, ptr[0]);
}
[Fact]
public unsafe void Double()
{
var ptr = stackalloc double[1];
*ptr = 17;
Unsafe.Write<double>(ptr, 42);
Assert.Equal(42, ptr[0]);
}
[Fact]
public unsafe void ValueType()
{
var ptr = stackalloc Bgr[1];
*ptr = new Bgr { B = 1, G = 2, R = 3 };
Unsafe.Write(ptr, new Bgr { B = 11, G = 22, R = 33 });
Assert.Equal(11, ptr[0].B);
Assert.Equal(22, ptr[0].G);
Assert.Equal(33, ptr[0].R);
}
}
}
|
using UltimateTool.Framework.Configuration;
using SFarmer = StardewValley.Farmer;
using SObject = StardewValley.Object;
namespace UltimateTool.Framework.Tools
{
internal class SeedTool : BaseTool
{
private readonly SeedsConfig Config;
public SeedTool(SeedsConfig config)
{
this.Config = config;
}
public override bool IsEnabled(SFarmer who, Tool tool, Item item, GameLocation location)
{
return this.Config.Enabled && item?.category == SObject.SeedsCategory;
}
public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, SFarmer who, Tool tool, Item item, GameLocation location)
{
if(item == null || item.Stack <= 0)
{
return false;
}
if(!(tileFeature is HoeDirt dirt) || dirt.crop != null)
{
return false;
}
bool planted = dirt.plant(item.parentSheetIndex, (int)tile.X, (int)tile.Y, who);
if (planted)
{
this.RemoveItem(who, item);
}
return planted;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Expenses.Data.Models
{
public class Expenses
{
public long Id { get; set; }
[Required]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required]
[Display(Name = "Amount")]
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
public double Amount { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
}
public class ExpenseReport
{
public ExpenseReport()
{
Report = new List<Expenses>();
Year = System.DateTime.Now.Year;
}
[Required]
[Display(Name = "Fiscal Year")]
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
public int FiscalYear { get; set; }
public int Year { get; set; }
public List<Expenses> Report { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AspNetAngular.Model;
namespace AspNetAngular.Controllers
{
[Route("api/controllers")]
[ApiController]
public class JobOrderMonitoring : ControllerBase
{
private readonly AtlanticContext _context;
public JobOrderMonitoring(AtlanticContext context)
{
_context = context;
}
[HttpGet("getJobOrder")]
public async Task<ActionResult<IEnumerable<JobOrder>>> getJobOrder(string cardName)
{
var jobOrderQuery = @"
select
case
when A.DocStatus = 'O'
then 'Open'
else 'Close'
end 'DocStatus',
A.DocNum,
'' 'ITRNo',
A.CardName,
A.DocDate,
'' 'Status',
(select datediff(d, z.DocDate, GETDATE()) from OPOR z where z.DocEntry = A.DocEntry and z.DocStatus = 'O') 'DaysDue',
'' 'ProdForecastNo',
A.U_Remarks 'DocRemarks'
from
OPOR A
--inner join IGE1 B on A.DocEntry = B.DocEntry
left join [@BOCODE] D on A.U_BranchCode = D.Code
where
A.DocStatus = 'O'
--and A.DocDate between '2019-08-01' and '2019-08-08'
and D.Name = {0}
";
var jobOrder = await _context.JobOrder.FromSql(jobOrderQuery, cardName).ToListAsync();
return jobOrder;
}
[HttpGet("getJobOrderDetails")]
public async Task<ActionResult<IEnumerable<JobOrderDetails>>> getJobOrderDetails(int docnum)
{
var jobOrderDetails = @"
select
b.ItemCode,
b.Dscription 'Description',
b.Quantity,
b.PriceAfVAT,
b.LineTotal
from
OPOR a
inner join POR1 b on a.DocEntry = b.DocEntry
where
a.DocNum = {0}
";
var orderDetails = await _context.JobOrderDetails.FromSql(jobOrderDetails, docnum).ToListAsync();
return orderDetails;
}
}
} |
using System;
using System.Globalization;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
// ReSharper disable InvertIf
namespace Atc.CodeAnalysis.CSharp.SyntaxFactories
{
public static class SyntaxLiteralExpressionFactory
{
public static LiteralExpressionSyntax Create(string value, SyntaxKind syntaxKind = SyntaxKind.StringLiteralExpression)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (syntaxKind == SyntaxKind.NumericLiteralExpression)
{
if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedInt))
{
return SyntaxFactory.LiteralExpression(syntaxKind, SyntaxFactory.Literal(parsedInt));
}
value = value.Replace(",", ".", StringComparison.Ordinal);
if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedDouble))
{
return SyntaxFactory.LiteralExpression(syntaxKind, SyntaxFactory.Literal(parsedDouble));
}
// Value cannot be parsed as number.
throw new ArgumentOutOfRangeException(nameof(value), "Cannot parse value as number");
}
return SyntaxFactory.LiteralExpression(syntaxKind, SyntaxFactory.Literal(value));
}
public static LiteralExpressionSyntax Create(int value)
{
return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(value));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using V50_IDOMBackOffice.AspxArea.Booking.Models;
using V50_IDOMBackOffice.AspxArea.Booking.Controllers;
using IdomOffice.Interface.BackOffice.Booking;
using V50_IDOMBackOffice.AspxArea.Helper;
using DevExpress.Web;
namespace V50_IDOMBackOffice.AspxArea.Booking.Forms
{
public partial class B2BCustomerView : System.Web.UI.Page
{
ICoreController controller = new B2BCustomerController();
protected void Page_Load(object sender, EventArgs e)
{
Bind();
}
private void Bind()
{
GridB2BCustomerView.DataSource = controller.Init();
GridB2BCustomerView.DataBind();
}
protected void GridB2BCustomerView_Init(object sender, EventArgs e)
{
GridB2BCustomerView.Columns["Id"].Visible = false;
}
protected void GridB2BCustomerView_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
{
string id = e.Keys[0].ToString();
controller.Delete(id);
e.Cancel = true;
GridB2BCustomerView.CancelEdit();
Bind();
}
protected void GridB2BCustomerView_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
CoreViewModel model = new CoreViewModel();
model.Address = e.NewValues["Address"].ToString();
model.Bank = e.NewValues["Bank"].ToString();
model.City = e.NewValues["City"].ToString();
model.Country = e.NewValues["Country"].ToString();
model.IBAN = e.NewValues["IBAN"].ToString();
model.Name = e.NewValues["Name"].ToString();
model.PersonalIdentificationNumber = e.NewValues["PersonalIdentificationNumber"].ToString();
model.ProviderId = (int)e.NewValues["ProviderId"];
controller.Add(model);
e.Cancel = true;
GridB2BCustomerView.CancelEdit();
Bind();
}
protected void GridB2BCustomerView_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
var list = (List<CoreViewModel>)GridB2BCustomerView.DataSource;
CoreViewModel model = list.Find(m => m.Id == e.Keys[0].ToString());
model.Address = e.NewValues["Address"].ToString();
model.Bank = e.NewValues["Bank"].ToString();
model.City = e.NewValues["City"].ToString();
model.Country = e.NewValues["Country"].ToString();
model.IBAN = e.NewValues["IBAN"].ToString();
model.Name = e.NewValues["Name"].ToString();
model.PersonalIdentificationNumber = e.NewValues["PersonalIdentificationNumber"].ToString();
model.ProviderId = (int)e.NewValues["ProviderId"];
controller.Update(model);
e.Cancel = true;
GridB2BCustomerView.CancelEdit();
Bind();
}
protected void GridB2BCustomerView_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
ASPxGridView grid = sender as ASPxGridView;
int index = e.VisibleIndex;
string id = grid.GetRowValues(index, "Id").ToString();
if (e.ButtonID=="ButtonContacts")
{
ASPxWebControl.RedirectOnCallback(VirtualPathUtility.ToAbsolute("~/AspxArea/Booking/Forms/B2BCustomerDetailsView.aspx?id=" + id));
}
if (e.ButtonID == "ButtonBookingProcess")
{
ASPxWebControl.RedirectOnCallback(VirtualPathUtility.ToAbsolute("~/AspxArea/Booking/Forms/B2BCustomerBookingDetailsView.aspx?id=" + id));
}
}
protected void GridB2BCustomerView_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
if (GridB2BCustomerView.IsNewRowEditing)
GridB2BCustomerView.DoRowValidation();
}
protected void GridB2BCustomerView_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
{
GridValidation.ValidateLength("Address",2, sender, e);
GridValidation.ValidateLength("Bank",2, sender, e);
GridValidation.ValidateLength("City",2, sender, e);
GridValidation.ValidateLength("Country",2, sender, e);
GridValidation.ValidateLength("IBAN",2, sender, e);
GridValidation.ValidateLength("Name",2, sender, e);
}
}
} |
using System;
using System.Reflection;
namespace SciVacancies.WebApp.Infrastructure.Saga
{
public class SagaFactory : IConstructSagas
{
public ISaga Build(Type type, Guid id)
{
ConstructorInfo constructor = type.GetConstructor(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] { typeof(Guid) },
null);
if (constructor==null) throw new ArgumentNullException("constructor is null");
return constructor.Invoke(new object[] { id }) as ISaga;
}
}
}
|
// This file is part of LAdotNET.
//
// LAdotNET is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// LAdotNET 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with LAdotNET. If not, see <https://www.gnu.org/licenses/>.
using DotNetty.Buffers;
using System.Text;
namespace LAdotNET.Extensions
{
public static class ByteBufferExt
{
/// <summary>
/// Write a length prefixed unicode string
/// </summary>
/// <param name="buffer"></param>
/// <param name="v"></param>
public static void WriteUnicodeString(this IByteBuffer buffer, string v)
{
var bytes = Encoding.Unicode.GetBytes(v);
buffer.WriteShortLE(bytes.Length / 2);
buffer.WriteBytes(bytes);
}
/// <summary>
/// Write a length prefixed ascii string
/// </summary>
/// <param name="buffer"></param>
/// <param name="v"></param>
public static void WriteString(this IByteBuffer buffer, string v)
{
var bytes = Encoding.ASCII.GetBytes(v);
buffer.WriteShortLE(bytes.Length / 2);
buffer.WriteBytes(bytes);
}
/// <summary>
/// Read a length prefixed unicode string
/// </summary>
/// <param name="buffer"></param>
/// <param name="v"></param>
public static string ReadUnicodeString(this IByteBuffer buffer)
{
var len = (buffer.ReadShortLE() * 2);
return buffer.ReadString(len, Encoding.Unicode);
}
/// <summary>
/// Read a length prefixed ascii string
/// </summary>
/// <param name="buffer"></param>
/// <param name="v"></param>
public static string ReadString(this IByteBuffer buffer)
{
var len = buffer.ReadShortLE();
return buffer.ReadString(len, Encoding.ASCII);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CalculadoraWS.Clases
{
public class Calcular
{
public decimal numero1 { get; set; }
public decimal numero2 { get; set; }
public decimal areacuadrado()
{
return numero1 * numero2;
}
public decimal areatriangulo()
{
return numero1 * numero2 /2;
}
public double areacirculo()
{
double pi;
double area;
var res= numero1 * numero1;
pi = Convert.ToDouble(3.1416);
area = Convert.ToDouble(res);
return pi * area;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace SoundServant.Controls
{
/// <summary>
/// Interaction logic for Track.xaml
/// </summary>
public partial class TrackReadOnlyControl : UserControl
{
StoredTrack track;
public delegate void VoidInvokeHandler();
public TrackReadOnlyControl(StoredTrack t)
{
InitializeComponent();
track = t;
Draw();
if (track.Current)
{
SS.TenthOfASecondTimer.Tick += new EventHandler(Timer_Tick);
track.Finished += new StoredTrack.VoidEventHandler(track_Finished);
}
else if (track.Error)
{
Time.Content = "Error";
Title.Content = track.ErrorMessage;
}
track.Updated += new StoredTrack.VoidEventHandler(track_Updated);
}
void track_Finished()
{
SS.TenthOfASecondTimer.Tick -= Timer_Tick;
track.Finished -= track_Finished;
Draw();
}
void Timer_Tick(object sender, EventArgs e)
{
Time.Content = SS.ParseTimeSpan(track.Length);
}
void track_Updated()
{
Draw();
}
private void Draw()
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (VoidInvokeHandler)delegate()
{
Title.Content = track.Title;
Time.Content = SS.ParseTimeSpan(track.Length);
Number.Content = "TRACK " + track.Number.ToString("00");
});
}
}
}
|
using System;
using System.ComponentModel.Design;
using System.Windows.Forms;
using Phenix.Core.Windows;
namespace Phenix.Services.Client.Security
{
internal class ReadWriteAuthorizationDesigner : ComponentDesigner
{
#region 属性
public IDesignerHost DesignerHost
{
get { return GetService(typeof(IDesignerHost)) as IDesignerHost; }
}
public ContainerControl RootComponent
{
get { return DesignerHost.RootComponent as ContainerControl; }
}
public ReadWriteAuthorization ReadWriteAuthorization
{
get { return Component as ReadWriteAuthorization; }
}
public override DesignerVerbCollection Verbs
{
get
{
base.Verbs.Add(new DesignerVerb(Phenix.Services.Client.Properties.Resources.ShowReadWriteAuthorizationRules,
new EventHandler(ShowReadWriteAuthorizationRules)));
return base.Verbs;
}
}
#endregion
#region 事件
private void ShowReadWriteAuthorizationRules(object sender, EventArgs e)
{
ShowMessageDialog.Execute(
Phenix.Services.Client.Properties.Resources.ShowReadWriteAuthorizationRules,
RootComponent.Name + Environment.NewLine + Environment.NewLine +
ReadWriteAuthorization.RuleMessage());
}
#endregion
#region 方法
public override void InitializeNewComponent(System.Collections.IDictionary defaultValues)
{
base.InitializeNewComponent(defaultValues);
IDesignerHost host = GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host == null)
return;
AppUtilities.ReferenceAssembly(this.GetService(typeof(ITypeResolutionService)) as ITypeResolutionService);
}
#endregion
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level37 : MonoBehaviour
{
public List<GameObject> solution;
public int counter = 0;
private void OnDestroy()
{
ClickListener.ObjClicked -= CheckClick;
}
private void Start()
{
ClickListener.ObjClicked += CheckClick;
}
private void CheckClick(GameObject go)
{
if (ReferenceEquals(go, solution[counter]))
{
counter++;
}
else
{
counter = 0;
}
CheckWin();
}
private void CheckWin()
{
if (counter == solution.Count)
{
Debug.Log("Win");
GameManager.instance.NextLevel();
}
}
} |
using System;
namespace Jypeli
{
public partial class FileManager
{
public event Action<Exception> ReadAccessDenied;
public event Action<Exception> WriteAccessDenied;
private void OnAccessDenied(Exception e, bool write)
{
if (!write && ReadAccessDenied != null)
ReadAccessDenied(e);
if (write && WriteAccessDenied != null)
WriteAccessDenied(e);
}
protected void FMAssert(Action func, bool write)
{
#if DEBUG
func();
#else
try
{
func();
}
catch ( Exception e )
{
OnAccessDenied( e, write );
}
#endif
}
protected void FMAssert<TP1>(Action<TP1> func, bool write, TP1 p1)
{
#if DEBUG
func(p1);
#else
try
{
func( p1 );
}
catch ( Exception e )
{
OnAccessDenied( e, write );
}
#endif
}
protected TR FMAssert<TR>(Func<TR> func, bool write, TR defaultVal)
{
#if DEBUG
return func();
#else
try
{
return func();
}
catch ( Exception e )
{
OnAccessDenied( e, write );
}
return defaultVal;
#endif
}
protected TR FMAssert<TP1, TR>(Func<TP1, TR> func, bool write, TR defaultVal, TP1 p1)
{
#if DEBUG
return func(p1);
#else
try
{
return func( p1 );
}
catch ( Exception e )
{
OnAccessDenied( e, write );
}
return defaultVal;
#endif
}
protected TR FMAssert<TP1, TP2, TR>(Func<TP1, TP2, TR> func, bool write, TR defaultVal, TP1 p1, TP2 p2)
{
#if DEBUG
return func(p1, p2);
#else
try
{
return func( p1, p2 );
}
catch ( Exception e )
{
OnAccessDenied( e, write );
}
return defaultVal;
#endif
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Game
{
/// <summary>This is our training dummy</summary>
public class DummyController : MonoBehaviour, IEntity
{
[SerializeField]
private Animator _animator;
/// <summary>Text to display hit counter</summary>
/// <remarks>Should probably be in a separate HUD class</remarks>
[SerializeField]
private Text _hitCounterText;
/// <summary>Delay before resetting the hit counter</summary>
[SerializeField]
private float _resetHitCounterDelay;
/// <summary>Number of hit received</summary>
private int _hitCounter;
/// <summary>Remaining delay before resetting the hit counter</summary>
private float _resetHitCounterRemaining;
private void Awake()
{
_hitCounterText.text = "";
}
private void Update()
{
// Reset and hide hit counter after some delay
if (_resetHitCounterRemaining > 0.0f)
{
_resetHitCounterRemaining -= Time.deltaTime;
if (_resetHitCounterRemaining <= 0.0f)
{
_hitCounter = 0;
_hitCounterText.text = "";
}
}
}
public void OnHitBy(AttackPhase attackPhase, AttackCollision attackCollision)
{
// Increment hit counter and reset timer
_hitCounter++;
_hitCounterText.text = $"{_hitCounter} hit";
_resetHitCounterRemaining = _resetHitCounterDelay;
// Trigger visual and audio effects
_animator.SetTrigger("Guard");
AudioManager.singleton.Play(attackPhase.attackId);
EffectManager.singleton.Play(attackPhase.attackId, attackCollision.position);
}
}
} |
namespace XH.Core.Context
{
public interface IWorkContextProvider
{
IWorkContext GetWorkContext();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.