text stringlengths 13 6.01M |
|---|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nusstudios.Common;
using Nusstudios.Models;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Nusstudios.Controllers
{
public class ArticlesController : Controller
{
public override void OnActionExecuting(ActionExecutingContext context) => base.OnActionExecuting(context);
[Route("{controller}/{action}/{gb?}")]
public IActionResult dijkstra(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "Dijkstra's shortest path" : "Dijkstra: legrövidebb útvonal", "https://nusstudios.com/Articles/dijkstra", false, false, isgb));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult heapsort(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "Heapsort" : "Kupacrendezés", "https://nusstudios.com/Articles/heapsort", false, false, isgb));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult mergesort(bool? gb)
{
string val;
return View(new ArticleViewModel("Mergesort", "https://nusstudios.com/Articles/mergesort", false, false, gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val))));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult knuthmorrispratt(bool? gb)
{
string val;
return View(new ArticleViewModel("Knuth-Morris-Pratt", "https://nusstudios.com/Articles/knuthmorrispratt", false, false, gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val))));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult floydstortoiseandhare(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "Floyd's tortoise and hare" : "Floyd: teknős és nyúl", "https://nusstudios.com/Articles/floydstortoiseandhare", false, true, isgb));
}
// GET: /<controller>/
[Route("{controller}/{action}/{gb?}")]
public IActionResult transformers_game_configurations_low_level(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "TF configs" : "TF konfigok", "https://nusstudios.com/Articles/transformers_game_configurations_low_level", false, false, isgb));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult youtube_ciphered_signatures(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "Youtube ciphered signatures" : "Youtube titkosított aláírások", "https://nusstudios.com/Articles/youtube_ciphered_signatures", false, true, isgb));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult graph_api_and_x_instagram_gis(bool? gb)
{
string val;
return View(new ArticleViewModel("Graph API & X-Instagram-GIS", "https://nusstudios.com/Articles/graph_api_and_x_instagram_gis", false, true, gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val))));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult paradigms_brief_history(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "Paradigms' history" : "A paradigmák története", "https://nusstudios.com/Articles/paradigms_brief_history", false, false, isgb));
}
[Route("{controller}/{action}/{gb?}")]
public IActionResult high_level_languages_behind_the_scenes(bool? gb)
{
string val;
bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val));
return View(new ArticleViewModel(isgb ? "High level languages" : "Magasszintű nyelvek", "https://nusstudios.com/Articles/high_level_languages_behind_the_scenes", false, false, isgb));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavior : MonoBehaviour
{
public float speed = 10;
public float airspeed = 10;
public float jumpHeight = 5;
public float gravity = 9.8f;
public int health = 3;
// animals now get recalled upon damage
//public int[] health = {3, 3};
public static int[] status = {1, -1, -1, -1};
public static int activeChar = 0;
public GameObject[] chars = {null, null};
public CharPanel charPanel;
PlayerCamera playerCamera;
CharacterController controller;
Animator anim;
Vector3 moveVector;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
anim.SetInteger("animState", 0);
activeChar = 0;
playerCamera = Camera.main.GetComponent<PlayerCamera>();
chars[0] = gameObject;
chars[1] = GameObject.FindGameObjectWithTag("Pet1");
chars[2] = GameObject.FindGameObjectWithTag("Pet2");
chars[3] = GameObject.FindGameObjectWithTag("Pet3");
}
void Update()
{
// only toggles between 0 and 1 for now
if (Input.GetKeyDown("f") & status[charPanel.target] != -1)
{
SwitchControl(charPanel.target);
}
if (Input.GetKeyDown("r") & charPanel.target != 0)
{
Recall(charPanel.target);
}
float moveHorizontal = Input.GetAxis("Horizontal") * Time.deltaTime;
float moveVertical = Input.GetAxis("Vertical") * Time.deltaTime;
Vector3 lateralMove = new Vector3(moveHorizontal, 0.0f, moveVertical).normalized * speed;
lateralMove = Quaternion.Euler(0, PlayerCamera.horizontal, 0) * lateralMove;
if (CheckGrounded()) {
moveVector = lateralMove;
if (Input.GetButton("Jump"))
{
if (activeChar == 3)
{
moveVector.y = Mathf.Sqrt(2 * FrogBehavior.frogJumpHeight * gravity);
} else
{
moveVector.y = Mathf.Sqrt(2 * jumpHeight * gravity);
}
if (activeChar == 0)
{
anim.SetInteger("animState", 2);
}
}
else {
moveVector.y = 0.0f;
if (moveVector == Vector3.zero)
{
if (activeChar == 0)
{
anim.SetInteger("animState", 0);
}
}
else
{
if (activeChar == 0)
{
anim.SetInteger("animState", 1);
}
}
}
}
else
{
// Player is in air
moveVector.x = lateralMove.x * airspeed / speed;
moveVector.z = lateralMove.z * airspeed / speed;
}
moveVector.y -= gravity * Time.deltaTime;
if (Mathf.Abs(moveVector.x) + Mathf.Abs(moveVector.z) > 0.1f){
controller.transform.LookAt(new Vector3(controller.transform.position.x + moveVector.x, controller.transform.position.y, controller.transform.position.z + moveVector.z));
}
controller.Move(moveVector * Time.deltaTime);
}
void SwitchControl(int target)
{
if (activeChar != target)
{
if (status[target] == 0)
{
status[target] = 1;
Vector3 summonPosition = chars[0].transform.position + 0.1f * chars[0].transform.forward;
chars[target].transform.position = summonPosition;
chars[target].SetActive(true);
}
playerCamera.focus = chars[target].transform;
activeChar = target;
controller = chars[target].GetComponent<CharacterController>();
Debug.Log("Active Char: " + activeChar);
}
//charPanel.UpdatePanels();
}
// currently can recall an individual stuffed animal
void Recall(int target)
{
/*
if (activeChar == 0)
{
for (int i = 1; i < status.Length; i++ )
{
if (status[i] == 1)
{
chars[i].SetActive(false);
status[i] = 0;
}
}
}
*/
chars[target].SetActive(false);
status[target] = 0;
if (activeChar != 0)
{
SwitchControl(0);
}
//charPanel.UpdatePanels();
}
public void Damage(int target)
{
if (target == 0)
{
health --;
if (health <= 0) {
FindObjectOfType<LevelManager>().LevelLost();
}
}
else
{
status[target] = 0;
chars[activeChar].SetActive(false);
SwitchControl(0);
}
//charPanel.UpdatePanels();
}
bool CheckGrounded()
{//Judge whether current character is on the ground or not
if (activeChar == 0)
{
Ray ray = new Ray(chars[activeChar].transform.position + Vector3.up * 0.05f, Vector3.down * 0.1f);//Shoot ray at 0.05f upper from Junkochan's feet position to the ground with its length of 0.1f
return Physics.Raycast(ray, 0.05f);//If the ray hit the ground, return true
} else
{
return controller.isGrounded;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityTemplateProjects;
public class CharacterController : MonoBehaviour
{
private Animator ani;
[SerializeField] private float moveSpeed;
[SerializeField] private float turnSpeed;
[SerializeField] private TrailRenderer footTrail;
[SerializeField] private TrailRenderer swordTrail;
[SerializeField] private Material glowMaterial;
[SerializeField] private Material trailMaterial;
[SerializeField] private GameObject sword;
[SerializeField] private GameObject bow;
[SerializeField] private ParticleSystem switchEffect;
[SerializeField] private GameObject arrowPrefab;
[SerializeField] private Color fireColor;
[SerializeField] private Color waterColor;
[SerializeField] private Color lightColor;
private Coroutine turnRoutine;
private Vector3 orientation;
private bool inAction = false;
private bool usingRootMotion = false;
private PlayerElementalState playerElementalState = PlayerElementalState.FIRE;
// Start is called before the first frame update
void Start()
{
ani = GetComponent<Animator>();
orientation = transform.forward;
}
// Update is called once per frame
void Update()
{
Vector3 dirInput = GetDirectionInput();
if (!inAction && dirInput.magnitude > 0)
{
ani.SetBool("run", true);
if (!usingRootMotion) transform.position += dirInput * (moveSpeed * Time.deltaTime);
if (dirInput != orientation)
{
orientation = dirInput;
turnRoutine = StartCoroutine(turnTowards(orientation));
}
}
else
{
ani.SetBool("run", false);
}
if (Input.GetMouseButtonDown(0))
{
if (!inAction)
{
switch (playerElementalState)
{
case PlayerElementalState.FIRE:
StartCoroutine(SwordAttack());
break;
case PlayerElementalState.WATER:
StartCoroutine(SwordAttack());
break;
case PlayerElementalState.LIGHT:
StartCoroutine(BowAttack());
break;
}
}
}
if (Input.GetMouseButtonDown(1))
{
if (!inAction) StartCoroutine(Hook());
}
if (Input.GetKeyDown("space"))
{
if (!inAction) StartCoroutine(Roll());
}
if (Input.GetKeyDown("q"))
{
RotateElementalState(true);
}
if (Input.GetKeyDown("e"))
{
RotateElementalState(false);
}
if (Physics.Raycast(transform.position + (Vector3.up * 0.5f), dirInput, 1))
{
if (!inAction && dirInput.magnitude > 0)
{
StartCoroutine(CollideWithWall(dirInput));
}
};
}
public void EnableTrail()
{
swordTrail.emitting = true;
}
public void DisableTrail()
{
swordTrail.emitting = false;
}
public void EnableFootTrail()
{
footTrail.emitting = true;
}
public void DisableFootTrail()
{
footTrail.emitting = false;
}
public void SpawnBowSwitchProjectiles()
{
var arrow1 = Instantiate(arrowPrefab);
arrow1.transform.forward = (transform.forward + Vector3.down).normalized;
arrow1.transform.position = transform.position + Vector3.up * 1.7f + transform.forward * 0.4f;
var arrow2 = Instantiate(arrow1);
arrow2.transform.forward = Quaternion.AngleAxis(30, Vector3.up) * arrow1.transform.forward;
var arrow3 = Instantiate(arrow1);
arrow3.transform.forward = Quaternion.AngleAxis(-30, Vector3.up) * arrow1.transform.forward;
var arrow4 = Instantiate(arrow1);
arrow4.transform.forward = Quaternion.AngleAxis(60, Vector3.up) * arrow1.transform.forward;
var arrow5 = Instantiate(arrow1);
arrow5.transform.forward = Quaternion.AngleAxis(-60, Vector3.up) * arrow1.transform.forward;
}
private void TurnToMousePos()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
transform.forward = (new Vector3(hit.point.x, 0, hit.point.z) - transform.position).normalized;
}
orientation = transform.forward;
}
private Vector3 GetDirectionInput()
{
return Quaternion.Euler(0, 45, 0) *
new Vector3(-Input.GetAxisRaw("Vertical"), 0, Input.GetAxisRaw("Horizontal"))
.normalized;
}
private IEnumerator turnTowards(Vector3 targetOrientation)
{
if (turnRoutine != null)
{
StopCoroutine(turnRoutine);
}
Vector3 cross = Vector3.Cross(transform.forward, targetOrientation);
int dir = (cross.y < 0) ? -1 : 1;
while (Mathf.Abs(Vector3.Angle(transform.forward, targetOrientation)) > turnSpeed * Time.deltaTime * 100)
{
transform.forward = Quaternion.Euler(0, dir * turnSpeed * Time.deltaTime * 100, 0) * transform.forward;
yield return null;
}
transform.forward = targetOrientation;
yield return null;
}
private IEnumerator SwordAttack()
{
TurnToMousePos();
inAction = true;
usingRootMotion = true;
ani.SetTrigger("attack");
//ani.Play("attack");
yield return new WaitForSeconds(0.64f);
inAction = false;
usingRootMotion = false;
}
private IEnumerator Hook()
{
TurnToMousePos();
inAction = true;
ani.SetTrigger("hook");
yield return new WaitForSeconds(0.8f);
inAction = false;
}
private IEnumerator BowAttack()
{
TurnToMousePos();
inAction = true;
usingRootMotion = true;
ani.SetTrigger("bow_shoot");
bow.GetComponent<Animator>().SetTrigger("pull");
yield return new WaitForSeconds(0.2f);
var arrow = Instantiate(arrowPrefab);
arrow.transform.forward = transform.forward;
arrow.transform.position = transform.position + Vector3.up * 1.7f + transform.forward * 0.2f;
yield return new WaitForSeconds(0.44f);
inAction = false;
usingRootMotion = false;
}
private IEnumerator Roll()
{
inAction = true;
usingRootMotion = true;
ani.SetTrigger("roll");
yield return new WaitForSeconds(0.55f);
inAction = false;
yield return new WaitForSeconds(0.15f);
usingRootMotion = false;
}
private void RotateElementalState(bool left)
{
switch (playerElementalState)
{
case PlayerElementalState.FIRE:
if (left) StartCoroutine(SwitchToLight());
else StartCoroutine(SwitchToWater());
break;
case PlayerElementalState.WATER:
if (left) StartCoroutine(SwitchToFire());
else StartCoroutine(SwitchToLight());
break;
case PlayerElementalState.LIGHT:
if (left) StartCoroutine(SwitchToWater());
else StartCoroutine(SwitchToFire());
break;
}
}
private IEnumerator SwitchToFire()
{
playerElementalState = PlayerElementalState.FIRE;
glowMaterial.SetColor("Color_ec00cd6084ac4d0b9d49bfeaac867853", fireColor);
trailMaterial.color = fireColor;
sword.SetActive(true);
bow.SetActive(false);
Debug.Log("Switch to fire");
switchEffect.startColor = fireColor;
var switchEffectEmission = switchEffect.emission;
switchEffectEmission.enabled = true;
yield return new WaitForSeconds(0.3f);
switchEffectEmission.enabled = false;
yield return null;
}
private IEnumerator SwitchToWater()
{
playerElementalState = PlayerElementalState.WATER;
glowMaterial.SetColor("Color_ec00cd6084ac4d0b9d49bfeaac867853", waterColor);
trailMaterial.color = waterColor;
Debug.Log("Switch to water");
sword.SetActive(true);
bow.SetActive(false);
switchEffect.startColor = waterColor;
var switchEffectEmission = switchEffect.emission;
switchEffectEmission.enabled = true;
yield return new WaitForSeconds(0.3f);
switchEffectEmission.enabled = false;
yield return null;
}
private IEnumerator SwitchToLight()
{
playerElementalState = PlayerElementalState.LIGHT;
glowMaterial.SetColor("Color_ec00cd6084ac4d0b9d49bfeaac867853", lightColor);
trailMaterial.color = lightColor;
Debug.Log("Switch to ligth");
bow.SetActive(true);
sword.SetActive(false);
switchEffect.startColor = lightColor;
var switchEffectEmission = switchEffect.emission;
switchEffectEmission.enabled = true;
inAction = true;
usingRootMotion = true;
ani.SetTrigger("switch_bow");
yield return new WaitForSeconds(0.3f);
switchEffectEmission.enabled = false;
yield return new WaitForSeconds(0.5f);
inAction = false;
usingRootMotion = false;
}
private IEnumerator CollideWithWall(Vector3 direction)
{
inAction = true;
ani.SetBool("collision_front", true);
yield return new WaitForSeconds(0.2f);
usingRootMotion = true;
yield return new WaitUntil(() => GetDirectionInput() != direction);
inAction = false;
usingRootMotion = false;
ani.SetBool("collision_front", false);
}
private void OnDestroy()
{
glowMaterial.SetColor("Color_ec00cd6084ac4d0b9d49bfeaac867853", fireColor);
trailMaterial.color = fireColor;
}
} |
using System;
namespace Fuzzing.Fuzzers.Impl
{
public class FloatFuzzer : TypeFuzzer<float>
{
private const int FloatSize = sizeof (float);
public override float Fuzz()
{
var data = new byte[FloatSize];
RandomNumberGenerator.GetBytes(data);
var result = BitConverter.ToSingle(data, 0);
return result;
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chargeIO.Models
{
public interface IPaymentMethodInformation
{
[JsonProperty("email")]
string Email { get; set; }
[JsonProperty("name")]
string Name { get; set; }
[JsonProperty("address1")]
string Address1 { get; set; }
[JsonProperty("city")]
string City { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Refactoring.UntanglingStructureFromOperations
{
class Painters
{
private IEnumerable<IPainter> ContainedPainters { get; }
public Painters(IEnumerable<IPainter> painters)
{
this.ContainedPainters = painters.ToList();
}
public Painters GetAvailable() =>
//creating another instance of Painters, we keep the sequence safer
new Painters(this.ContainedPainters.Where(painter => painter.IsAvailable));
public Painters GetAvailableUsingLessMemory()
{
//Regarding the length of sequence, It could make sense, even if the execution time increase a little.
if (ContainedPainters.All(painter => painter.IsAvailable))
return this;
//creating another instance of Painters, we keep the sequence safer
return new Painters(this.ContainedPainters.Where(painter => painter.IsAvailable));
}
//Group what client wants to know/do with IPainter.
//In this case, the client wants to get the cheapest painter and/or the fastest painter.
public IPainter GetCheapestOne(double sqMeters) =>
this.ContainedPainters.WithMinimum(painter => painter.EstimateCompensation(sqMeters));
public IPainter GetFastestOne(double sqMeters) =>
this.ContainedPainters.WithMinimum(painter => painter.EstimateTimeToPaint(sqMeters));
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DontDestroy : MonoBehaviour
{
public static DontDestroy dd;
private int vidas = 3;
[SerializeField]
private Text textoVidas;
private void Awake()
{
if (dd == null)
{
dd = this;
}
else if (dd != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
private void Start()
{
TextVidas();
}
private void Update()
{
TextVidas();
}
public int PerdidaVida()
{
vidas--;
return vidas;
}
public int Vidas()
{
return vidas;
}
public string TextVidas()
{
textoVidas.text = "Vidas: " + vidas.ToString();
return textoVidas.text;
}
}
|
using System;
using System.Collections.Generic;
using Fbtc.Domain.Entities;
using Fbtc.Domain.Interfaces.Services;
using Fbtc.Application.Interfaces;
using prmToolkit.Validation;
using Fbtc.Application.Helper;
namespace Fbtc.Application.Services
{
public class EventoApplication : IEventoApplication
{
private readonly IEventoService _eventoService;
public EventoApplication(IEventoService eventoService)
{
_eventoService = eventoService;
}
public string DeleteById(int id)
{
throw new NotImplementedException();
}
public IEnumerable<Evento> FindByFilters(string titulo, int ano, string tipoEvento)
{
string _titulo, _tipoEvento;
_titulo = titulo == "0" ? "" : titulo;
_tipoEvento = tipoEvento == "0" ? "" : tipoEvento;
return _eventoService.FindByFilters(_titulo, ano, _tipoEvento);
}
public IEnumerable<EventoDao> FindEventoDaoByFilters(string titulo, int ano, string tipoEvento)
{
string _titulo, _tipoEvento;
_titulo = titulo == "0" ? "" : titulo;
_tipoEvento = tipoEvento == "0" ? "" : tipoEvento;
return _eventoService.FindEventoDaoByFilters(_titulo, ano, _tipoEvento);
}
public IEnumerable<Evento> GetAll()
{
return _eventoService.GetAll();
}
public Evento GetEventoById(int id)
{
return _eventoService.GetEventoById(id);
}
public Evento GetEventoByRecebimentoId(int id)
{
return _eventoService.GetEventoByRecebimentoId(id);
}
public EventoDao GetEventoDaoById(int id)
{
return _eventoService.GetEventoDaoById(id);
}
public string GetNomeFotoByEventoId(int id)
{
return _eventoService.GetNomeFotoByEventoId(id);
}
public string Save(Evento e)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNullOrEmpty(e.Titulo, "Título não informado"),
RaiseException.IfNullOrEmpty(e.Descricao, "Descrição não informada"),
RaiseException.IfTrue(DateTime.Equals(e.DtInicio, DateTime.MinValue), "Data de Início não informada"),
RaiseException.IfTrue(DateTime.Equals(e.DtTermino, DateTime.MinValue), "Data de Término não informada"),
RaiseException.IfNullOrEmpty(e.TipoEvento, "Tipo de Evento não informado")
);
Evento _e = new Evento()
{
EventoId = e.EventoId,
Titulo = Functions.AjustaTamanhoString(e.Titulo, 100),
Descricao = Functions.AjustaTamanhoString(e.Descricao, 2000),
Codigo = Functions.AjustaTamanhoString(e.Codigo, 60),
DtInicio = e.DtInicio,
DtTermino = e.DtTermino,
DtTerminoInscricao = e.DtTerminoInscricao,
TipoEvento = e.TipoEvento,
AceitaIsencaoAta = e.AceitaIsencaoAta,
NomeFoto = e.NomeFoto,
Ativo = e.Ativo
};
try
{
if (_e.EventoId == 0)
{
return _eventoService.Insert(_e);
}
else
{
return _eventoService.Update(e.EventoId, _e);
}
}
catch (Exception ex)
{
throw ex;
}
}
public string SaveEventoDao(EventoDao e)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNullOrEmpty(e.Titulo, "Título não informado"),
RaiseException.IfNullOrEmpty(e.Descricao, "Descrição não informada"),
RaiseException.IfTrue(DateTime.Equals(e.DtInicio, DateTime.MinValue), "Data de Início não informada"),
RaiseException.IfTrue(DateTime.Equals(e.DtTermino, DateTime.MinValue), "Data de Término não informada"),
RaiseException.IfNullOrEmpty(e.TipoEvento, "Tipo de Evento não informado")
);
EventoDao _e = new EventoDao()
{
EventoId = e.EventoId,
Titulo = Functions.AjustaTamanhoString(e.Titulo, 100),
Descricao = Functions.AjustaTamanhoString(e.Descricao, 2000),
Codigo = Functions.AjustaTamanhoString(e.Codigo, 60),
DtInicio = e.DtInicio,
DtTermino = e.DtTermino,
DtTerminoInscricao = e.DtTerminoInscricao,
TipoEvento = e.TipoEvento,
AceitaIsencaoAta = e.AceitaIsencaoAta,
NomeFoto = e.NomeFoto,
Ativo = e.Ativo,
TiposPublicosValoresDao = e.TiposPublicosValoresDao
};
try
{
if (_e.EventoId == 0)
{
return _eventoService.InsertEventoDao(_e);
}
else
{
return _eventoService.UpdateEventoDao(e.EventoId, _e);
}
}
catch (Exception ex)
{
throw ex;
}
}
public string SaveValoresEvento(IEnumerable<TipoPublicoValorDao> tiposPublicosValoresDao)
{
throw new NotImplementedException();
}
public Evento SetEvento()
{
Evento e = new Evento() {
EventoId = 0,
Titulo = "",
Descricao = "",
Codigo = "",
DtInicio = null,
DtTermino = null,
DtTerminoInscricao = null,
TipoEvento = "",
AceitaIsencaoAta = false,
Ativo = true,
NomeFoto = ""
};
return e;
}
}
}
|
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 System.Configuration;
namespace PayRoll
{
public partial class WorkSheet : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["luname"] != null && Session["lpass"] != null)
{
Data();
}
else
{
Response.Redirect("Login.aspx");
}
}
}
void Data()
{
SqlDataAdapter da = new SqlDataAdapter("select a.Name,b.* from Employee as a inner join WorkSheet as b on a.EmpId=b.EmpId", con);
DataSet ds = new DataSet();
da.Fill(ds);
gdvemp.DataSource = ds;
gdvemp.DataBind();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FormUserManager : MonoBehaviour
{
[SerializeField]
GameObject SignInMenu;
[SerializeField]
GameObject SignUpMenu;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void SignUp()
{
SignInMenu.SetActive(false);
SignUpMenu.SetActive(true);
}
public void SignIn()
{
SignInMenu.SetActive(true);
SignUpMenu.SetActive(false);
}
}
|
using ControleFinanceiro.Domain.Contracts.Repositories;
using ControleFinanceiro.Domain.Contracts.Services;
using ControleFinanceiro.Domain.Entities;
using ControleFinanceiro.Infra.Data.EF;
using System;
using System.Collections.Generic;
namespace ControleFinanceiro.Domain.Service.Services
{
public class ServicoDespesa : ServicoBase<Despesa>, IServicoDespesa
{
private readonly IRepositorioDespesa _repositorioDespesa;
public ServicoDespesa(IRepositorioDespesa repositorioDespesa, EFContext context) : base(repositorioDespesa, context)
{
_repositorioDespesa = repositorioDespesa;
}
public List<Despesa> ListarDespesaPorData(DateTime data, int idUsuario)
{
return _repositorioDespesa.ListarDespesaPorData(data, idUsuario);
}
}
}
|
/// summary>
/// CodeArtist.mx 2018
/// To get the selector color, call in any method: ColorSelector.GetColor();
/// </summary>
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.Events;
public class ColorSelector : MonoBehaviour , IDragHandler, IPointerDownHandler, IPointerUpHandler
{
[SerializeField]
private RawImage selectorImage;
[SerializeField]
private Image outerCursor;
[SerializeField]
private Image innerCursor;
[SerializeField]
private Image finalColorImage;
private RectTransform rectTransform;
private Vector2 innerDelta;
private Color finalColor;
private Color selectedColor;
private float selectorAngle;
private enum SelectorState { OuterColor,InnerColor,None}
private SelectorState selectorState;
private void Start ()
{
selectedColor = Color.red;
selectorAngle = 0.0f;
innerDelta = Vector2.zero;
finalColorImage.color=finalColor;
rectTransform = transform as RectTransform;
selectorState = SelectorState.None;
SelectInnerColor(Vector2.zero);
}
public void OnDrag(PointerEventData eventData)
{
UpdateSelector(eventData);
}
public void OnPointerDown(PointerEventData eventData)
{
UpdateSelector(eventData);
}
public void OnPointerUp(PointerEventData eventData)
{
selectorState = SelectorState.None;
}
private void UpdateSelector(PointerEventData eventData)
{
Vector2 localPosition = Vector2.zero;
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out localPosition);
localPosition *= 1.0f / (rectTransform.sizeDelta.x * 0.5f);
if (selectorState == SelectorState.None)
{
float dist = Vector2.Distance(Vector2.zero, localPosition) ;
if (dist <= 0.8f)
{
selectorState = SelectorState.InnerColor;
}
else
{
selectorState = SelectorState.OuterColor;
}
}
switch (selectorState)
{
case SelectorState.InnerColor:
SelectInnerColor(localPosition);
break;
case SelectorState.OuterColor:
SelectOuterColor(localPosition);
break;
}
}
private void SelectInnerColor(Vector2 delta)
{
float v=0.0f, w=0.0f, u=0.0f;
Barycentric (delta,ref v,ref w,ref u);
/*v = Mathf.Clamp(v, 0.15f,v);
w = Mathf.Clamp(w, -0.15f,w);
u = Mathf.Clamp(u, -0.15f,u);*/
if (v >= 0.15f && w >= -0.15f && u >= -0.15f)
{
Debug.Log(delta.magnitude);
Vector3 colorVector = new Vector3 (selectedColor.r, selectedColor.g, selectedColor.b);
Vector3 finalColorVector = v * colorVector + u * new Vector3 (0.0f, 0.0f, 0.0f) + w * new Vector3 (1.0f, 1.0f, 1.0f);
finalColor = new Color (finalColorVector.x, finalColorVector.y, finalColorVector.z);
finalColorImage.color=finalColor;
innerDelta=delta;
Vector2 a = new Vector2(0.0f, 0.5f);
Vector2 b = new Vector2(-0.58f, -0.58f);
Vector2 c = new Vector2(0.58f, -0.58f);
innerCursor.transform.localPosition = delta * rectTransform.sizeDelta.x*0.5f;//ClosesPointOnTriangle(a, b, c, delta) * rectTransform.sizeDelta.x * 0.5f; //
innerDelta = delta;
}
}
private Vector3 ClampPosToCircle(Vector3 pos)
{
Vector3 newPos = Vector3.zero;
float dist = 0.9f;
float angle = Mathf.Atan2(pos.x, pos.y);// * 180 / Mathf.PI;
newPos.x = dist * Mathf.Sin( angle ) ;
newPos.y = dist * Mathf.Cos( angle ) ;
newPos.z = pos.z;
return newPos;
}
void Barycentric(Vector2 point,ref float u,ref float v,ref float w)
{
Vector2 a = new Vector2 (0.0f, 0.5f);
Vector2 b = new Vector2 (-0.58f, -0.58f);
Vector2 c = new Vector2 (0.58f, -0.58f);
Vector2 v0 = b - a, v1 = c - a, v2 = point - a;
float d00 = Vector2.Dot(v0, v0);
float d01 = Vector2.Dot(v0, v1);
float d11 = Vector2.Dot(v1, v1);
float d20 = Vector2.Dot(v2, v0);
float d21 = Vector2.Dot(v2, v1);
float denom = d00 * d11 - d01 * d01;
v = (d11 * d20 - d01 * d21) / denom;
w = (d00 * d21 - d01 * d20) / denom;
u = 1.0f - v - w;
}
private void SelectOuterColor(Vector2 delta)
{
float angle= Mathf.Atan2(delta.x, delta.y);
float angleGrad = angle * Mathf.Rad2Deg;
if (angleGrad < 0.0f)
{
angleGrad=360+angleGrad;
}
selectorAngle =angleGrad/360;
selectedColor=HSVToRGB(selectorAngle,1.0f,1.0f);
selectorImage.GetComponent<CanvasRenderer>().GetMaterial().SetColor("_Color",selectedColor);
outerCursor.transform.localPosition = ClampPosToCircle (delta)*(rectTransform.sizeDelta.x*0.5f);
SelectInnerColor (innerDelta);
}
public static Color HSVToRGB(float H, float S, float V)
{
if (S == 0f)
return new Color(V,V,V);
else if (V == 0f)
return Color.black;
else
{
Color col = Color.black;
float Hval = H * 6f;
int sel = Mathf.FloorToInt(Hval);
float mod = Hval - sel;
float v1 = V * (1f - S);
float v2 = V * (1f - S * mod);
float v3 = V * (1f - S * (1f - mod));
switch (sel + 1)
{
case 0:
col.r = V;
col.g = v1;
col.b = v2;
break;
case 1:
col.r = V;
col.g = v3;
col.b = v1;
break;
case 2:
col.r = v2;
col.g = V;
col.b = v1;
break;
case 3:
col.r = v1;
col.g = V;
col.b = v3;
break;
case 4:
col.r = v1;
col.g = v2;
col.b = V;
break;
case 5:
col.r = v3;
col.g = v1;
col.b = V;
break;
case 6:
col.r = V;
col.g = v1;
col.b = v2;
break;
case 7:
col.r = V;
col.g = v3;
col.b = v1;
break;
}
col.r = Mathf.Clamp(col.r, 0f, 1f);
col.g = Mathf.Clamp(col.g, 0f, 1f);
col.b = Mathf.Clamp(col.b, 0f, 1f);
return col;
}
}
private Vector3 ClosesPointOnTriangle( Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p)
{
Vector3 result= p;
result = Vector3.Project(p0 - p1, (Vector3.zero - p0).normalized);
/* p = NearestPointOnLine(p0, (p0 - p1), p);
p = NearestPointOnLine(p1, (p1 - p2), p);
p = NearestPointOnLine(p2, (p2 - p0), p);*/
return result;
}
public static Vector3 NearestPointOnLine(Vector3 linePnt, Vector3 lineDir, Vector3 pnt)
{
lineDir.Normalize();//this needs to be a unit vector
var v = pnt - linePnt;
var d = Vector3.Dot(v, lineDir);
return linePnt + lineDir * d;
}
/// <summary>
/// Returns the selected color.
/// </summary>
/// <returns>The Selected Color</returns>
public Color GetColor()
{
return finalColor;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Globalization.DateTimeFormatting;
namespace Season
{
public static class SeasonExtensions
{
// original code by riofly see http://stackoverflow.com/a/12243809/1248177
// equinox entry on wiki https://en.wikipedia.org/wiki/Equinox
public static Season GetSeason(this DateTime date, bool ofSouthernHemisphere)
{
var hemisphereConst = ofSouthernHemisphere ? 2 : 0;
Func<int, Season> handleHemisphere = northern =>
(Season) ((northern + hemisphereConst) % 4);
Func<Season, DateTime> getDay = season =>
(DateTime) new JulianDay(Equinox.Approximate(date.Year, season));
var winterSolstice = getDay(Season.Winter);
var springEquinox = getDay(Season.Spring);
var summerSolstice = getDay(Season.Summer);
var autumnEquinox = getDay(Season.Autumn);
if (date < springEquinox || date >= winterSolstice) return handleHemisphere(3);
if (date < summerSolstice) return handleHemisphere(0);
if (date < autumnEquinox) return handleHemisphere(1);
return handleHemisphere(2);
}
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace ProyectoSCA_Navigation.Clases.Clases_Para_los_Grids
{
public class estadoDeCuentaGrid
{
public float Monto { get; set; }
public String Descripcion { get; set; }
public String fechaPlazo { get; set; }
public String fechaRealizacion { get; set; }
public String Motivo { get; set; }
}
}
|
using System;
using System.Collections.Concurrent;
namespace SpeedSlidingTrainer.Application.Infrastructure
{
public sealed class MessageBus : IMessageBus
{
private readonly ConcurrentDictionary<Type, Action<object>[]> handlersByType = new ConcurrentDictionary<Type, Action<object>[]>();
public void Subscribe<TEvent>(Action<TEvent> handler)
{
Action<object> objectHandler = eventObject => handler((TEvent)eventObject);
this.handlersByType.AddOrUpdate(typeof(TEvent), eventType => new[] { objectHandler }, (eventType, current) => AppendToArray(current, objectHandler));
}
public void Publish<TEvent>(TEvent message)
{
Action<object>[] handlers;
if (this.handlersByType.TryGetValue(typeof(TEvent), out handlers))
{
foreach (Action<object> handler in handlers)
{
handler(message);
}
}
}
private static T[] AppendToArray<T>(T[] array, T newItem)
{
T[] newArray = new T[array.Length + 1];
Array.Copy(array, newArray, array.Length);
newArray[array.Length] = newItem;
return newArray;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace GymWorkout.Application.Interfaces
{
public interface IBaseEntity
{
int Id { get; set; }
DateTime CreateDate { get; set; }
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace todo_app.Controllers
{
public class ToDoContext : DbContext
{
string TODO_CONNECTION_STRING = "";
public ToDoContext(IOptions<Parameters> options)
{
Console.WriteLine("DB Connection String ToDoContext - " + options.Value.AuroraConnectionString);
TODO_CONNECTION_STRING = options.Value.AuroraConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL(TODO_CONNECTION_STRING);
base.OnConfiguring(optionsBuilder);
}
public DbSet<ToDo> ToDos { get; set; }
}
} |
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
public partial class _Default : System.Web.UI.Page
{
private DataClassesDataContext db = new DataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
Repeater_Frontpage.DataSource = db.dbNews.OrderByDescending(n => n.PostDate).Take(5).ToList();
Repeater_Frontpage.DataBind();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deactivate : MonoBehaviour {
Transform _player;
public float deactivationDistance;
void Start () {
_player = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update () {
if(Vector3.Distance(_player.position, transform.position) > deactivationDistance)
{
gameObject.SetActive(false);
}
else
{
gameObject.SetActive(true);
}
}
}
|
namespace Assets.Scripts.Models.Clothes
{
public class Boots : Clothes
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace InventorySolution
{
public partial class WelcomeScr : Form
{
public WelcomeScr()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Record rcform = new Record();
rcform.MdiParent = this;
rcform.Show();
rcform.StartPosition = FormStartPosition.CenterParent;
btnNext.Enabled = false;
}
private void WelcomeScr_Layout(object sender, LayoutEventArgs e)
{
}
}
}
|
using Dapper;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
namespace Kaax.Sample
{
static class DbConnectionProviderDapperExtensions
{
public static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnectionProvider dbConnectionProvider, string commandText, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null, CancellationToken cancellationToken = default)
{
using var connection = dbConnectionProvider.OpenConnection();
var result = await connection.QueryAsync<T>(new CommandDefinition(commandText, param, transaction, commandTimeout, commandType, cancellationToken: cancellationToken)).ConfigureAwait(false);
return result;
}
}
}
|
using MikeGrayCodes.BuildingBlocks.Domain;
namespace MikeGrayCodes.Ordering.Domain.Entities.Orders.Rules
{
public class UnitsOrderedMustBeGreaterThanZeroRule : IBusinessRule
{
private readonly int units;
public UnitsOrderedMustBeGreaterThanZeroRule(int units)
{
this.units = units;
}
public bool IsBroken()
{
return units <= 0;
}
public string Message => "Number of units must be greater than 0";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ProxyPattern
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
//MathProxy proxy = new MathProxy();
Math proxy = new Math();
Console.WriteLine(proxy.Add(5,6));
Console.WriteLine(proxy.Sub(11,3));
Console.WriteLine(proxy.Mul(8,9));
Console.WriteLine(proxy.Div(44369, 16016));
sw.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed);
Console.ReadKey();
}
}
public interface IMath
{
double Add(double x, double y);
double Sub(double x, double y);
double Div(double x, double y);
double Mul(double x, double y);
}
class Math : IMath
{
public double Add(double x, double y)
{
return x + y;
}
public double Div(double x, double y)
{
return x / y;
}
public double Mul(double x, double y)
{
return x * y;
}
public double Sub(double x, double y)
{
return x - y;
}
}
class MathProxy : IMath
{
private Math _math = new Math();
public double Add(double x, double y)
{
return _math.Add(x,y);
}
public double Div(double x, double y)
{
return _math.Div(x, y);
}
public double Mul(double x, double y)
{
return _math.Mul(x, y);
}
public double Sub(double x, double y)
{
return _math.Sub(x, y);
}
}
}
|
//#define debug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AxisPosCore;
using KartObjects;
using System.IO;
using System.Xml.Serialization;
using System.Diagnostics;
using AxisPosCore;
using System.Timers;
using KartObjects.Entities;
namespace AxisPosUtil
{
/// <summary>
/// Основная логика работы AxisPos (DKposHelper)
/// </summary>
public class AxisPosPresenter
{
private static AbstractDataConnection _dataContext;
Timer CheckTimeTimer;
/// <summary>
/// Соединение с серверной базой данных
/// </summary>
public AbstractDataConnection ServerDataContext
{
get;
set;
}
/// <summary>
/// Директория, в которой находится сборка
/// </summary>
public static string AppDirectory
{
get
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
private static Log _logger;
/// <summary>
/// Логгер
/// </summary>
public static Log Logger
{
get
{
if (_logger == null)
{
// Проверим папку с логами
string fullLogsFolder = Path.Combine(AppDirectory, LogsFolder);
if (!Directory.Exists(fullLogsFolder))
{
Directory.CreateDirectory(fullLogsFolder);
}
_logger = new Log(Path.Combine(fullLogsFolder, GetFileLogName()));
}
return _logger;
}
}
/// <summary>
/// Название папки, в которой хранятся логи
/// </summary>
public const string LogsFolder = "";
private static string GetFileLogName()
{
return "AxisPos.log";
}
/// <summary>
/// Признак того, можно ли сохранять настройки
/// </summary>
private bool _allowSaveOptions;
/// <summary>
/// Интерфейс формы, через которых презентер будет с ней общаться
/// </summary>
private IDateView _view;
public string OptionsPath
{
get
{
return Path.Combine(Settings.GetExecPath(), "Settings");
}
}
/// <summary>
/// Конструктор презентера
/// </summary>
public AxisPosPresenter(IDateView view)
: base()
{
_view = view;
CloseReciepts = true;
ExecDemandJob = false;
}
DataDictionary dictionary;
DictionaryLoader dictionaryLoader;
List<DemandWhSetting> DemandWhSettings;
public void ViewLoad()
{
LoadDemandWhSettings();
CheckTimeTimer = new Timer();
//полсекунды
CheckTimeTimer.Interval = 1000;
CheckTimeTimer.Elapsed += new ElapsedEventHandler(CheckTimeTimer_Elapsed);
CheckTimeTimer.Start();
#if !debug
try
{
#endif
if (!Settings.LoadSettings("config.xml", "dkpos.cfg"))
{
const string error = "Не удалось загрузить настройки из файла конфигурации.";
Logger.WriteToLog(error);
throw new ConfigLoadException(error);
}
//Загрузчик , firebird
string ServerConnectionString = string.Format("DataSource={0}; database={1}; user={2}; password={3};" + "Port=3050;Dialect=1; Charset=win1251;ServerType=0;", Settings.ServerHost, Settings.ServerDBase, Settings.ServerUser, Settings.ServerPassword);
Loader.DataContext = new FbDataConnection(ServerConnectionString);
//Saver mssql
if (Settings.DBase != "")
{
string connectionString = string.Format("server={0}; database={1}; user={2}; password={3}", Settings.Server, Settings.DBase, Settings.User, Settings.Password);
Saver.DataContext = new SqlDataConnection(connectionString);
}
//Загрузка всех справочников
Logger.WriteToLog("Инициализация справочников ");
bool fileLoadResult = false;
if (File.Exists(DataDictionary.DatFileName))
{
Stopwatch sw = new Stopwatch();
sw.Start();
try
{
dictionary = DataDictionary.LoadData();
sw.Stop();
fileLoadResult = true;
Logger.WriteToLog("Загрузка из локального кэша " + KartObjects.Helper.formatSwString(sw));
}
catch (Exception e)
{
fileLoadResult = false;
Logger.WriteToLog("Ошибка загрузки из кэша " + e.Message);
}
}
dictionaryLoader = new DictionaryLoaderDCTSaver();
if (!fileLoadResult)
if (Loader.IsOnline)
{
Stopwatch sw = new Stopwatch();
sw.Start();
dictionary = new DataDictionary();
///
if (dictionaryLoader.loadGoods)
{
Loader.DataContext.BeginTransaction();
DataDictionary.SActualDate = (DateTime)Loader.DataContext.ExecuteScalar("select cast('now' as date) from rdb$database");
Logger.WriteToLog("Загрузка товаров... ");
DataDictionary.SGoods = Loader.DbLoad<Good>(" 1=1 order by name");
Logger.WriteToLog("Загрузка штрих-кодов... ");
DataDictionary.SBarcodes = Loader.DbLoad<Barcode>("");
Logger.WriteToLog("Загрузка ассортимента... ");
DataDictionary.SAssortments = Loader.DbLoad<Assortment>("");
Logger.WriteToLog("Загрузка атрибутов... ");
DataDictionary.SGoodAttributes = Loader.DbLoad<GoodAttribute>("");
Loader.DataContext.CommitTransaction();
sw.Stop();
Logger.WriteToLog("Загрузка из БД " + KartObjects.Helper.formatSwString(sw));
}
}
Logger.WriteToLog(string.Format("Запуск загрузчика {0} ...", Settings.ServerDBase));
dictionaryLoader.onNeedWriteLog += new NeedWriteLogDeletage(dictionaryLoader_onNeedWriteLog);
dictionaryLoader.onNeedUpdateDateReceipts += new NeedSetDateValueDeletage(dictionaryLoader_onNeedUpdateDateReceipts);
dictionaryLoader.Start();
//Начинаем парсить лог с начала дня
LastLogTime = DateTime.Today;
#if !debug
}
catch (Exception e)
{
Logger.WriteToLog("Ошибка загрузки " + e.Message + "\n" +e.StackTrace);
}
#endif
}
void dictionaryLoader_onNeedUpdateDateReceipts(DateTime dt)
{
_view.ReceiptsDate = dt;
}
/// <summary>
/// Загрузка настроек формирования заявки на склад
/// </summary>
private void LoadDemandWhSettings()
{
if (File.Exists("DemandWhSettings.xml"))
{
//Десериализуем из файла
StreamReader reader = new StreamReader("DemandWhSettings.xml");
XmlSerializer serializer = new XmlSerializer(typeof(List<DemandWhSetting>));
DemandWhSettings = (List<DemandWhSetting>)serializer.Deserialize(reader);
}
else
{
DemandWhSettings = new List<DemandWhSetting>();
//тагил
DemandWhSetting s = new DemandWhSetting() { IdWarehouse = 6999, NameWarehouse = "Тагил" };
s.Conditions = new List<ComplexWdCondition>();
ComplexWdCondition c = new ComplexWdCondition();
c.wdWorkDays = new List<DayOfWeek>();
c.wdStartDemand = DayOfWeek.Monday;
c.wdWorkDays.Add(DayOfWeek.Thursday);
c.wdWorkDays.Add(DayOfWeek.Friday);
c.wdWorkDays.Add(DayOfWeek.Saturday);
c.wdWorkDays.Add(DayOfWeek.Sunday);
s.Conditions.Add(c);
ComplexWdCondition c1 = new ComplexWdCondition();
c1.wdWorkDays = new List<DayOfWeek>();
c1.wdStartDemand = DayOfWeek.Thursday;
c1.wdWorkDays.Add(DayOfWeek.Monday);
c1.wdWorkDays.Add(DayOfWeek.Tuesday);
c1.wdWorkDays.Add(DayOfWeek.Wednesday);
s.Conditions.Add(c1);
DemandWhSettings.Add(s);
//джаз
DemandWhSetting s_jazz = new DemandWhSetting() { IdWarehouse = 6994, NameWarehouse = "Джаз" };
s_jazz.Conditions = new List<ComplexWdCondition>();
ComplexWdCondition s_jazz_c = new ComplexWdCondition();
s_jazz_c.wdWorkDays = new List<DayOfWeek>();
s_jazz_c.wdStartDemand = DayOfWeek.Sunday;
s_jazz_c.wdWorkDays.Add(DayOfWeek.Thursday);
s_jazz_c.wdWorkDays.Add(DayOfWeek.Friday);
s_jazz_c.wdWorkDays.Add(DayOfWeek.Saturday);
s_jazz.Conditions.Add(s_jazz_c);
ComplexWdCondition s_jazz_c1 = new ComplexWdCondition();
s_jazz_c1.wdWorkDays = new List<DayOfWeek>();
s_jazz_c1.wdStartDemand = DayOfWeek.Thursday;
s_jazz_c1.wdWorkDays.Add(DayOfWeek.Sunday);
s_jazz_c1.wdWorkDays.Add(DayOfWeek.Monday);
s_jazz_c1.wdWorkDays.Add(DayOfWeek.Tuesday);
s_jazz_c1.wdWorkDays.Add(DayOfWeek.Wednesday);
s_jazz.Conditions.Add(s_jazz_c1);
DemandWhSettings.Add(s_jazz);
//Апельсин
DemandWhSetting s_Orange = new DemandWhSetting() { IdWarehouse = 6995, NameWarehouse = "Апельсин" };
s_Orange.Conditions = new List<ComplexWdCondition>();
ComplexWdCondition s_Orange_c = new ComplexWdCondition();
s_Orange_c.wdWorkDays = new List<DayOfWeek>();
s_Orange_c.wdStartDemand = DayOfWeek.Sunday;
s_Orange_c.wdWorkDays.Add(DayOfWeek.Thursday);
s_Orange_c.wdWorkDays.Add(DayOfWeek.Friday);
s_Orange_c.wdWorkDays.Add(DayOfWeek.Saturday);
s_Orange.Conditions.Add(s_Orange_c);
ComplexWdCondition s_Orange_c1 = new ComplexWdCondition();
s_Orange_c1.wdWorkDays = new List<DayOfWeek>();
s_Orange_c1.wdStartDemand = DayOfWeek.Thursday;
s_Orange_c1.wdWorkDays.Add(DayOfWeek.Sunday);
s_Orange_c1.wdWorkDays.Add(DayOfWeek.Monday);
s_Orange_c1.wdWorkDays.Add(DayOfWeek.Tuesday);
s_Orange_c1.wdWorkDays.Add(DayOfWeek.Wednesday);
s_Orange.Conditions.Add(s_Orange_c1);
DemandWhSettings.Add(s_Orange);
//Марс
DemandWhSetting s_Mars = new DemandWhSetting() { IdWarehouse = 6998, NameWarehouse = "Марс" };
s_Mars.Conditions = new List<ComplexWdCondition>();
ComplexWdCondition s_Mars_c = new ComplexWdCondition();
s_Mars_c.wdWorkDays = new List<DayOfWeek>();
s_Mars_c.wdStartDemand = DayOfWeek.Sunday;
s_Mars_c.wdWorkDays.Add(DayOfWeek.Wednesday);
s_Mars_c.wdWorkDays.Add(DayOfWeek.Thursday);
s_Mars_c.wdWorkDays.Add(DayOfWeek.Friday);
s_Mars_c.wdWorkDays.Add(DayOfWeek.Saturday);
s_Mars.Conditions.Add(s_Mars_c);
ComplexWdCondition s_Mars_c1 = new ComplexWdCondition();
s_Mars_c1.wdWorkDays = new List<DayOfWeek>();
s_Mars_c1.wdStartDemand = DayOfWeek.Wednesday;
s_Mars_c1.wdWorkDays.Add(DayOfWeek.Sunday);
s_Mars_c1.wdWorkDays.Add(DayOfWeek.Monday);
s_Mars_c1.wdWorkDays.Add(DayOfWeek.Tuesday);
s_Mars.Conditions.Add(s_Mars_c1);
DemandWhSettings.Add(s_Mars);
//Пирамида
DemandWhSetting s_Pyramid = new DemandWhSetting() { IdWarehouse = 6997, NameWarehouse = "Пирамида" };
s_Pyramid.Conditions = new List<ComplexWdCondition>();
ComplexWdCondition s_Pyramid_c = new ComplexWdCondition();
s_Pyramid_c.wdWorkDays = new List<DayOfWeek>();
s_Pyramid_c.wdStartDemand = DayOfWeek.Sunday;
s_Pyramid_c.wdWorkDays.Add(DayOfWeek.Wednesday);
s_Pyramid_c.wdWorkDays.Add(DayOfWeek.Thursday);
s_Pyramid_c.wdWorkDays.Add(DayOfWeek.Friday);
s_Pyramid_c.wdWorkDays.Add(DayOfWeek.Saturday);
s_Pyramid.Conditions.Add(s_Pyramid_c);
ComplexWdCondition s_Pyramid_c1 = new ComplexWdCondition();
s_Pyramid_c1.wdWorkDays = new List<DayOfWeek>();
s_Pyramid_c1.wdStartDemand = DayOfWeek.Wednesday;
s_Pyramid_c1.wdWorkDays.Add(DayOfWeek.Sunday);
s_Pyramid_c1.wdWorkDays.Add(DayOfWeek.Monday);
s_Pyramid_c1.wdWorkDays.Add(DayOfWeek.Tuesday);
s_Pyramid.Conditions.Add(s_Pyramid_c1);
DemandWhSettings.Add(s_Pyramid);
//Ревда
DemandWhSetting s_Revda = new DemandWhSetting() { IdWarehouse = 6996, NameWarehouse = "Ревда" };
s_Revda.Conditions = new List<ComplexWdCondition>();
ComplexWdCondition s_Revda_c = new ComplexWdCondition();
s_Revda_c.wdWorkDays = new List<DayOfWeek>();
s_Revda_c.wdStartDemand = DayOfWeek.Sunday;
s_Revda_c.wdWorkDays.Add(DayOfWeek.Wednesday);
s_Revda_c.wdWorkDays.Add(DayOfWeek.Thursday);
s_Revda_c.wdWorkDays.Add(DayOfWeek.Friday);
s_Revda_c.wdWorkDays.Add(DayOfWeek.Saturday);
s_Revda.Conditions.Add(s_Revda_c);
ComplexWdCondition s_Revda_c1 = new ComplexWdCondition();
s_Revda_c1.wdWorkDays = new List<DayOfWeek>();
s_Revda_c1.wdStartDemand = DayOfWeek.Wednesday;
s_Revda_c1.wdWorkDays.Add(DayOfWeek.Sunday);
s_Revda_c1.wdWorkDays.Add(DayOfWeek.Monday);
s_Revda_c1.wdWorkDays.Add(DayOfWeek.Tuesday);
s_Revda.Conditions.Add(s_Revda_c1);
DemandWhSettings.Add(s_Revda);
TextWriter writer = new StreamWriter("DemandWhSettings.xml");
XmlSerializer serializer = new XmlSerializer(typeof(List<DemandWhSetting>));
serializer.Serialize(writer, DemandWhSettings);
writer.Close();
}
}
/// <summary>
/// Закрыть чеки за текущий период
/// </summary>
bool CloseReciepts
{
get;
set;
}
public bool ExecDemandJob
{
get;
set;
}
/// <summary>
/// Сработка таймера
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CheckTimeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if ((DateTime.Now.Hour == DemandTime.Hour) && (DateTime.Now.Minute == DemandTime.Minute) && (DateTime.Now.Second == DemandTime.Second))
{
CheckTimeTimer.Stop();
///Создавать документ следующим числом, если время формирования больше 22
///Если время от нуля до 5 то дата срабатывания- предыдущее число
int DateDocNextDay = 1;
if (DateTime.Now.Hour < 10)
DateDocNextDay = 0;
Logger.WriteToLog("Срабатывание таймера запуска формирований требования на склад");
try
{
//Проверка на работу потока выгрузки
if (!(Loader.DataContext is FbDataConnection))
{
///Ждем минуту до следующего запуска
Logger.WriteToLog("Ожидание завершения потока загрузки чеков ");
DemandTime=DemandTime.AddMinutes(1);
}
else
{
if (ExecDemandJob)
{
List<Warehouse> wh = Loader.DbLoad<Warehouse>("");
string query = "";
foreach (Warehouse w in wh)
{
List<DemandWhSetting> whs = (from s in DemandWhSettings where s.IdWarehouse == w.Id select s).ToList();
//Доп настроек нет, формируем на дату выгрузки
if (whs.Count == 0)
{
query = "execute procedure SP_CREATE_WH_DEMAND (0," + w.Id + ",null,null,null," + DateDocNextDay.ToString() + ",null,1 )";
Logger.WriteToLog("Выполнение команды " + query);
Loader.DataContext.ExecuteNonQuery(query);
}
else
foreach (DemandWhSetting dw in whs)
{
ComplexWdCondition cond = (from d in dw.Conditions where d.wdStartDemand == DateTime.Now.DayOfWeek - DateDocNextDay select d).SingleOrDefault();
if (cond != null)
{
query = "execute procedure SP_CREATE_WH_DEMAND (0," + w.Id + ",'" + DateTime.Now.ToShortDateString() + "','" + cond.MinDate.ToShortDateString() + "','" + cond.MaxDate.ToShortDateString() + "'," + DateDocNextDay.ToString() + ",null,1 )";
Logger.WriteToLog("Выполнение команды " + query);
Loader.DataContext.ExecuteNonQuery(query);
}
}
}
}
if (CloseReciepts)
{
Logger.WriteToLog("Закрытие чеков");
Loader.DataContext.ExecuteNonQuery("execute procedure sp_close_day");
}
}
}
catch (Exception ex)
{
Logger.WriteToLog("Ошибка формирования требований на склад \n" + ex.Message +"\n"+ex.StackTrace);
}
finally
{
CheckTimeTimer.Start();
}
Logger.WriteToLog("Работа таймера закончена");
}
}
void dictionaryLoader_onNeedWriteLog(string LogMessage)
{
Logger.WriteToLog(LogMessage);
}
/// <summary>
/// Сохранение данных
/// </summary>
/// <returns></returns>
public bool SaveData()
{
bool result = false;
Logger.WriteToLog("Сохранение данных ");
Stopwatch sw = new Stopwatch();
sw.Start();
#if !debug
try
{
#endif
dictionary.SaveData();
//Удаление файлов пакетов
if (Directory.Exists(Settings.AppDir + @"\Packets"))
Directory.Delete(Settings.AppDir + @"\Packets",true);
result = true;
sw.Stop();
Logger.WriteToLog("Сохранение данных завершено за " + KartObjects.Helper.formatSwString(sw));
#if !debug
}
catch (Exception e1)
{
result = false;
Logger.WriteToLog("Ошибка сохранения данных "+e1.Message);
}
#endif
CheckTimeTimer.Stop();
return result;
}
/// <summary>
/// Сохранение Штрихкодов с дополнительным наименованием
/// </summary>
public void SaveBC()
{
if (Saver.DataContext != null)
{
Logger.WriteToLog("Сохранение всех штрихкодов " );
Stopwatch sw = new Stopwatch();
sw.Start();
/*
if (DataDictionary.sAssortments != null)
foreach (Assortment a in DataDictionary.sAssortments)
{
//a.Good = g;
//обновляем у каждого штрихкода дополнительно наименование для печати на чеке dklinkfo
Barcode b = DataDictionary.sBarcodes.FirstOrDefault(q => q.IdAssortment == a.Id);
if (b != null)
{
if (b.barcode == "2116000170983")
Logger.WriteToLog("шк " + b.barcode + " описание до " + b.AddName);
if (a.NameDB != null)
b.AddName = a.NameDB;
if (b.barcode == "2116000170983")
Logger.WriteToLog("шк " + b.barcode + " описание после " + b.AddName);
}
}
*/
//Сохраняем каждый штрихкод
foreach (Barcode b in DataDictionary.SBarcodes)
{
if (b.barcode == "2116000170983")
Logger.WriteToLog("шк " + b.barcode + " описание " + b.AddName);
Saver.SaveToDb<Barcode>(b);
}
sw.Stop();
Logger.WriteToLog("Сохранение всех штрихкодов завершено за " + KartObjects.Helper.formatSwString(sw));
}
}
/// <summary>
/// Время последнего просмотра лога
/// </summary>
private DateTime LastLogTime
{
get;
set;
}
public List<string> getCurrentBarcodesList()
{
Logger.WriteToLog("Анализ лога с даты "+LastLogTime.ToString());
//List<Receipt> r = Loader.DkPosLogLoad<Receipt>(new DateTime(2011, 2, 24, 16, 59, 27).ToString());
List<Receipt> rl = Loader.DkPosLogLoad<Receipt>(LastLogTime.ToString());
Receipt r = rl.FirstOrDefault(q => q.ReceiptState == ReceiptState.Open);
LastLogTime = DateTime.Now;
if (r != null) return r._barcodeList;
else return null;
}
public DateTime DemandTime { get; set; }
public DateTime ReceiptsDate
{
get
{
return (dictionaryLoader as DictionaryLoaderReceiptSaver).LastLoadReceiptTime;
}
set
{
(dictionaryLoader as DictionaryLoaderReceiptSaver).LastLoadReceiptTime = value;
}
}
public bool LoadReceipts
{
set
{
(dictionaryLoader as DictionaryLoaderReceiptSaver).LoadReceipts = value;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class DangerBase : MonoBehaviour {
GameObject levels;
GameObject fade;
public GameObject centre;
GameObject player;
string oldname;
string levelname;
string levelNum;
GameObject endEffect;
GameObject currentLevel;
GameObject Fix;
public int FixCont;
AudioSource source;
public AudioClip sawOn;
[Header("Rotation")]
public bool Rotate;
public float SpeedRotate;
[Header("Folow")]
public bool FolowToPlayer;
public Transform Player;
public float SpeedFolow;
[Header("Move")]
public bool Move;
public Vector2 Distance;
private Vector3 StartPosition;
public float MoveSpeed;
private Vector2 States = new Vector2 (1, 1);
[Header("Other")]
private bool death = false;
public AudioClip SawPlayer;
public AudioClip FirePlayer;
public bool ThisSaw = false;
[Header("Fire")]
public bool JustFire = false;
void Start(){
Fix = GameObject.Find("HUD").transform.GetChild(0).gameObject;
levels = GameObject.Find("Levels");
player = levels.transform.GetChild(2).gameObject;
endEffect = levels.transform.GetChild(3).GetChild(0).gameObject;
fade = levels.transform.GetChild(1).gameObject;
currentLevel = transform.parent.parent.gameObject;
oldname = currentLevel.name;
levelname = oldname.Substring(0, 6);
source = GetComponent<AudioSource>();
if (Distance.x == 0)
States = new Vector2 (0, States.y);
if (Distance.y == 0)
States = new Vector2 (States.x, 0);
StartPosition += transform.localPosition;
if (transform.localPosition.x < Distance.x)
States = new Vector2 (-1, States.y);
if (transform.localPosition.y < Distance.y)
States = new Vector2 (States.x, -1);
}
void FixedUpdate(){
if (Rotate)
transform.Rotate (0, 0, SpeedRotate);
if (FolowToPlayer) {
if (transform.position.x >= Player.position.x && transform.position.y >= Player.position.y)
transform.position += new Vector3 (-SpeedFolow, -SpeedFolow, 0);
if (transform.position.x >= Player.position.x && transform.position.y <= Player.position.y)
transform.position += new Vector3 (-SpeedFolow, SpeedFolow, 0);
if (transform.position.x <= Player.position.x && transform.position.y <= Player.position.y)
transform.position += new Vector3 (SpeedFolow, SpeedFolow, 0);
if (transform.position.x <= Player.position.x && transform.position.y >= Player.position.y)
transform.position += new Vector3 (SpeedFolow, -SpeedFolow, 0);
}
if (Move) {
if (States.x == 1) {
if (transform.localPosition.x > Distance.x)
transform.localPosition += new Vector3 (-MoveSpeed, 0, 0);
else
States = new Vector2 (2, States.y);
}
if (States.x == 2) {
if (transform.localPosition.x < StartPosition.x)
transform.localPosition += new Vector3 (MoveSpeed, 0, 0);
else
States = new Vector2 (1, States.y);
}
if (States.x == -1) {
if (transform.localPosition.x < Distance.x)
transform.localPosition += new Vector3 (MoveSpeed, 0, 0);
else
States = new Vector2 (-2, States.y);
}
if (States.x == -2) {
if (transform.localPosition.x > StartPosition.x)
transform.localPosition += new Vector3 (-MoveSpeed, 0, 0);
else
States = new Vector2 (-1, States.y);
}
if (States.y == 1) {
if (transform.localPosition.y > Distance.y)
transform.localPosition += new Vector3 (0, -MoveSpeed, 0);
else
States = new Vector2 (States.x, 2);
}
if (States.y == 2) {
if (transform.localPosition.y < StartPosition.y)
transform.localPosition += new Vector3 (0, MoveSpeed, 0);
else
States = new Vector2 (States.x, 1);
}
if (States.y == -1) {
if (transform.localPosition.y < Distance.y)
transform.localPosition += new Vector3 (0, MoveSpeed, 0);
else
States = new Vector2 (States.x, -2);
}
if (States.y == -2) {
if (transform.localPosition.y > StartPosition.y)
transform.localPosition += new Vector3 (0, -MoveSpeed, 0);
else
States = new Vector2 (States.x, -1);
}
}
}
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.name == "Player") {
PlayerGameOver(other.gameObject.transform, endEffect.transform);
source.PlayOneShot(sawOn);
}
}
private void PlayerGameOver(Transform Player, Transform Particle)
{
Player.GetComponent<Animator>().SetTrigger("die");
Particle.gameObject.SetActive(true);
Particle.transform.position = Player.transform.position;
Player.GetComponent<SoundCollision>().enabled = false;
Player.GetComponent<Collider2D>().enabled = false;
Invoke("enterAnim", 2.0f);
}
void enterAnim()
{
fade.GetComponent<Animator>().SetTrigger("Enter");
Invoke("reborn", 0.5f);
}
void reborn()
{
endEffect.gameObject.SetActive(false);
gameObject.transform.parent.parent.parent.parent.transform.rotation = Quaternion.identity;
player.GetComponent<Animator>().SetTrigger("reborn");
player.GetComponent<Collider2D>().enabled = true;
if(levelname == "Level1")
{
Fix.GetComponent<Fix>().fixCount = 2;
Fix.GetComponent<Fix>().refreshFix();
}
else if (levelname == "Level2")
{
Fix.GetComponent<Fix>().fixCount = 0;
Fix.GetComponent<Fix>().refreshFix();
}
else if (levelname == "Level3")
{
Fix.GetComponent<Fix>().fixCount = 1;
Fix.GetComponent<Fix>().refreshFix();
}
else if (levelname == "Level4")
{
Fix.GetComponent<Fix>().fixCount = 0;
Fix.GetComponent<Fix>().refreshFix();
}
else if (levelname == "Level5")
{
Fix.GetComponent<Fix>().fixCount = 0;
Fix.GetComponent<Fix>().refreshFix();
}
else if (levelname == "Level6")
{
Fix.GetComponent<Fix>().fixCount = 1;
Fix.GetComponent<Fix>().refreshFix();
}
else if (levelname == "Level7")
{
Fix.GetComponent<Fix>().fixCount = 4;
Fix.GetComponent<Fix>().refreshFix();
}
Instantiate(Resources.Load(levelname,typeof(GameObject)) as GameObject, levels.transform.GetChild(3));
Invoke("newAnim", 0.5f);
}
void newAnim()
{
player.transform.position = centre.transform.position;
player.transform.localScale = new Vector3(1, 1, 1);
fade.GetComponent<Animator>().SetTrigger("New");
Destroy(currentLevel);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EventSystem;
public class Loan
{
public int Amount { get; private set; }
public float InterestRate { get; private set; }
public int Duration { get; private set; } // in years
public int TotalPaid { get; private set; }
public int TotalOwed {
get { return Mathf.FloorToInt(Amount * InterestRate) + Amount; }
}
public int MonthlyPayment {
get { return TotalOwed / (Duration * 12); }
}
public int Owed {
get { return TotalOwed - TotalPaid; }
}
public bool Completed {
get { return TotalOwed <= 0; }
}
public Loan(int amount, float interestRate, int duration) {
Amount = amount;
InterestRate = interestRate;
Duration = duration;
TotalPaid = 0;
Events.instance.AddListener<NewMonthEvent>(OnNewMonthEvent);
Print();
}
void OnNewMonthEvent(NewMonthEvent e) {
TotalPaid += MonthlyPayment;
if (Completed) {
Events.instance.RemoveListener<NewMonthEvent>(OnNewMonthEvent);
}
}
public void Print() {
Debug.Log (string.Format("Amount: {0}\nInterestRate: {1}\nDuration: {2}\nTotalPaid: {3}\nTotalOwed: {4}\nMonthlyPayment: {5}",
Amount,
InterestRate,
Duration,
TotalPaid,
TotalOwed,
MonthlyPayment));
}
}
|
using System.Collections.Generic;
namespace ticketarena.lib.model
{
public class ReturnResult
{
public ReturnResultTypes ResultType { get; set; }
public IEnumerable<Coin> Coins { get; set; }
}
} |
using ClassesIerarchy.Interfaces;
using System;
namespace ClassesIerarchy
{
class StartUp
{
static void Main(string[] args)
{
string command = Console.ReadLine();
while (command!="End")
{
string []array = command.Split();
if (array[0] == "Private")
{
var privat = new Private(int.Parse(array[1]), array[2], array[3], decimal.Parse(array[4]));
Console.WriteLine(privat.ToString());
}
if (array[0] == "Commando")
{
if (Enum.TryParse(array[5], true, out CorpType corp))
{
var privat = new Commando(int.Parse(array[1]), array[2], array[3], decimal.Parse(array[4]), corp);
Console.WriteLine(privat.ToString());
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MarieCurie.Interview.Assets.Model;
namespace MarieCurie.HelperServices.Utilities
{
public static class HelperServicesUtility
{
public static bool checkOpenningHours(string dayOfWeek, int Hour, HelperService center)
{
if (dayOfWeek == DayOfWeek.Monday.ToString())
{
if (center.MondayOpeningHours[0] <= Hour
&& center.MondayOpeningHours[1] >= Hour)
return true;
else
return false;
}
else if (dayOfWeek == DayOfWeek.Tuesday.ToString())
{
if (center.TuesdayOpeningHours[0] <= Hour
&& center.TuesdayOpeningHours[1] >= Hour)
return true;
else
return false;
}
else if (dayOfWeek == DayOfWeek.Wednesday.ToString())
{
if (center.WednesdayOpeningHours[0] <= Hour
&& center.WednesdayOpeningHours[1] >= Hour)
return true;
else
return false;
}
else if (dayOfWeek == DayOfWeek.Thursday.ToString())
{
if (center.ThursdayOpeningHours[0] <= Hour
&& center.ThursdayOpeningHours[1] >= Hour)
return true;
else
return false;
}
else if (dayOfWeek == DayOfWeek.Friday.ToString())
{
if (center.FridayOpeningHours[0] <= Hour
&& center.FridayOpeningHours[1] >= Hour)
return true;
else
return false;
}
else if (dayOfWeek == DayOfWeek.Saturday.ToString())
{
if (center.SaturdayOpeningHours[0] <= Hour
&& center.SaturdayOpeningHours[1] >= Hour)
return true;
else
return false;
}
else // (dayOfWeek == DayOfWeek.Sunday.ToString())
{
if (center.SundayOpeningHours[0] <= Hour
&& center.SundayOpeningHours[1] >= Hour)
return true;
else
return false;
}
}
public static string nextOpenningHours(string dayOfWeek, int Hour, HelperService center)
{
if (dayOfWeek == DayOfWeek.Monday.ToString())
{
var openUntil = center.MondayOpeningHours[1] >= 12 ?
$"{center.MondayOpeningHours[1] - 12}.00 pm" : $"{center.MondayOpeningHours[1]}.00 am";
var openNext = center.TuesdayOpeningHours[0] >= 12 ?
$"{center.TuesdayOpeningHours[0] - 12}.00 pm" : $"{center.TuesdayOpeningHours[0]}.00 am";
if (center.MondayOpeningHours[0] <= Hour
&& center.MondayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
return $"Reopens tomorrow {openNext}";
}
else if (dayOfWeek == DayOfWeek.Tuesday.ToString())
{
var openUntil = center.TuesdayOpeningHours[1] >= 12 ?
$"{center.TuesdayOpeningHours[1] - 12}.00 pm" : $"{center.TuesdayOpeningHours[1]}.00 am";
var openNext = center.WednesdayOpeningHours[0] >= 12 ?
$"{center.WednesdayOpeningHours[0] - 12}.00 pm" : $"{center.WednesdayOpeningHours[0]}.00 am";
if (center.TuesdayOpeningHours[0] <= Hour
&& center.TuesdayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
return $"Reopens tomorrow {openNext}";
}
else if (dayOfWeek == DayOfWeek.Wednesday.ToString())
{
var openUntil = center.WednesdayOpeningHours[1] >= 12 ?
$"{center.WednesdayOpeningHours[1] - 12}.00 pm" : $"{center.WednesdayOpeningHours[1]}.00 am";
var openNext = center.ThursdayOpeningHours[0] >= 12 ?
$"{center.ThursdayOpeningHours[0] - 12}.00 pm" : $"{center.ThursdayOpeningHours[0]}.00 am";
if (center.WednesdayOpeningHours[0] <= Hour
&& center.WednesdayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
return $"Reopens tomorrow {openNext}";
}
else if (dayOfWeek == DayOfWeek.Thursday.ToString())
{
var openUntil = center.ThursdayOpeningHours[1] >= 12 ?
$"{center.ThursdayOpeningHours[1] - 12}.00 pm" : $"{center.ThursdayOpeningHours[1]}.00 am";
var openNext = center.FridayOpeningHours[0] >= 12 ?
$"{center.FridayOpeningHours[0] - 12}.00 pm" : $"{center.FridayOpeningHours[0]}.00 am";
if (center.ThursdayOpeningHours[0] <= Hour
&& center.ThursdayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
return $"Reopens tomorrow {openNext}";
}
else if (dayOfWeek == DayOfWeek.Friday.ToString())
{
var openUntil = center.FridayOpeningHours[1] >= 12 ?
$"{center.FridayOpeningHours[1] - 12}.00 pm" : $"{center.FridayOpeningHours[1]}.00 am";
var openNext = center.SaturdayOpeningHours[0] >= 12 ?
$"{center.SaturdayOpeningHours[0] - 12}.00 pm" : $"{center.SaturdayOpeningHours[0]}.00 am";
if (center.FridayOpeningHours[0] <= Hour
&& center.FridayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
return $"Reopens tomorrow {openNext}";
}
else if (dayOfWeek == DayOfWeek.Saturday.ToString())
{
var openUntil = center.SaturdayOpeningHours[1] >= 12 ?
$"{center.SaturdayOpeningHours[1] - 12}.00 pm" : $"{center.SaturdayOpeningHours[1]}.00 am";
var openNext = center.MondayOpeningHours[0] >= 12 ?
$"{center.MondayOpeningHours[0] - 12}.00 pm" : $"{center.MondayOpeningHours[0]}.00 am";
if (center.SaturdayOpeningHours[0] <= Hour
&& center.SaturdayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
//assumed closed on Sunday/Mock data supports that
return $"Reopens Monday {openNext}";
}
else
{
var openUntil = center.SundayOpeningHours[1] >= 12 ?
$"{center.SundayOpeningHours[1] - 12}.00 pm" : $"{center.SundayOpeningHours[1]}.00 am";
var openNext = center.MondayOpeningHours[0] >= 12 ?
$"{center.MondayOpeningHours[0] - 12}.00 pm" : $"{center.MondayOpeningHours[0]}.00 am";
if (center.SundayOpeningHours[0] <= Hour
&& center.SundayOpeningHours[1] >= Hour)
return $"Open today until {openUntil}";
else
//assumed closed on Sunday/Mock data supports that
return $"Reopens Monday {openNext}";
}
}
}
}
|
// HomePage.cs
//
using System;
using System.Collections;
using System.Html;
using System.Net;
using jQueryApi;
using SportsLinkScript.Shared;
using System.Serialization;
namespace SportsLinkScript.Controls
{
public class QuickMatch : Module
{
public QuickMatch(Element element)
: base(element)
{
this.Obj.Find(".findMatch").Click(CreateMatch);
((jQueryUIObject)this.Obj.Find(".datepicker")).DatePicker(new JsonObject("minDate", 0));
((jQueryUIObject)this.Obj.Find(".findMatch")).Button();
((jQueryUIObject)this.Obj.Find("select")).SelectMenu();
Utility.WireLocationAutoComplete((jQueryUIObject)this.Obj.Find(".placesAutoFill"), (jQueryUIObject)this.Obj.Find(".placesAutoValue"));
}
private void CreateMatch(jQueryEvent e)
{
jQueryObject button = jQuery.FromElement(e.CurrentTarget);
jQueryObject module = button.Parents(".module").First();
string date = module.Find(".datepicker").GetValue();
string time = module.Find(".time").GetValue();
string ampm = module.Find(".ampm").GetValue();
string comments = module.Find(".comments").GetValue();
string courtData = module.Find(".placesAutoValue").GetValue();
string datetime = date + " " + time + ampm;
ArrayList ids = new ArrayList();
module.Find(".cities input").Each((ElementIterationCallback)delegate(int index, Element element)
{
ids.Add(((CheckBoxElement)element).Value);
});
DoCreateMatch(this.Obj, datetime, ids, courtData, comments, 0, null);
}
public static void DoCreateMatch(jQueryObject obj, string datetime, object ids, string courtData, string comments, object opponentId, Callback callback)
{
JsonObject parameters = new JsonObject("date", datetime, "locations", ids, "courtData", courtData, "comments", comments, "opponentId", opponentId);
obj.Attribute("disabled", "disabled").AddClass("ui-state-disabled");
jQuery.Post("/services/CreateOffer?signed_request=" + Utility.GetSignedRequest(), Json.Stringify(parameters), (AjaxRequestCallback<object>)delegate(object data, string textStatus, jQueryXmlHttpRequest<object> request)
{
obj.Attribute("disabled", "").RemoveClass("ui-state-disabled");
Utility.ProcessResponse((Dictionary)data);
if (null != callback)
{
callback();
}
}
);
}
}
}
|
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.WsFederation;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SFA.DAS.ProviderCommitments.Configuration;
namespace SFA.DAS.ProviderCommitments.Web.Authentication
{
public static class AuthenticationExtensions
{
public static IServiceCollection AddProviderAuthentication(this IServiceCollection services, IConfiguration config)
{
if (config["UseStubProviderAuth"] != null && bool.Parse(config["UseStubProviderAuth"]))
{
services.AddProviderStubAuthentication();
}
else
{
services.AddProviderIdamsAuthentication(config);
}
return services;
}
public static IServiceCollection AddProviderStubAuthentication(this IServiceCollection services)
{
services.AddAuthentication("Provider-stub").AddScheme<AuthenticationSchemeOptions, ProviderStubAuthHandler>(
"Provider-stub",
options => { }).AddCookie(options =>
{
options.AccessDeniedPath = "/Error/403";
options.CookieManager = new ChunkingCookieManager {ChunkSize = 3000};
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ReturnUrlParameter = "/Home/Index";
});
return services;
}
public static IServiceCollection AddProviderIdamsAuthentication(this IServiceCollection services, IConfiguration config)
{
var authenticationSettings = config.GetSection(ProviderCommitmentsConfigurationKeys.AuthenticationSettings).Get<AuthenticationSettings>();
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
})
.AddWsFederation(options =>
{
options.MetadataAddress = authenticationSettings.MetadataAddress;
options.Wtrealm = authenticationSettings.Wtrealm;
options.Events.OnSecurityTokenValidated = OnSecurityTokenValidated;
}).AddCookie(options =>
{
options.AccessDeniedPath = "/Error/403";
options.CookieManager = new ChunkingCookieManager {ChunkSize = 3000};
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ReturnUrlParameter = "/Home/Index";
});
return services;
}
private static Task OnSecurityTokenValidated(SecurityTokenValidatedContext context)
{
var claims = context.Principal.Claims;
var ukprn = claims.FirstOrDefault(claim => claim.Type == (ProviderClaims.Ukprn))?.Value;
return Task.CompletedTask;
}
public class ProviderStubAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ProviderStubAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IHttpContextAccessor httpContextAccessor) : base(options, logger, encoder, clock)
{
_httpContextAccessor = httpContextAccessor;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[]
{
new Claim(ClaimsIdentity.DefaultNameClaimType, "10005077"),
new Claim(ProviderClaims.DisplayName, "Test-U-Good Corporation"),
new Claim(ProviderClaims.Service, "DAA"),
new Claim(ProviderClaims.Ukprn, "10005077"),
new Claim(ProviderClaims.Upn, "10005077"),
new Claim(ProviderClaims.Email, "test+10005077@test.com"),
new Claim(ClaimsIdentity.DefaultRoleClaimType, "Provider")
};
var identity = new ClaimsIdentity(claims, "Provider-stub");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Provider-stub");
var result = AuthenticateResult.Success(ticket);
_httpContextAccessor.HttpContext.Items.Add(ClaimsIdentity.DefaultNameClaimType,"10005077");
_httpContextAccessor.HttpContext.Items.Add(ClaimsIdentity.DefaultRoleClaimType,"Provider");
_httpContextAccessor.HttpContext.Items.Add(ProviderClaims.DisplayName,"Test-U-Good Corporation");
return Task.FromResult(result);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class GizmosDemo : MonoBehaviour
{
void OnDrawGizmosSelected()
{
//改变gizmo的颜色
Gizmos.color = new Color32(145, 244, 139, 210);
Gizmos.DrawWireCube(transform.position, transform.lossyScale);
}
[DrawGizmo(GizmoType.NonSelected | GizmoType.Active)]
static void DrawExampleGizmos(MonoBehaviour example, GizmoType gizmoType)
{
var transform = example.transform;
Gizmos.color = new Color32(145, 244, 139, 210);
//GizmoType.Active的时候用红色
if ((gizmoType & GizmoType.Active) == GizmoType.Active)
Gizmos.color = Color.red;
Gizmos.DrawWireCube(transform.position, transform.lossyScale);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BitClassroom.DAL.Models;
using System.Data.Entity;
using System.Net;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using PagedList;
namespace BitClassroom.MVC.Controllers
{
public class MentorsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Mentors
[Authorize(Roles = "Admin")]
public ActionResult Index(string sortingOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortingOrder;
ViewBag.MentorNameSort = sortingOrder == "mentorNameAscending" ? "mentorNameDescending" : "mentorNameAscending";
ViewBag.MentorLastnameSort = sortingOrder == "mentorLastnameAscending" ? "mentorLastnameDescending" : "mentorLastnameAscending";
ViewBag.StudentNameSort = sortingOrder == "studentNameAscending" ? "studentNameDescending" : "studentNameAscending";
ViewBag.StudentLastnameSort = sortingOrder == "studentLastnameAscending" ? "studentLastnameDescending" : "studentLastnameAscending";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var listOfAssignedMentors = from x in db.Users.Where(x => x.MentorId != null) select x;
if (!String.IsNullOrEmpty(searchString) && searchString.Trim() != "")
{
listOfAssignedMentors = listOfAssignedMentors.Where(x => x.Mentor.Name.ToLower().Contains(searchString.ToLower())
|| x.Mentor.Lastname.ToLower().Contains(searchString.ToLower())
|| x.Name.ToLower().Contains(searchString.ToLower())
|| x.Lastname.ToLower().Contains(searchString.ToLower()));
}
switch (sortingOrder)
{
case "mentorNameAscending":
listOfAssignedMentors = listOfAssignedMentors.OrderBy(x => x.Mentor.Name);
break;
case "mentorNameDescending":
listOfAssignedMentors = listOfAssignedMentors.OrderByDescending(x => x.Mentor.Name);
break;
case "mentorLastnameAscending":
listOfAssignedMentors = listOfAssignedMentors.OrderBy(x => x.Mentor.Lastname);
break;
case "mentorLastnameDescending":
listOfAssignedMentors = listOfAssignedMentors.OrderByDescending(x => x.Mentor.Lastname);
break;
case "studentNameAscending":
listOfAssignedMentors = listOfAssignedMentors.OrderBy(x => x.Name);
break;
case "studentNameDescending":
listOfAssignedMentors = listOfAssignedMentors.OrderByDescending(x => x.Name);
break;
case "studentLastnameAscending":
listOfAssignedMentors = listOfAssignedMentors.OrderBy(x => x.Lastname);
break;
case "studentLastnameDescending":
listOfAssignedMentors = listOfAssignedMentors.OrderByDescending(x => x.Lastname);
break;
default:
listOfAssignedMentors = listOfAssignedMentors.OrderBy(x => x.Id);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1); //means that if page is null set pageNumber to 1
return View(listOfAssignedMentors.ToPagedList(pageNumber, pageSize));
//return View(db.Users.Where(x => x.MentorId != null).ToList());
}
// GET
[Authorize(Roles = "Admin")]
public ActionResult Create()
{
var mentorRole = db.Roles.Where(x => x.Name.Contains("Mentor")).FirstOrDefault();
var studentRole = db.Roles.Where(x => x.Name.Contains("Student")).FirstOrDefault();
ViewBag.MentorId = new SelectList(db.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(mentorRole.Id)).OrderBy(z=>z.Name), "Id","FullName");
ViewBag.StudentId = new SelectList(db.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(studentRole.Id)).OrderBy(z => z.Name), "Id", "FullName");
return View();
}
// POST
[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult Create(string studentId, string mentorId)
{
ApplicationUser user = new ApplicationUser();
string userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
var student = db.Users.Find(studentId);
var mentor = db.Users.Find(mentorId);
student.Mentor = mentor;
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
Notification notification = new Notification();
notification.SenderId = mentorId;
notification.RecipientId = studentId;
notification.Content = "is assigned to you as new mentor";
db.Notifications.Add(notification);
Notification notification1 = new Notification();
notification1.RecipientId = mentorId;
notification1.SenderId = studentId;
notification1.Content = "is assigned to you as new mentee";
db.Notifications.Add(notification1);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MentorId = new SelectList(db.Users, "Id", "FullName", user.MentorId);
ViewBag.StudentId = new SelectList(db.Users, "Id", "FullName", user.Id);
return View(user);
}
[Authorize(Roles = "Admin")]
public ActionResult Details(string studentId, string mentorId)
{
if (studentId == null || mentorId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
List<ApplicationUser> user = db.Users.Where(x => x.Id == studentId && x.MentorId == mentorId).ToList();
if (user == null)
{
return HttpNotFound();
}
return View(user[0]);
}
[Authorize(Roles = "Admin")]
public ActionResult Delete(string studentId, string mentorId)
{
if (studentId == null || mentorId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
List<ApplicationUser> user = db.Users.Where(x => x.Id == studentId && x.MentorId == mentorId).ToList();
if (user == null)
{
return HttpNotFound();
}
return View(user[0]);
}
//POST
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult DeleteConfirmed(string studentId, string mentorId)
{
var student = db.Users.Find(studentId);
if (student == null)
{
return HttpNotFound();
}
student.MentorId = null;
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
|
using System;
using Microsoft.Xna.Framework;
namespace VoxelSpace {
public struct Bounds {
public Vector3 Position;
public Vector3 Size;
public Vector3 Center {
get => Position + Size / 2;
set => Position = value - Size / 2;
}
public Vector3 Min {
get => Position;
set {
Size += Position - value;
Position = value;
}
}
public Vector3 Max {
get => Position + Size;
set {
Size = Position + value;
}
}
public Coords MinCoords =>
new Coords((int)MathF.Floor(Min.X), (int) MathF.Floor(Min.Y), (int) MathF.Floor(Min.Z));
public Coords MaxCoords =>
new Coords((int)MathF.Ceiling(Max.X), (int) MathF.Ceiling(Max.Y), (int) MathF.Ceiling(Max.Z));
public Bounds(Vector3 position, Vector3 size) {
Position = position;
Size = size;
}
public Bounds(Vector3 size) {
Size = size;
Position = Vector3.Zero;
}
public Region GetBoundingRegion() {
return new Region(MinCoords, MaxCoords);
}
// move the bounds by a certain position delta, checking for and solving collisions withing a collision grid
// returns the actual change in position
// skinwidth: the amount of space to leave between the bounds and whatever surface it hits
// this is absolutely necessary if you dont want floating point errors to literally crash your game
// note: i spent all night trying to get this to work and that among other annoying things was what fixed 99% of issues. I can sleep now (will i? probably not. but i can.)
public Vector3 MoveInCollisionGrid(Vector3 delta, ICollisionGrid grid, float skinWidth = 1E-5f) {
float inc;
var d = delta;
var start = Position;
var startRegion = GetBoundingRegion();
bool hadCollision = false;
while (d.X != 0 || d.Y != 0 || d.Z != 0) {
if (d.X != 0) {
inc = MathF.Abs(d.X) < 1 ? d.X : MathF.Sign(d.X);
Position.X += inc;
if (grid.CheckBounds(this, startRegion)) {
hadCollision = true;
float x;
if (d.X > 0) {
x = MathF.Ceiling(Max.X) - 1 - Size.X - skinWidth;
}
else {
x = MathF.Floor(Min.X) + 1 + skinWidth;
}
d.X = 0;
Position.X = x;
}
else {
d.X -= inc;
}
}
if (d.Y != 0) {
inc = MathF.Abs(d.Y) < 1 ? d.Y : MathF.Sign(d.Y);
Position.Y += inc;
if (grid.CheckBounds(this, startRegion)) {
hadCollision = true;
float y;
if (d.Y > 0) {
y = MathF.Ceiling(Max.Y) - 1 - Size.Y - skinWidth;
}
else {
y = MathF.Floor(Min.Y) + 1 + skinWidth;
}
d.Y = 0;
Position.Y = y;
}
else {
d.Y -= inc;
}
}
if (d.Z != 0) {
inc = MathF.Abs(d.Z) < 1 ? d.Z : MathF.Sign(d.Z);
Position.Z += inc;
if (grid.CheckBounds(this, startRegion)) {
hadCollision = true;
float z;
if (d.Z > 0) {
z = MathF.Ceiling(Max.Z) - 1 - Size.Z - skinWidth;
}
else {
z = MathF.Floor(Min.Z) + 1 + skinWidth;
}
d.Z = 0;
Position.Z = z;
}
else {
d.Z -= inc;
}
}
}
if (hadCollision) {
return Position - start;
}
else {
return delta;
}
}
public bool Raycast(Vector3 origin, Vector3 direction, out RaycastResult result) {
bool inside = true;
Vector3 quadrant= Vector3.Zero;
Vector3 maxT = Vector3.Zero;
Vector3 candidatePlane = Vector3.Zero;
var min = Position;
var max = min + Size;
// candidate planes
// X
if (origin.X < min.X) {
quadrant.X = -1;
candidatePlane.X = min.X;
inside = false;
}
else if (origin.X > max.X) {
quadrant.X = 1;
candidatePlane.X = max.X;
inside = false;
}
else {
quadrant.X = 0;
}
// Y
if (origin.Y < min.Y) {
quadrant.Y = -1;
candidatePlane.Y = min.Y;
inside = false;
}
else if (origin.Y > max.Y) {
quadrant.Y = 1;
candidatePlane.Y = max.Y;
inside = false;
}
else {
quadrant.Y = 0;
}
// Z
if (origin.Z < min.Z) {
quadrant.Z = -1;
candidatePlane.Z = min.Z;
inside = false;
}
else if (origin.Z > max.Z) {
quadrant.Z = 1;
candidatePlane.Z = max.Z;
inside = false;
}
else {
quadrant.Z = 0;
}
// if we are inside, were done
if (inside) {
result = new RaycastResult() {
Point = origin,
Normal = Vector3.Zero,
Distance = 0
};
return true;
}
// calculate maxT
// X
if (quadrant.X != 0 && direction.X != 0)
maxT.X = (candidatePlane.X - origin.X) / direction.X;
else maxT.X = -1;
// Y
if (quadrant.Y != 0 && direction.Y != 0)
maxT.Y = (candidatePlane.Y - origin.Y) / direction.Y;
else maxT.Y = -1;
// Z
if (quadrant.Z != 0 && direction.Z != 0)
maxT.Z = (candidatePlane.Z - origin.Z) / direction.Z;
else maxT.Z = -1;
var plane = maxT.Max();
if (plane < 0){
result = new RaycastResult();
return false;
}
Vector3 point = Vector3.Zero;
Vector3 normal = Vector3.Zero;
if (plane == maxT.X) {
normal.X = quadrant.X;
point.X = candidatePlane.X;
point.Y = origin.Y + maxT.X * direction.X;
if (point.Y < min.Y || point.Y > max.Y) {
result = new RaycastResult();
return false;
}
point.Z = origin.Z + maxT.X * direction.X;
if (point.Z < min.Z || point.Z > max.Z) {
result = new RaycastResult();
return false;
}
}
else if (plane == maxT.Y) {
normal.Y = quadrant.Y;
point.Y = candidatePlane.Y;
point.X = origin.X + maxT.Y * direction.Y;
if (point.X < min.X || point.X > max.X) {
result = new RaycastResult();
return false;
}
point.Z = origin.Z + maxT.Y * direction.Y;
if (point.Z < min.Z || point.Z > max.Z) {
result = new RaycastResult();
return false;
}
}
else if (plane == maxT.Z) {
normal.Z = quadrant.Z;
point.Z = candidatePlane.Z;
point.X = origin.X + maxT.Z * direction.Z;
if (point.X < min.X || point.X > max.X) {
result = new RaycastResult();
return false;
}
point.Y = origin.Y + maxT.Z * direction.Z;
if (point.Y < min.Y || point.Y > max.Y) {
result = new RaycastResult();
return false;
}
}
var distance = Vector3.Distance(point, origin);
result = new RaycastResult() {
Point = point,
Normal = normal,
Distance = distance
};
return true;
}
}
} |
using System.Collections.Generic;
namespace Algorithms.Lib.Interfaces
{
public interface IGraphAtoFactory
{
IArcs CreateArc(INode from, INode to);
IEdge CreateEdge(INode node1, INode node2);
IOrgraph CreateOrgraph(IEnumerable<INode> nodes, IEnumerable<IArcs> edges);
IGraph CreateGraph(IEnumerable<INode> nodes, IEnumerable<IEdge> edges);
IOrgraph CreateOrgraph(params (string From, string To)[] edges);
IGraph CreateGraph(params (string Node1, string Node2)[] edges);
INode CreateNode(string name);
IPairNode CreatePairNode(string name, bool isX);
IRoute CreatePoute();
IPath CreatePath();
IOrgraph CreateOrgraph(int[,] incidence, params string[] names);
IWeighedEdge CreateWeighedEdge(IPairNode node1, IPairNode node2, int weight);
ITwoPartsWeighedGraph CreateTwoPartsWeighedGraph(int[,] pair, string[] xNames, string[] yNames);
IWeighedPairsGraph CreateWeighedPairsGraph(IEnumerable<IPairNode> nodeXs, IEnumerable<IPairNode> nodeYs);
ITwoPartsWeighedGraph CreateTwoPartsWeighedGraph(IEnumerable<IPairNode> nodeXs, IEnumerable<IPairNode> nodeYs);
ITwoPartsWeighedRout CreateTwoPartsWeighedRout(IPairNode start);
}
} |
using System.Windows;
using System.Windows.Controls;
using BLL.Services;
using UI.ViewModels;
namespace UI.Pages
{
/// <summary>
/// Логика взаимодействия для RecordsListPage.xaml
/// </summary>
public partial class RecordsListPage : Page
{
private readonly RecordsListViewModel _viewModel;
public RecordsListPage()
{
_viewModel = new RecordsListViewModel(
ServiceProviderContainer.GetService<RecordService>(),
ServiceProviderContainer.GetService<CategoryService>()
);
DataContext = _viewModel;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
ShowRecordModificationWindow(new RecordModificationPage(null));
UpdateViewModelServices();
}
private void ChangeButton_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.IsCurrentRecordModelNotNull)
{
ShowRecordModificationWindow(new RecordModificationPage(_viewModel.CurrentRecordModel));
UpdateViewModelServices();
}
}
private void ShowRecordModificationWindow(RecordModificationPage content)
{
var dialogWindow = new DialogWindow()
{
Owner = Window.GetWindow(this),
Content = content
};
dialogWindow.ShowDialog();
}
public void UpdateViewModelServices()
{
_viewModel.UpdateServices(
ServiceProviderContainer.GetService<RecordService>(),
ServiceProviderContainer.GetService<CategoryService>()
);
}
}
}
|
public class Solution {
public bool IsIsomorphic(string s, string t) {
if (s.Length != t.Length) return false;
var m1 = new Dictionary<char, char>();
var m2 = new Dictionary<char, char>();
for (int i=0; i<s.Length; i++) {
if (m1.ContainsKey(s[i]) && m1[s[i]] != t[i]) {
return false;
}
if (m2.ContainsKey(t[i]) && m2[t[i]] != s[i]) {
return false;
}
if (!m1.ContainsKey(s[i])) {
m1[s[i]] = t[i];
}
if (!m2.ContainsKey(t[i])) {
m2[t[i]] = s[i];
}
}
return true;
}
} |
using UnityEngine;
/*
* Author : Elio Valenzuela
* Create on : 01-06-2018
*
* Clase controla a los poderes especiales del personaje principal
*/
public class Projectile : MonoBehaviour {
private Vector2 direction;
public float movementSpeed = 10;
public bool upgraded;
void Start () {
Destroy(gameObject, 2);
}
void Update () {
Move(direction);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!upgraded && collision.GetComponent<Collider2D>().tag != "Player")
{
Destroy(gameObject);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag != "Player")
{
Destroy(gameObject);
}
}
private void Move(Vector2 direction)
{
transform.Translate(direction * movementSpeed * Time.deltaTime);
}
public void SetDirection(Vector2 direction)
{
this.direction = direction;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TypeInThai.Models
{
public class OrderItem : Item
{
public int Quantity;
public decimal OrderPrice
{
get { return Price * Quantity; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
/*
* tags: regular expression, wildcard matching, dp, greedy
* Lc010_Regular_Expression_Matching: support only '.' and '*' in pattern. '*' Matches zero or more of the preceding char.
* Lc044_Wildcard_Matching: support only '?' and '*' in pattern. '*' can match 0-n any chars
* Lc072_Edit_Distance: Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
*/
namespace alg.dp
{
public class RegularExpression
{
/*
* Lc044_Wildcard_Matching: support only '?' and '*' in pattern. '*' can match 0-n any chars
* Greedy: Time(mn), Space(1)
* 1. For each '*', we try match 0 char, if it fails then restart from here to try match 1 char, and then next, ...
* 2. We only restart from only last '*'
*/
public bool IsMatch_Greedy(string s, string p)
{
int i = 0, j = 0, n = p.Length;
int match = -1, star = -1; // index of last star '*'
while (i < s.Length)
{
if (j < n && (p[j] == '?' || p[j] == s[i])) { i++; j++; }
else if (j < n && p[j] == '*') { match = i; star = j++; }
else if (star >= 0) { i = ++match; j = star + 1; }
else return false;
}
while (j < n && p[j] == '*') j++;
return j == n;
}
/*
* Lc072_Edit_Distance: Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
* Only 3 operations are permitted on a word: Insert/Delete/Replace a character.
* DP: Time(mn), Space(n)
* dp[i+1, j+1] is the minimum number of operations required to convert a[0..i] to b[0..j]
* dp[i+1, j+1] = dp[i, j], if a[i]==b[j]
* or 1 + min(dp[i, j+1], //insert
* dp[i+1, j], //delete
* dp[i, j]), //Replace a character
* base case: dp[0, j]=j, dp[i, 0]=i
*/
public int EditDistance(string word1, string word2)
{
int m = word1.Length, n = word2.Length;
var dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++) dp[i, 0] = i;
for (int j = 0; j <= n; j++) dp[0, j] = j;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (word1[i] == word2[j])
dp[i + 1, j + 1] = dp[i, j];
else
dp[i + 1, j + 1] = 1 + Math.Min(Math.Min(dp[i, j + 1], dp[i + 1, j]), dp[i, j]);
}
}
return dp[m, n];
}
/*
* Lc044_Wildcard_Matching: support only '?' and '*' in pattern. '*' can match 0-n any chars
* DP: Time(mn), Space(n)
* dp[i+1, j+1] is true if s[0..i] match to p[0..j]
* dp[i+1, j+1] = dp[i, j], if s[i]==p[j] or p[j]=='?'
* or dp[i+1, j] // '*' match 0, respective to Delete
* || dp[i, j+1], if p[j]=='*', // '*' match 1, respective to Insert
* base case: dp[0, 0]=true, dp[0, j]=true if all p[0..j-1] are '*'
*/
public bool IsMatch_Dp(string s, string p)
{
int m = s.Length, n = p.Length;
var dp = new bool[m + 1, n + 1];
dp[0, 0] = true;
for (int j = 1; j <= n && p[j - 1] == '*'; j++) dp[0, j] = true;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (s[i] == p[j] || p[j] == '?')
dp[i + 1, j + 1] = dp[i, j];
else if (p[j] == '*')
dp[i + 1, j + 1] = dp[i + 1, j] || dp[i, j + 1];
}
}
return dp[m, n];
}
/*
* Lc010_Regular_Expression_Matching: support only '.' and '*' in pattern. '*' Matches zero or more of the preceding char.
* DP: Time(mn), Space(n)
* dp[i+1, j+1] is true if s[0..i] match to p[0..j]
* dp[i+1, j+1] = dp[i, j], if s[i] match p[j]
* // 'x*' match 0 or 1 or 2, respective to Delete/Insert a character
* or dp[i+1, j-1] // 'x*' match 0, respective to Delete
* || dp[i+1, j] // 'x*' match 1 'x', respective to Delete '*'
* || (dp[i, j+1] && s[i] match p[j]), if p[j]=='*', // 'x*' match 2 'xx', respective to Insert
* base case: dp[0, 0]=true, dp[0, 2j]=true if all p[0..2i-1] are '*', i<j
*/
public bool IsMatch_Regex(string s, string p)
{
int m = s.Length, n = p.Length;
var dp = new bool[m + 1, n + 1];
dp[0, 0] = true;
for (int j = 2; j <= n && p[j - 1] == '*'; j += 2) dp[0, j] = true;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (s[i] == p[j] || p[j] == '.')
dp[i + 1, j + 1] = dp[i, j];
else if (p[j] == '*')
dp[i + 1, j + 1] = dp[i + 1, j - 1]
|| dp[i + 1, j]
|| (dp[i, j + 1] && (s[i] == p[j - 1] || p[j - 1] == '.'));
}
}
return dp[m, n];
}
public void Test()
{
Console.WriteLine(IsMatch_Greedy("aa", "a") == false);
Console.WriteLine(IsMatch_Greedy("aa", "*") == true);
Console.WriteLine(IsMatch_Greedy("cb", "?a") == false);
Console.WriteLine(IsMatch_Greedy("adceb", "*a*b") == true);
Console.WriteLine(IsMatch_Greedy("acdcb", "a*c?b") == false);
Console.WriteLine(IsMatch_Greedy("baababbaaaaabbababbbbbabaabaabaaabbaabbbbbbaabbbaaabbabbaabaaaaabaabbbaabbabababaaababbaaabaababbabaababbaababaabbbaaaaabbabbabababbbbaaaaaabaabbbbaababbbaabbaabbbbbbbbabbbabababbabababaaababbaaababaabb",
"*ba***b***a*ab**b***bb*b***ab**aa***baba*b***bb**a*abbb*aa*b**baba**aa**b*b*a****aabbbabba*b*abaaa*aa**b") == false);
Console.WriteLine(IsMatch_Dp("aa", "a") == false);
Console.WriteLine(IsMatch_Dp("aa", "*") == true);
Console.WriteLine(IsMatch_Dp("cb", "?a") == false);
Console.WriteLine(IsMatch_Dp("adceb", "*a*b") == true);
Console.WriteLine(IsMatch_Dp("acdcb", "a*c?b") == false);
Console.WriteLine(IsMatch_Dp("baababbaaaaabbababbbbbabaabaabaaabbaabbbbbbaabbbaaabbabbaabaaaaabaabbbaabbabababaaababbaaabaababbabaababbaababaabbbaaaaabbabbabababbbbaaaaaabaabbbbaababbbaabbaabbbbbbbbabbbabababbabababaaababbaaababaabb",
"*ba***b***a*ab**b***bb*b***ab**aa***baba*b***bb**a*abbb*aa*b**baba**aa**b*b*a****aabbbabba*b*abaaa*aa**b") == false);
Console.WriteLine(IsMatch_Regex("aa", "a") == false);
Console.WriteLine(IsMatch_Regex("aa", "a*") == true);
Console.WriteLine(IsMatch_Regex("cb", ".*") == true);
Console.WriteLine(IsMatch_Regex("aab", "c*a*b") == true);
Console.WriteLine(IsMatch_Regex("mississippi", "mis*is*p*.") == false);
Console.WriteLine(IsMatch_Regex("bbbba", ".*a*a") == true);
Console.WriteLine(EditDistance("horse", "ros") == 3);
Console.WriteLine(EditDistance("intention", "execution") == 5);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
public Dictionary<int,Empire> empires;
public Empire selectedEmpire;
private void Start()
{
}
void StartGame()
{
}
void LoadEmpiresFromInternalXML()
{
}
void LoadEmpiresFromExternalXML()
{
}
}
|
namespace NStandard.Security
{
public class DesCipher : SymmetricCipher<DesCipher>
{
public override int IVLength => 8;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Globalization;
using System.Threading;
using System.Collections.Specialized;
using System.IO;
using System.Xml;
namespace WindowsFA
{
public partial class FormPE : WindowsFA.FormFA
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
Boolean xmlHasChanged = false;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPE));
private System.Windows.Forms.Timer animationTimer;
private System.Windows.Forms.Timer indexTimer;
// private System.Windows.Forms.Panel animationCanvas;
string xmlFilename = "";
string xmloutput = "";
bool isAnimating = false;
bool isFirstTime = true;
int animCanvasWidth;
int animCanvasHeight;
Image imageCelPanel_left;
Image imageCelPanel_right;
Image imageCelPanel_bear_left;
Image imageCelPanel_bear_right;
Sprite[] spriteArray;
Sprite[] spriteArrayBackup;
Screen screen;
Rectangle r;
private PriceEarning pe1 = new PriceEarning();
private PriceEarning peQuoted = new PriceEarning();
private StringCollection symbolHistory = new StringCollection();
int currentSymbolHistoryIndex;
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
public FormPE()
{
InitializeComponent();
this.numericUpDownYield.Enabled = false;
setformTitle("Price Earning Analysis - FA");
this.Text = formTitle;
//this.openToolStripButton.Visible = false;
//this.saveToolStripButton.Visible = false;
//this.openToolStripMenuItem.Visible = false;
//this.toolStripSeparator3.Visible = false;
//this.saveToolStripMenuItem.Visible = false;
//this.saveAsToolStripMenuItem.Visible = false;
this.components = new System.ComponentModel.Container();
// this.animationCanvas = new System.Windows.Forms.Panel();
this.animationTimer = new System.Windows.Forms.Timer(this.components);
this.indexTimer = new System.Windows.Forms.Timer(this.components);
animationTimer.Tick += new System.EventHandler(this.animationTimer_Tick);
indexTimer.Tick += new EventHandler(indexTimer_Tick);
Random random = new Random();
indexTimer.Interval = 20000 + random.Next(500, 5000); ;
indexTimer.Enabled = true;
r = new Rectangle(0, 0, animationCanvas.Width, animationCanvas.Height);
animCanvasWidth = r.Width-5;
animCanvasHeight = r.Height-2;
StartAnimation();
}
private void StartAnimation()
{
// Load images for animation.
try
{
/*
string path = Directory.GetCurrentDirectory() + "\\redbull_tiny_to_left.gif";
imageCelPanel_left = Image.FromFile(path);
path = Directory.GetCurrentDirectory() + "\\redbull_tiny_to_right.gif";
//MessageBox.Show(path);
imageCelPanel_right = Image.FromFile(path);
*/
imageCelPanel_left = ((System.Drawing.Image)(resources.GetObject("redbull_tiny_to_left")));
imageCelPanel_right = ((System.Drawing.Image)(resources.GetObject("redbull_tiny_to_right")));
imageCelPanel_bear_left = ((System.Drawing.Image)(resources.GetObject("bear_tiny_to_left")));
imageCelPanel_bear_right = ((System.Drawing.Image)(resources.GetObject("bear_tiny_to_right")));
}
catch (FileNotFoundException)
{
MessageBox.Show("Image file not found." );
}
if(isAnimating == false)
{
if (isFirstTime == true)
{
// Class for doing actual drawing, along with offscreen.
screen = new Screen(animationCanvas, r, System.Windows.Forms.Panel.DefaultBackColor, System.Windows.Forms.Panel.DefaultBackColor);
isFirstTime = false;
}
if (screen == null || imageCelPanel_left == null || imageCelPanel_right == null)
{
MessageBox.Show("Animation not initialized!");
return;
}
isAnimating = true;
int numSprites = 4 ;
// Bigger values = shorter delays.
int delayMS = 75 ;
//-------------------------------------------------------------
// Create requested # of sprites.
//-------------------------------------------------------------
spriteArray = new Sprite[numSprites];
spriteArrayBackup = new Sprite[numSprites];
// for (int i = 0; i < numSprites; i++)
{
spriteArray[0] = new Sprite(imageCelPanel_left,
1, 60, 50, 1,
animCanvasWidth,
animCanvasHeight);
spriteArray[0].makeNewCoordinates();
spriteArray[1] = new Sprite(imageCelPanel_right,
1, 60, 50, 1,
animCanvasWidth,
animCanvasHeight);
spriteArray[1].makeNewCoordinates();
spriteArray[2] = new Sprite(imageCelPanel_bear_left,
1, 60, 50, 1,
animCanvasWidth,
animCanvasHeight);
spriteArray[2].makeNewCoordinates();
spriteArray[3] = new Sprite(imageCelPanel_bear_right,
1, 60, 50, 1,
animCanvasWidth,
animCanvasHeight);
spriteArray[3].makeNewCoordinates();
for (int i = 0; i < numSprites; i++)
{
spriteArrayBackup[i]=spriteArray[i];
}
}
//-------------------------------------------------------------
// Start our thread.
animationTimer.Interval = delayMS;
animationTimer.Enabled = true;
}
else
{
// Stop animation.
isAnimating = false;
// (This kills animation thread in Timer method.)
// This will also reset Start/Stop button to "Start."
}
}
private void recalcThreaded()
{
try
{
this.toolStripStatusLabel1.Text = "Retrieving quote...";
Cursor = Cursors.WaitCursor;
// Thread t = new Thread(recalc);
if (this.backgroundWorker1.CancellationPending)
{ return; }
if (this.backgroundWorker1.IsBusy)
{ this.backgroundWorker1.CancelAsync(); this.backgroundWorker1.RunWorkerAsync(); }
else {this.backgroundWorker1.RunWorkerAsync();}
// t.Start();
}
catch (InvalidOperationException)
{
this.toolStripStatusLabel1.Text = "Busy retrieving quote...";
}
}
private void recalc()
{
try
{
pe1.setSymbol(maskedTextBoxSymbol.Text.Trim());
try
{
if (Program.cApp.QuoteSourceIndex == 0)
{
pe1.GetQuotesYahoo();
}
if (Program.cApp.QuoteSourceIndex == 1)
{
pe1.GetQuotesGoogle();
}
}
catch (System.IO.FileNotFoundException)
{
pe1.GetQuotesYahoo();
}
if (!symbolHistory.Contains(pe1.getSymbol()))
{
symbolHistory.Add(pe1.getSymbol());
currentSymbolHistoryIndex = symbolHistory.Count - 1;
xmlHasChanged = true;
}
//recalc1();
//backupPE();
//calcPriceChange();
//maskedTextBoxSymbol.SelectAll();
}
catch (WebException)
{
MessageBox.Show("Could not retrieve the quote.", "Internet error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (FormatException)
{
MessageBox.Show("Invalid value returned.\nPlease contact support.", "Invalid value error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentOutOfRangeException)
{
MessageBox.Show(maskedTextBoxSymbol.Text + " is not a valid ticker symbol.\nTry with valid symbol.", "Invalid ticker symbol", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
//Cursor = Cursors.Default;
//maskedTextBoxSymbol.SelectAll();
}
private void recalc1()
{
try
{
numericUpDownEPS.Value = (decimal)pe1.getEPS("calc");
numericUpDownPE.Value = (decimal)pe1.getPE("calc");
numericUpDownPrice.Value = (decimal)pe1.getPrice();
numericUpDownYield.Value = (decimal)(100 * pe1.getYield("calc"));
// nfi.CurrencyDecimalDigits = 0;
// maskedTextBoxMarketCap.Text = pe1.getMarketCap().ToString("C", nfi);
maskedTextBoxMarketCap.Text = pe1.getMarketCapstr();
maskedTextBoxCompanyName.Text = pe1.getCompanyName();
refreshBackForward();
}
catch (ArgumentOutOfRangeException)
{
}
}
private void refreshBackForward()
{
if (symbolHistory.Count > 1 && currentSymbolHistoryIndex > 0)
{
buttonBack.Enabled = true;
}
else
{
buttonBack.Enabled = false;
}
if (symbolHistory.Count > 1 && currentSymbolHistoryIndex < symbolHistory.Count - 1)
{
buttonForward.Enabled = true;
}
else
{
buttonForward.Enabled = false;
}
if (symbolHistory.Count > 0)
{
comboBoxBack.Enabled = true;
comboBoxBack.Items.Clear();
comboBoxBack.Items.AddRange(new object[] { });
for (int i = 0; i < symbolHistory.Count; i++)
{
comboBoxBack.Items.Add(symbolHistory[i].ToString());
}
}
else
{
comboBoxBack.Enabled = false;
}
}
private void calcPriceChange()
{
double dPriceChange;
double dPriceChangePercent;
string strPriceChange;
string strPriceChangePercent;
dPriceChange = (Math.Round(pe1.getPrice() - peQuoted.getPrice(), 2));
dPriceChangePercent = ((pe1.getPrice() - peQuoted.getPrice()) / peQuoted.getPrice());
strPriceChange = (dPriceChange).ToString("C", nfi);
strPriceChangePercent = (dPriceChangePercent).ToString("P", nfi);
maskedTextBoxPriceChange.Text = strPriceChange;
maskedTextBoxPriceChangePercent.Text = strPriceChangePercent;
if (dPriceChange < 0.0)
{
maskedTextBoxPriceChange.BackColor = Color.Orange;
maskedTextBoxPriceChangePercent.BackColor = Color.Orange;
}
else if (dPriceChange > 0.0)
{
maskedTextBoxPriceChange.BackColor = Color.LawnGreen;
maskedTextBoxPriceChangePercent.BackColor = Color.LawnGreen;
}
else
{
maskedTextBoxPriceChange.BackColor = System.Windows.Forms.MaskedTextBox.DefaultBackColor;
maskedTextBoxPriceChangePercent.BackColor = System.Windows.Forms.MaskedTextBox.DefaultBackColor;
}
} //calcPriceChange
private void refreshIndex()
{
try
{
this.toolStripStatusLabel1.Text = "Retrieving market indices...";
Cursor = Cursors.WaitCursor;
if (this.backgroundWorker2.CancellationPending)
{ return; }
if (this.backgroundWorker2.IsBusy)
{ this.backgroundWorker2.CancelAsync(); this.backgroundWorker2.RunWorkerAsync(); }
else { this.backgroundWorker2.RunWorkerAsync(); }
}
catch (InvalidOperationException)
{
this.toolStripStatusLabel1.Text = "Busy getting market indices...";
}
}
private void calcPriceOpenChange()
{
double dPriceChange;
double dPriceChangePercent;
string strPriceChange;
string strPriceChangePercent;
dPriceChange = (Math.Round(pe1.getPrice() - pe1.getPriceOpen(), 2));
dPriceChangePercent = ((pe1.getPrice() - pe1.getPriceOpen()) / pe1.getPrice());
strPriceChange = (dPriceChange).ToString("C", nfi);
strPriceChangePercent = (dPriceChangePercent).ToString("P", nfi);
maskedTextBoxPriceOpen.Text = pe1.getPriceOpen().ToString("C", nfi);
maskedTextBoxPriceChangeMarket.Text = strPriceChange;
maskedTextBoxPriceChangeMarketPercent.Text = strPriceChangePercent;
if (dPriceChange < 0.0)
{
maskedTextBoxPriceChangeMarketPercent.BackColor = Color.Orange;
maskedTextBoxPriceChangeMarket.BackColor = Color.Orange;
spriteArray[0] = spriteArrayBackup[2];
spriteArray[1] = spriteArrayBackup[3];
}
else if (dPriceChange > 0.0)
{
maskedTextBoxPriceChangeMarketPercent.BackColor = Color.LawnGreen;
maskedTextBoxPriceChangeMarket.BackColor = Color.LawnGreen;
spriteArray[2] = spriteArrayBackup[0];
spriteArray[3] = spriteArrayBackup[1];
}
else
{
maskedTextBoxPriceChangeMarketPercent.BackColor = System.Windows.Forms.MaskedTextBox.DefaultBackColor;
maskedTextBoxPriceChangeMarket.BackColor = System.Windows.Forms.MaskedTextBox.DefaultBackColor;
}
}
private void negEPSMessageBox()
{
toolStripStatusLabel1.Text = "EPS is negative. Therefore, P/E is invalid.";
MessageBox.Show("Either EPS or P/E ratio is out of range.\n" +
"Cannot calculate Price, or P/E ratio based on negative EPS(earnings per share).\n" +
"P/E was temporarily set to negative value.", "Negative EPS error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void backupPE()
{
peQuoted.setSymbol(pe1.getSymbol());
peQuoted.setPrice(pe1.getPrice());
peQuoted.setEPS(pe1.getEPS());
peQuoted.setPE(pe1.getPE());
peQuoted.setYield(pe1.getYield());
}
private void buttonBack_Click(object sender, EventArgs e)
{
if (currentSymbolHistoryIndex > 0)
{
currentSymbolHistoryIndex = currentSymbolHistoryIndex - 1;
}
maskedTextBoxSymbol.Text=symbolHistory[currentSymbolHistoryIndex].ToString();
recalcThreaded();
}
private void buttonForward_Click(object sender, EventArgs e)
{
if (currentSymbolHistoryIndex < symbolHistory.Count)
{
currentSymbolHistoryIndex = currentSymbolHistoryIndex + 1;
}
try
{
maskedTextBoxSymbol.Text = symbolHistory[currentSymbolHistoryIndex].ToString();
}
catch (ArgumentOutOfRangeException)
{
currentSymbolHistoryIndex = symbolHistory.Count-1;
maskedTextBoxSymbol.Text = symbolHistory[currentSymbolHistoryIndex].ToString();
}
recalcThreaded();
}
protected void indexTimer_Tick(object sender, EventArgs e)
{
refreshIndex();
}
protected void animationTimer_Tick(object sender, System.EventArgs e)
{
// Using a timer here for animation
// (not a separate thread as in Java.
// Run animation.
if (isAnimating == true)
{
//-------------------------------------
// Do animation work.
//-------------------------------------
// Draw offscreen.
Graphics g = screen.getGraphics();
// Display and move every Sprite object.
// Sort array first -- This allows smaller (= more distant)
// objects to be drawn first.
if (spriteArray.Length > 1)
Sprite.sortArrayByZOrder(spriteArray);
// Erase and redraw objects off-screen.
screen.erase();
// Draw each object.
for (int i = 0; i < spriteArray.Length; i++)
{
spriteArray[i].draw(g);
spriteArray[i].calcNextCoordinates();
}
// Now 'flip' screen -- copy offscreen content to visible screen.
screen.flip();
}
else
{
// To-here, we're cleaning-up animation.
// Change button to 'Start' for next run.
animationTimer.Enabled = false;
}
}
public override void SaveXml(bool confirm)
{
if (xmlHasChanged)
{
if (confirm)
{
if (MessageBox.Show("Do you want to save the changes you made to your worksheet?", "Finance Advisor - Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
}
if (xmlFilename == "")
{
mainSaveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
mainSaveFileDialog.Filter = "Quote List Files (*.quo)|*.quo|TVM Files (*.tvm)|*.tvm|CFLO Files (*.cfo)|*.cfo|All Files (*.*)|*.*";
if (mainSaveFileDialog.ShowDialog() == DialogResult.OK)
{
xmlFilename = mainSaveFileDialog.FileName;
}
else
{
return;
}
}
using (StreamWriter sw = new StreamWriter(xmlFilename, false, Encoding.Unicode))
{
StringBuilder stringb = new StringBuilder();
XmlWriterSettingsLibrary settings = new XmlWriterSettingsLibrary();
using (XmlWriter writer = XmlWriter.Create(stringb, settings.maindocxmlsettings))
{
/*
* Sample document
*
<?xml version="1.0" encoding="utf-16"?>
<FA>
<PE>
<Symbol id="0">YHOO</Symbol>
<Symbol id="1">MSFT</Symbol>
</PE>
</FA>
*/
// Write XML data.
writer.WriteStartElement("FA");
writer.WriteStartElement("PE");
for (int i = 0; i < symbolHistory.Count; i++)
{
writer.WriteStartElement("Symbol");
string id = i.ToString();
writer.WriteAttributeString("id", id);
writer.WriteString(symbolHistory[i].ToString());
writer.WriteEndElement();
}
writer.WriteEndElement(); //PE
writer.WriteEndElement(); //FA
writer.Flush();
}
xmloutput = stringb.ToString();
sw.WriteLine(xmloutput);
}
this.Text = formTitle + " - " + xmlFilename;
xmlHasChanged = false;
}
}
public override void OpenFile(object sender, EventArgs e)
{
if (xmlHasChanged)
{
SaveXml(true);
}
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Filter = "Quote List Files (*.quo)|*.quo|TVM Files (*.tvm)|*.tvm|CFLO Files (*.cfo)|*.cfo|All Files (*.*)|*.*";
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
try
{
xmlFilename = openFileDialog.FileName;
xmlHasChanged = true;
doc.Load(xmlFilename);
XmlNode root = doc.DocumentElement;
XmlNodeList fa_pe_symbol = doc.GetElementsByTagName("Symbol");
symbolHistory.Clear();
for (int i=0; i < fa_pe_symbol.Count; i++)
{
if (symbolHistory.Count <= i)
{
symbolHistory.Add(fa_pe_symbol[i].InnerText);
}
else
{
symbolHistory[i] = fa_pe_symbol[i].InnerText;
}
}
/*
* Sample document
*
<?xml version="1.0" encoding="utf-16"?>
<FA>
<PE>
<Symbol id="0">YHOO</Symbol>
<Symbol id="1">MSFT</Symbol>
</PE>
</FA>
*/
this.Text = formTitle + " - " + xmlFilename;
xmlHasChanged = false;
refreshBackForward();
}
catch (XmlException)
{
MessageBox.Show("Invalid file.\nThe file you have opened is not valid for this application.", "Invalid file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (NullReferenceException)
{
MessageBox.Show("Incomplete file.\nThe file you have opened is not valid for this application.", "Invalid file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//catch (ArgumentOutOfRangeException)
//{
// MessageBox.Show("Value is out of range.\nThe file you have opened is not valid for this application.", "Invalid file", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
}
public override void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveXml(false);
}
public override void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
xmlFilename = "";
xmlHasChanged = true;
SaveXml(false);
}
public override void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
{
if (xmlHasChanged)
{
SaveXml(true);
}
Configuration.Serialize("config.xml", Program.cApp);
Application.Exit();
}
}
}
|
using System;
class complex {
private double Re = 0;
private double Im = 0;
//定义一个复数
public complex (double r, double m) {
Re = r;
Im = m;
}
//两个复数相加
public complex plus (complex a) {
double RE = a.Re + this.Re;
double IM = a.Im + this.Im;
complex c = new complex (RE, IM);
c.print ();
return c;
}
//两个复数相减
public complex Sub (complex a) {
double RE = this.Re - a.Re;
double IM = this.Im - a.Im;
complex c = new complex (RE, IM);
c.print ();
return c;
}
//两个复数相乘
public complex Mul (complex a) {
double RE = a.Re * this.Re - a.Im * this.Im;
double IM = a.Re * this.Im + a.Im * this.Re;
complex c = new complex (RE, IM);
c.print ();
return c;
}
//静态方法
static public complex operator + (complex a, complex b) {
double RE = a.Re + b.Re;
double IM = a.Im + b.Im;
complex c = new complex (RE, IM);
c.print ();
return c;
}
static public complex operator - (complex a, complex b) {
double RE = a.Re - b.Re;
double IM = a.Im - b.Im;
complex c = new complex (RE, IM);
c.print ();
return c;
}
static public complex operator * (complex a, complex b) {
double RE = a.Re * b.Re - a.Im * b.Im;
double IM = a.Re * b.Im + a.Im * b.Re;
complex c = new complex (RE, IM);
c.print ();
return c;
}
//显示结果
public void print () {
if (Re != 0) {
if (Im > 0)
Console.WriteLine (Re + "+" + Im + "i");
if (Im == 0)
Console.WriteLine (Re);
if (Im < 0)
Console.WriteLine (Re + "" + Im + "i");
} else {
if (Im != 0)
Console.WriteLine (Im + "i");
else
Console.WriteLine ("0");
}
}
}
class Program {
static void Main (string[] args) {
complex a = new complex (1, 1);
complex b = new complex (1, -2);
complex c = new complex (1, 0);
complex d = a + b;
complex e = a - b;
complex f = a * b;
d = a.plus (b);
e = a.Sub (b);
f = a.Mul (b);
}
} |
using Alabo.Domains.Entities;
using Alabo.Domains.Repositories.Mongo.Extension;
using Alabo.Framework.Basic.PostRoles.Dtos;
using Alabo.Framework.Core.Enums.Enum;
using Alabo.Framework.Themes.Domain.Enums;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Framework.Themes.Domain.Entities
{
/// <summary>
/// 主题模板配置
/// </summary>
[BsonIgnoreExtraElements]
[Table("Themes_Theme")]
[ClassProperty(Name = "主题模板配置")]
public class Theme : AggregateMongodbRoot<Theme>
{
/// <summary>
/// 所属站点
/// 站点为空的时候,表示系统模板
/// </summary>
[JsonConverter(typeof(ObjectIdConverter))]
[Display(Name = "所属站点")]
public ObjectId SiteId { get; set; } = ObjectId.Empty;
/// <summary>
/// 客户端类型
/// </summary>
[Display(Name = "客户端类型")]
public ClientType ClientType { get; set; }
/// <summary>
/// 模板类型
/// </summary>
[Display(Name = "模板类型")]
public ThemeType Type { get; set; }
/// <summary>
/// 模板名称
/// </summary>
[Display(Name = "模板名称")]
public string Name { get; set; }
/// <summary>
/// 简介
/// </summary>
[Display(Name = "简介")]
public string Intro { get; set; } = "心意甄选 新品新意 ,一站式解决跨境电商难题 ";
/// <summary>
/// 预览图片
/// </summary>
[Display(Name = "预览图片")]
public string Image { get; set; } = "http://ui.5ug.com/images/theme/mb01.jpg";
/// <summary>
/// 模板设置
/// </summary>
public string Setting { get; set; }
/// <summary>
/// 是否默认
/// </summary>
[Display(Name = "是否默认")]
public bool IsDefault { get; set; }
/// <summary>
/// 底部TarBar设置
/// </summary>
public string TabBarSetting { get; set; }
/// <summary>
/// 最后更新时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime UpdateTime { get; set; }
/// <summary>
/// 模板菜单
/// </summary>
public ThemeMenu Menu { get; set; }
}
/// <summary>
/// 模板菜单
/// </summary>
public class ThemeMenu
{
/// <summary>
/// 样式风格
/// </summary>
public string StyleType { get; set; }
/// <summary>
/// 菜单 数据
/// </summary>
public List<ThemeOneMenu> Menus { get; set; }
}
} |
using System.Collections.Generic;
using System.Linq;
using Hangfire;
using log4net;
using NHibernate;
using Profiling2.Domain.Contracts.Queries;
using Profiling2.Domain.Contracts.Queries.Procs;
using Profiling2.Domain.Contracts.Queries.Search;
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.DTO;
using Profiling2.Domain.Prf.Careers;
using Profiling2.Domain.Prf.Organizations;
using Profiling2.Domain.Prf.Units;
using SharpArch.NHibernate;
using SharpArch.NHibernate.Contracts.Repositories;
namespace Profiling2.Tasks
{
public class OrganizationTasks : IOrganizationTasks
{
protected readonly ILog log = LogManager.GetLogger(typeof(OrganizationTasks));
protected readonly INHibernateRepository<Organization> orgRepo;
protected readonly INHibernateRepository<Unit> unitRepo;
protected readonly INHibernateRepository<Rank> rankRepo;
protected readonly INHibernateRepository<Role> roleRepo;
protected readonly INHibernateRepository<AdminUnitImport> adminUnitImportRepo;
protected readonly INHibernateRepository<UnitHierarchy> unitHierarchyRepo;
protected readonly INHibernateRepository<UnitHierarchyType> unitHierarchyTypeRepo;
protected readonly INHibernateRepository<UnitLocation> unitLocationRepo;
protected readonly INHibernateRepository<UnitAlias> unitAliasRepo;
protected readonly INHibernateRepository<UnitOperation> unitOperationRepo;
protected readonly INHibernateRepository<Operation> operationRepo;
protected readonly INHibernateRepository<OperationAlias> operationAliasRepo;
protected readonly IOrganizationSearchQuery orgSearchQuery;
protected readonly IUnitQueries unitQueries;
protected readonly IUnitSearchQuery unitSearchQuery;
protected readonly IRankSearchQuery rankSearchQuery;
protected readonly IRoleSearchQuery roleSearchQuery;
protected readonly ILuceneTasks luceneTasks;
protected readonly IMergeStoredProcQueries mergeQueries;
public OrganizationTasks(INHibernateRepository<Organization> orgRepo,
INHibernateRepository<Unit> unitRepo,
INHibernateRepository<Rank> rankRepo,
INHibernateRepository<Role> roleRepo,
INHibernateRepository<AdminUnitImport> adminUnitImportRepo,
INHibernateRepository<UnitHierarchy> unitHierarchyRepo,
INHibernateRepository<UnitHierarchyType> unitHierarchyTypeRepo,
INHibernateRepository<UnitLocation> unitLocationRepo,
INHibernateRepository<UnitAlias> unitAliasRepo,
INHibernateRepository<UnitOperation> unitOperationRepo,
INHibernateRepository<Operation> operationRepo,
INHibernateRepository<OperationAlias> operationAliasRepo,
IOrganizationSearchQuery orgSearchQuery,
IUnitQueries unitQueries,
IUnitSearchQuery unitSearchQuery,
IRankSearchQuery rankSearchQuery,
IRoleSearchQuery roleSearchQuery,
ILuceneTasks luceneTasks,
IMergeStoredProcQueries mergeQueries)
{
this.orgRepo = orgRepo;
this.unitRepo = unitRepo;
this.rankRepo = rankRepo;
this.roleRepo = roleRepo;
this.adminUnitImportRepo = adminUnitImportRepo;
this.unitHierarchyRepo = unitHierarchyRepo;
this.unitHierarchyTypeRepo = unitHierarchyTypeRepo;
this.unitLocationRepo = unitLocationRepo;
this.unitAliasRepo = unitAliasRepo;
this.unitOperationRepo = unitOperationRepo;
this.operationRepo = operationRepo;
this.operationAliasRepo = operationAliasRepo;
this.orgSearchQuery = orgSearchQuery;
this.unitQueries = unitQueries;
this.unitSearchQuery = unitSearchQuery;
this.rankSearchQuery = rankSearchQuery;
this.roleSearchQuery = roleSearchQuery;
this.luceneTasks = luceneTasks;
this.mergeQueries = mergeQueries;
}
public Organization GetOrganization(int orgId)
{
return this.orgRepo.Get(orgId);
}
protected Organization GetOrganization(string name)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("OrgShortName", name);
IList<Organization> candidates = this.orgRepo.FindAll(criteria);
if (candidates != null && candidates.Any())
return candidates[0];
criteria.Remove("OrgShortName");
criteria.Add("OrgLongName", name);
candidates = this.orgRepo.FindAll(criteria);
if (candidates != null && candidates.Any())
return candidates[0];
return null;
}
public IList<Organization> GetAllOrganizations()
{
return this.orgRepo.GetAll();
}
public IList<Organization> GetOrganizationsByName(string term)
{
return this.orgSearchQuery.GetResults(term);
}
public Organization GetOrCreateOrganization(string name)
{
if (!string.IsNullOrEmpty(name))
{
Organization o = this.GetOrganization(name);
if (o == null)
o = new Organization()
{
OrgShortName = name,
OrgLongName = name
};
return o;
}
return null;
}
public Organization SaveOrganization(Organization o)
{
this.luceneTasks.UpdatePersons(o);
this.luceneTasks.UpdateUnits(o);
return this.orgRepo.SaveOrUpdate(o);
}
public bool DeleteOrganization(Organization o)
{
if (o != null && o.Careers.Count < 1 && o.Units.Count < 1
&& o.OrganizationResponsibilities.Count < 1
&& o.OrganizationRelationshipsAsSubject.Count < 1
&& o.OrganizationRelationshipsAsObject.Count < 1
&& o.OrganizationPhotos.Count < 1
&& o.OrganizationAliases.Count < 1)
{
this.orgRepo.Delete(o);
return true;
}
return false;
}
public Unit GetUnit(int unitId)
{
return this.unitRepo.Get(unitId);
}
private Unit GetUnit(ISession session, int unitId)
{
return this.unitQueries.GetUnit(session, unitId);
}
public Unit GetUnit(string name)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("UnitName", name);
IList<Unit> results = this.unitRepo.FindAll(criteria);
if (results != null && results.Any())
return results.First();
return null;
}
public IList<Unit> GetAllUnits()
{
return this.GetAllUnits(null);
}
public IList<Unit> GetAllUnits(ISession session)
{
return this.unitQueries.GetAllUnits(session);
}
public IList<Unit> GetUnitsByName(string term)
{
return this.unitSearchQuery.GetResults(term);
}
public bool DeleteUnit(Unit unit)
{
// we force the user to manually remove these links. others such as UnitLocations and UnitSources may be deleted by cascade.
if (unit != null && unit.Careers.Count == 0 && unit.OrganizationResponsibilities.Count == 0
&& unit.UnitHierarchies.Where(x => x.UnitHierarchyType.UnitHierarchyTypeName == UnitHierarchyType.NAME_HIERARCHY
|| x.UnitHierarchyType.UnitHierarchyTypeName == UnitHierarchyType.NAME_CHANGED_NAME_TO).Count() == 0
&& unit.UnitHierarchyChildren.Where(x => x.UnitHierarchyType.UnitHierarchyTypeName == UnitHierarchyType.NAME_HIERARCHY
|| x.UnitHierarchyType.UnitHierarchyTypeName == UnitHierarchyType.NAME_CHANGED_NAME_TO).Count() == 0
&& unit.UnitAliases.Count == 0
&& unit.UnitOperations.Count == 0
&& unit.RequestUnits.Count == 0)
{
unit.AdminUnitImports.Clear();
unit.UnitHierarchies.Clear(); // clear UnitHierarchies not checked above
unit.UnitHierarchyChildren.Clear();
this.log.Info("Deleting Unit, Id: " + unit.Id + ", Name: " + unit.UnitName);
this.luceneTasks.DeleteUnit(unit.Id);
this.unitRepo.Delete(unit);
return true;
}
return false;
}
public Unit SaveUnit(Unit unit)
{
unit = this.unitRepo.SaveOrUpdate(unit);
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(unit.Id));
return unit;
}
public void LuceneUpdateUnitQueueable(int unitId)
{
using (ISession session = NHibernateSession.GetDefaultSessionFactory().OpenSession())
{
Unit unit = this.GetUnit(session, unitId);
this.luceneTasks.UpdateUnit(unit);
this.luceneTasks.UpdatePersons(unit);
}
}
public IList<UnitDTO> GetEmptyUnits()
{
return this.unitQueries.GetEmptyUnits();
}
// Bulk-run that populates Unit.Organization using Unit.Careers.Organization
public void PopulateUnitOrganization()
{
IList<Unit> units = this.GetAllUnits().Where(x => x.Organization == null).ToList();
foreach (Unit u in units)
{
IList<Organization> orgs = u.Careers.Where(x => x.Organization != null).Select(x => x.Organization).Distinct().ToList();
// set Unit.Organization if all its career.Organizations are the same
if (orgs.Count == 1)
{
u.Organization = orgs.First();
this.unitRepo.SaveOrUpdate(u);
}
}
}
public UnitHierarchy GetUnitHierarchy(int id)
{
return this.unitHierarchyRepo.Get(id);
}
public UnitHierarchy GetUnitHierarchy(int unitId, int parentId)
{
Unit unit = this.GetUnit(unitId);
Unit parentUnit = this.GetUnit(parentId);
if (unit != null && parentUnit != null)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Unit", unit);
criteria.Add("ParentUnit", parentUnit);
IList<UnitHierarchy> list = this.unitHierarchyRepo.FindAll(criteria);
if (list != null && list.Any())
return list[0];
}
return null;
}
public UnitHierarchy SaveUnitHierarchy(UnitHierarchy uh)
{
if (uh.ParentUnit != null)
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(uh.ParentUnit.Id));
if (uh.Unit != null)
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(uh.Unit.Id));
return this.unitHierarchyRepo.SaveOrUpdate(uh);
}
public void DeleteUnitHierarchy(UnitHierarchy uh)
{
if (uh != null)
{
if (uh.ParentUnit != null)
{
uh.ParentUnit.RemoveUnitHierarchy(uh);
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(uh.ParentUnit.Id));
}
if (uh.Unit != null)
{
uh.Unit.RemoveUnitHierarchy(uh);
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(uh.Unit.Id));
}
this.unitHierarchyRepo.Delete(uh);
}
}
public UnitHierarchyType GetUnitHierarchyType(int id)
{
return this.unitHierarchyTypeRepo.Get(id);
}
public UnitHierarchyType GetUnitHierarchyType(string name)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("UnitHierarchyTypeName", name);
return this.unitHierarchyTypeRepo.FindOne(criteria);
}
public IList<UnitHierarchyType> GetUnitHierarchyTypes()
{
return this.unitHierarchyTypeRepo.GetAll();
}
public UnitLocation GetUnitLocation(int id)
{
return this.unitLocationRepo.Get(id);
}
public UnitLocation SaveUnitLocation(UnitLocation ul)
{
return this.unitLocationRepo.SaveOrUpdate(ul);
}
public void DeleteUnitLocation(UnitLocation ul)
{
if (ul != null)
this.unitLocationRepo.Delete(ul);
}
public UnitAlias GetUnitAlias(int id)
{
return this.unitAliasRepo.Get(id);
}
public UnitAlias SaveUnitAlias(UnitAlias ua)
{
ua = this.unitAliasRepo.SaveOrUpdate(ua);
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(ua.Unit.Id));
return ua;
}
public void DeleteUnitAlias(UnitAlias ua)
{
if (ua != null)
{
this.unitAliasRepo.Delete(ua);
BackgroundJob.Enqueue<IOrganizationTasks>(x => x.LuceneUpdateUnitQueueable(ua.Unit.Id));
}
}
public Rank GetRank(int id)
{
return this.rankRepo.Get(id);
}
public Rank GetRank(string name)
{
if (!string.IsNullOrEmpty(name))
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("RankName", name);
return this.rankRepo.FindOne(criteria);
}
return null;
}
public IList<Rank> GetAllRanks()
{
return this.rankRepo.GetAll().OrderBy(x => x.RankName).ToList<Rank>();
}
public IList<Rank> GetRanksByName(string term)
{
return this.rankSearchQuery.GetResults(term);
}
public Rank GetOrCreateRank(string name)
{
if (!string.IsNullOrEmpty(name))
{
Rank r = this.GetRank(name);
if (r == null)
r = new Rank()
{
RankName = name
};
return r;
}
return null;
}
public Rank SaveRank(Rank rank)
{
this.luceneTasks.UpdatePersons(rank);
return this.rankRepo.SaveOrUpdate(rank);
}
public bool DeleteRank(Rank rank)
{
if (rank != null && rank.Careers.Count < 1)
{
this.rankRepo.Delete(rank);
return true;
}
return false;
}
public void MigrateSomeFunctionsToRanks()
{
Role[] roles = new Role[]
{
this.roleRepo.Get(4), // Capitaine de Frégate
this.roleRepo.Get(5), // Capitaine de Corvette
this.roleRepo.Get(7) // Lieutenant de Vaisseau
};
Rank[] ranks = new Rank[]
{
this.rankRepo.Get(116), // Capitaine de Frégate/Lieutenant Colonel
this.rankRepo.Get(122), // Capitaine de Corvette/Major
this.rankRepo.Get(118) // Lieutenant de Vaisseau/Capitaine
};
foreach (int i in new int[] { 0, 1, 2 })
this.MoveRoleToRank(roles[i], ranks[i]);
}
private void MoveRoleToRank(Role role, Rank rank)
{
if (role != null)
{
foreach (Career c in role.Careers.Where(x => x.Rank == null))
{
c.Role = null;
c.Rank = rank;
}
}
}
public Role GetRole(int id)
{
return this.roleRepo.Get(id);
}
public Role GetRole(string name)
{
if (!string.IsNullOrEmpty(name))
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("RoleName", name);
return this.roleRepo.FindOne(criteria);
}
return null;
}
public IList<Role> GetAllRoles()
{
return this.roleRepo.GetAll().OrderBy(x => x.RoleName).ToList<Role>();
}
public IList<Role> GetRolesByName(string term)
{
return this.roleSearchQuery.GetResults(term);
}
public Role SaveRole(Role role)
{
this.luceneTasks.UpdatePersons(role);
return this.roleRepo.SaveOrUpdate(role);
}
public bool DeleteRole(Role role)
{
if (role != null && role.Careers.Count < 1)
{
this.roleRepo.Delete(role);
return true;
}
return false;
}
protected void SaveAdminUnitImport(AdminUnitImport i)
{
i.Unit.AddAdminUnitImport(i);
this.adminUnitImportRepo.SaveOrUpdate(i);
}
protected void DeleteAdminUnitImport(AdminUnitImport i)
{
i.Unit.RemoveAdminUnitImport(i);
this.adminUnitImportRepo.Delete(i);
}
public int MergeUnits(int toKeepUnitId, int toDeleteUnitId, string userId, bool isProfilingChange)
{
int result = this.mergeQueries.MergeUnits(toKeepUnitId, toDeleteUnitId, userId, isProfilingChange);
if (result == 1)
{
// get Unit after merge in order to have updated attributes
Unit toKeep = this.GetUnit(toKeepUnitId);
this.luceneTasks.UpdateUnit(toKeep);
this.luceneTasks.DeleteUnit(toDeleteUnitId);
}
return result;
}
public UnitOperation GetUnitOperation(int id)
{
return this.unitOperationRepo.Get(id);
}
public IList<UnitOperation> GetUnitOperations(Unit unit, Operation op)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Unit", unit);
criteria.Add("Operation", op);
return this.unitOperationRepo.FindAll(criteria);
}
public UnitOperation SaveUnitOperation(UnitOperation uo)
{
return this.unitOperationRepo.SaveOrUpdate(uo);
}
public void DeleteUnitOperation(UnitOperation uo)
{
this.unitOperationRepo.Delete(uo);
}
public Operation GetOperation(int id)
{
return this.operationRepo.Get(id);
}
public Operation GetOperation(string name)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Name", name);
return this.operationRepo.FindOne(criteria);
}
public IList<Operation> GetOperationsLike(string term)
{
return this.unitSearchQuery.GetOperationsLike(term);
}
public IList<Operation> GetAllOperations()
{
return this.operationRepo.GetAll().Where(x => !x.Archive).ToList();
}
public Operation SaveOperation(Operation op)
{
//foreach (Unit u in op.Units)
// u.AddOperation(op);
return this.operationRepo.SaveOrUpdate(op);
}
public bool DeleteOperation(Operation op)
{
if (op != null)
{
if (!op.UnitOperations.Any())
{
this.operationRepo.Delete(op);
return true;
}
}
return false;
}
public OperationAlias GetOperationAlias(int id)
{
return this.operationAliasRepo.Get(id);
}
public OperationAlias SaveOperationAlias(OperationAlias oa)
{
return this.operationAliasRepo.SaveOrUpdate(oa);
}
public void DeleteOperationAlias(OperationAlias a)
{
this.operationAliasRepo.Delete(a);
}
}
}
|
using KartObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartSystem
{
public class GoodMovementRecord:SimpleNamedEntity
{
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Запись аналитики о товародвижении"; }
}
public double WasQuant
{
get;
set;
}
public double WasCostPrice
{
get;
set;
}
public double WasSalePrice
{
get;
set;
}
public double WasSaleSum
{
get;
set;
}
public double ReturnSupplierQuant
{
get;
set;
}
public double ReturnSupplierCostPrice
{
get;
set;
}
public double ReturnSupplierSalePrice
{
get;
set;
}
[DBIgnoreReadParam]
public double ReturnSupplierSaleSum
{
get
{
return ReturnSupplierQuant * ReturnSupplierSalePrice;
}
}
public double IncomeQuant
{
get;
set;
}
public double IncomeCostPrice
{
get;
set;
}
public double IncomeSalePrice
{
get;
set;
}
[DBIgnoreReadParam]
public double IncomeSaleSum
{
get
{
return IncomeQuant * IncomeSalePrice;
}
}
public double SaleQuant
{
get;
set;
}
public double SaleCostPrice
{
get;
set;
}
public double SaleSalePrice
{
get;
set;
}
public double SaleDiscount
{
get;
set;
}
[DBIgnoreReadParam]
public double SaleSaleSum
{
get
{
return SaleQuant * SaleSalePrice;
}
}
public double ReturnCustomerQuant
{
get;
set;
}
public double ReturnCustomerCostPrice
{
get;
set;
}
public double ReturnCustomerSalePrice
{
get;
set;
}
[DBIgnoreReadParam]
public double ReturnCustomerSaleSum
{
get
{
return ReturnCustomerQuant * ReturnCustomerSalePrice;
}
}
public double SurplusQuant
{
get;
set;
}
public double SurplusCostPrice
{
get;
set;
}
public double SurplusSalePrice
{
get;
set;
}
public double ExpenseMovementQuant
{
get;
set;
}
public double ExpenseMovementSalePrice
{
get;
set;
}
public double ExpenseMovementCostPrice
{
get;
set;
}
public double IncomeMovementQuant
{
get;
set;
}
public double IncomeMovementSalePrice
{
get;
set;
}
public double IncomeMovementCostPrice
{
get;
set;
}
[DBIgnoreReadParam]
public double SurplusSaleSum
{
get
{
return SurplusQuant * SurplusSalePrice;
}
}
public double CancellationQuant
{
get;
set;
}
public double CancellationCostPrice
{
get;
set;
}
public double CancellationSalePrice
{
get;
set;
}
[DBIgnoreReadParam]
public double CancellationSaleSum
{
get
{
return CancellationQuant * CancellationSalePrice;
}
}
public double RevaluationSum
{
get;
set;
}
public double StayQuant
{
get;
set;
}
public double StayCostPrice
{
get;
set;
}
public double StaySalePrice
{
get;
set;
}
public double WasCostSum
{
get;
set;
}
public double StayCostSum
{
get;
set;
}
/// <summary>
/// Погрешность розничной реализации
/// </summary>
public double RetailSaleFault
{
get;
set;
}
public double StaySaleSum
{
get;
set;
}
[DBIgnoreReadParam]
public double DiffQuant
{
get
{
return Math.Round(WasQuant + IncomeQuant - ReturnSupplierQuant + ReturnCustomerQuant - SaleQuant-StayQuant+SurplusQuant-CancellationQuant+IncomeMovementQuant-ExpenseMovementQuant,3);
}
}
[DBIgnoreReadParam]
public double DiffCostSum
{
get
{
return Math.Round(WasCostSum + IncomeQuant * IncomeCostPrice - ReturnSupplierQuant * ReturnSupplierCostPrice + ReturnCustomerQuant * ReturnCustomerCostPrice - SaleQuant * SaleCostPrice - StayCostSum + SurplusQuant * SurplusCostPrice - CancellationQuant * CancellationCostPrice+IncomeMovementQuant*IncomeMovementCostPrice-ExpenseMovementQuant*ExpenseMovementCostPrice , 3);
}
}
[DBIgnoreReadParam]
public double DiffSaleSum
{
get
{
return Math.Round(WasSaleSum + IncomeQuant * IncomeSalePrice - ReturnSupplierQuant * ReturnSupplierSalePrice + ReturnCustomerQuant * ReturnCustomerSalePrice - SaleQuant * SaleSalePrice - StaySaleSum + RevaluationSum +SurplusQuant * SurplusSalePrice - CancellationQuant * CancellationSalePrice +RetailSaleFault+RevaluationFault+IncomeMovementQuant*IncomeMovementSalePrice-ExpenseMovementQuant*ExpenseMovementSalePrice, 3);
}
}
[DBIgnoreReadParam]
public double Profit
{
get
{
return Math.Round(SaleQuant * (SaleSalePrice - SaleCostPrice), 2);
}
}
/*
[DBIgnoreReadParam]
public double NegativePartCostLoss
{
get
{
double result = 0;
if (StayQuant==0)
result = Math.Round(WasQuant * WasCostPrice + IncomeQuant * IncomeCostPrice - ReturnSupplierQuant * ReturnSupplierCostPrice + ReturnCustomerQuant * ReturnCustomerCostPrice - SaleQuant * SaleCostPrice - StayQuant * StayCostPrice + SurplusQuant * SurplusCostPrice - CancellationQuant * CancellationCostPrice, 2);
return result;
}
}
[DBIgnoreReadParam]
public double NegativePartSaleLoss
{
get
{
double result = 0;
if (StayQuant == 0)
result = Math.Round(WasQuant * WasSalePrice + IncomeQuant * IncomeSalePrice - ReturnSupplierQuant * ReturnSupplierSalePrice + ReturnCustomerQuant * ReturnCustomerSalePrice - SaleQuant * SaleSalePrice - StayQuant * StaySalePrice + RevaluationSum + SurplusQuant * SurplusSalePrice - CancellationQuant * CancellationSalePrice + RetailSaleFault + RevaluationFault, 2);
return result;
}
}
* */
/// <summary>
/// Ошибка переоценки
/// </summary>
public double RevaluationFault
{
get;
set;
}
public double StayRetailAccFault
{
get;
set;
}
public double StayRevaluationFault
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TournamentBot.BL.Common;
namespace TournamentBot.SimulatedClient
{
class Program
{
static void Main(string[] args)
{
string input = "";
Console.WriteLine("Welcome to TournamentBot Simulator!");
Console.WriteLine("Please enter your command, help for a list, or quit to exit");
while (input != "quit")
{
// get command from user:
input = Console.ReadLine();
var inputs = input.Split(' ');
List<string> arguments = new List<string>();
for (var x = 1; x < inputs.Length; x++)
{
arguments.Add(inputs[x]);
}
var response = Utils.ParseCommand(inputs.First(), arguments);
Console.WriteLine(response + "\n\n");
}
Console.WriteLine("Goodbye!");
Console.ReadKey();
}
}
}
|
namespace CustomAction.SaveAction
{
using Sitecore.Globalization;
using Sitecore.Publishing;
using Sitecore.SecurityModel;
using Sitecore.Data;
using Sitecore.Form.Submit;
/// <summary>
/// This class is meant to demonstrate how to create a custom action attached to the Save Action set of a WFFM form
/// </summary>
public class CustomAction : ISaveAction
{
/// <summary>
/// Executes the specified formid.
/// </summary>
/// <param name="formid">The formid.</param>
/// <param name="fields">The fields.</param>
/// <param name="data">The data.</param>
public void Execute(Sitecore.Data.ID formid, Sitecore.Form.Core.Client.Data.Submit.AdaptedResultList fields,
params object[] data)
{
var master = Sitecore.Configuration.Factory.GetDatabase("master");
var producttwo = master.GetItem(new ID("{2D9304C0-9CA7-484A-BD45-4AB664AFAFE3}"));
using (new SecurityDisabler())
{
producttwo.Editing.BeginEdit();
producttwo.Fields["Price"].Value = "$20.00";
producttwo.Editing.EndEdit();
}
var web = new[] {Sitecore.Configuration.Factory.GetDatabase("web")};
var english = new[] {Language.Current};
PublishManager.PublishItem(producttwo, web, english, false, false);
}
}
} |
using System;
using System.Collections.Generic;
namespace ApplicationUpdater
{
public class IISAplicationUpdater
{
public IUpdateProcess UpdateProcess { get; private set; }
public IISAplicationUpdater(IUpdateProcess selgrosApplicationUpdateStrategy)
{
UpdateProcess = selgrosApplicationUpdateStrategy;
}
private void ExecuteProcess(IEnumerable<Action<UpdateModel>> actions, UpdateModel updateModel)
{
foreach (var action in actions)
{
action.Invoke(updateModel);
Console.WriteLine();
}
}
public void Update(UpdateModel updateModel)
{
ExecuteProcess(UpdateProcess.GetProcess(updateModel), updateModel);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Student.Mangmnet.Models
{
public class StudentModels
{
public string StudentId { get; set; }
[Required(ErrorMessage = "Student Name must be not null")]
public string Name { get; set; }
[Required(ErrorMessage = "Subject Name must be not null")]
public int Age { get; set; }
public List<SubjectCheckModel> Subjects { get; set; }
}
} |
namespace BootcampTwitterKata.Messages
{
public class UnLikeTweet
{
public UnLikeTweet(int id)
{
this.Id = id;
}
public int Id { get; set; }
}
} |
using BradescoPGP.Common;
using BradescoPGP.Common.Logging;
using BradescoPGP.Repositorio;
using BradescoPGP.Web.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace BradescoPGP.Web.Services
{
public class AgendaService
{
public AgendaViewModel ObterAgendaCompleta(string matricula, string perfil)
{
var vencimentos = ObterVencimentosAgenda(matricula);
var pipes = ObterPipeLinesAgenda(matricula);
var teds = ObterTedsAgenda(matricula);
var niver = ObterAniversariantesAgenda(matricula, perfil);
var eventos = ObterEventosAgenda(matricula);
return AgendaViewModel.Mapear(vencimentos, pipes, teds, niver, eventos);
}
public List<Vencimento> ObterVencimentosAgenda(string matricula)
{
using (var context = new PGPEntities())
{
var minDate = DateTime.Now.AddDays(-90).Date;
var dataAtual = DateTime.Now.Date;
int[] statusValidos = new int[] { 5, 6, 7 };
var vencimentosDia = context.Vencimento
.Join(context.Encarteiramento,
venc => new { agencia = venc.Cod_Agencia.ToString(), conta = venc.Cod_Conta_Corrente.ToString() },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(venc, enc) => new { venc, enc })
.Where(v => v.enc.Matricula == matricula && v.venc.StatusId.HasValue && statusValidos.Contains(v.venc.StatusId.Value) &&
v.venc.Dt_Vecto_Contratado >= minDate && v.venc.Dt_Vecto_Contratado <= dataAtual )
.Select(s => s.venc).ToList();
return vencimentosDia;
}
}
public List<Pipeline> ObterPipeLinesAgenda(string matricula)
{
var statusValidos = new int[] { 3, 4 };
using (var context = new PGPEntities())
{
var minDate= DateTime.Now.Date.AddMonths(-12);
var pipelines = context.Pipeline
.Where(p => p.MatriculaConsultor == matricula && statusValidos.Contains(p.StatusId) &&
(p.DataProrrogada >= minDate || p.DataPrevista >= minDate ))
.ToList();
return pipelines;
}
}
public List<TED> ObterTedsAgenda(string matricula)
{
using (var context = new PGPEntities())
{
var statusValidos = context.Status.Where(s => s.Evento.Contains("TED") &&
!s.Descricao.Contains("Aplicado") && !s.Descricao.Contains("Finalizado")).Select(s => s.Id).ToList();
var dados = new List<TED>();
var ted = context.TED.Include("Motivo").Include("Status").Where(t => t.Area == "PGP");
var dataAtual = DateTime.Now.Date;
var minData = new DateTime(dataAtual.Year, dataAtual.Month, 1).AddMonths(-1);
var maxData = new DateTime(dataAtual.Year, dataAtual.Month, DateTime.DaysInMonth(dataAtual.Year, dataAtual.Month));
dados = ted.Where(t =>
t.MatriculaConsultor == matricula &&
statusValidos.Contains(t.StatusId) &&
DbFunctions.TruncateTime(t.Data) >= minData && DbFunctions.TruncateTime(t.Data) <= maxData).ToList();
return dados;
}
}
public List<AniversarianteViewModel> ObterAniversariantesAgenda(string matricula, string perfil)
{
if (perfil == NivelAcesso.Especialista.ToString())
{
using (var db = new PGPEntities())
{
var data = DateTime.Now.Date;
var nivers = db.Aniversarios.Join(db.Encarteiramento,
niver => new { agencia = niver.Agencia.ToString(), conta = niver.Conta.ToString() },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(niver, enc) => new { niver, enc.Matricula, enc.Agencia, enc.Conta })
.Join(db.Cockpit,
res => new { agencia = res.Agencia, conta = res.Conta },
cokc => new { agencia = cokc.CodigoAgencia.ToString(), conta = cokc.Conta.ToString() },
(resp, cock) => new { resp, cock.CodigoAgencia, cock.Conta, cock.NomeCliente })
.Where(r => r.resp.Matricula == matricula &&
r.resp.niver.DataNascimento.Day == data.Day && r.resp.niver.DataNascimento.Month == data.Month)
.GroupBy(g => new { agencia = g.CodigoAgencia, conta = g.Conta })
.Select(s => new AniversarianteViewModel
{
Agencia = s.FirstOrDefault().CodigoAgencia,
Conta = s.FirstOrDefault().Conta,
Nome = s.FirstOrDefault().NomeCliente,
DataAniversario = s.FirstOrDefault().resp.niver.DataNascimento
}).ToList();
return nivers;
}
}
return new List<AniversarianteViewModel>();
}
public List<Evento> ObterEventosAgenda(string matricula)
{
using (var db = new PGPEntities())
{
var dataAtual = DateTime.Now.Date;
var minDate = DateTime.Now.Date.AddDays(-1);
var maxDate = new DateTime(dataAtual.Year, dataAtual.Month, DateTime.DaysInMonth(dataAtual.Year, dataAtual.Month));
var eventos = db.Evento.Where(e => e.MatriculaConsultor == matricula &&
//e.DataHoraInicio.Day == dateAtual.Day && e.DataHoraInicio.Month == dateAtual.Month && e.DataHoraInicio.Year == dateAtual.Year ||
e.DataHoraInicio >= minDate && e.DataHoraInicio <= maxDate ).ToList();
return eventos;
}
}
public Evento NovoEvento(Evento evento)
{
using(var db = new PGPEntities())
{
if(evento != null)
{
try
{
db.Evento.Add(evento);
db.SaveChanges();
return evento;
}
catch (Exception e)
{
Log.Error("Erro ao criar um novo evento", e);
return new Evento();
}
}
else
{
return new Evento();
}
}
}
public bool ExcluirEvento(int id)
{
using (var db = new PGPEntities())
{
var evento = db.Evento.First(e => e.Id == id);
db.Evento.Remove(evento);
try
{
db.SaveChanges();
return true;
}
catch (Exception e)
{
Log.Error("Erro ao deletar evento " + e);
return false;
throw;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CEMAPI.Models
{
public class TransitionToCEMMeasureInfoDTO
{
public int? OfferId { get; set; }
public int MeasureId { get; set; }
public string MeasureName { get; set; }
public bool? IsMeasureChecked { get; set; }
public string SelectionType { get; set; }
// public List<SingleSelectionCEMMeasureInfoDTO> SingleSelectionCEMMeasureInfo=new List<SingleSelectionCEMMeasureInfoDTO>();
}
public class SingleSelectionCEMMeasureInfoDTO
{
public int? OfferId { get; set; }
public int MeasureId { get; set; }
public string MeasureName { get; set; }
public bool? IsMeasureChecked { get; set; }
}
} |
using eMAM.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace eMAM.UI.Models
{
public class HomeViewModel
{
public ICollection<EmailViewModel> NotReviewed { get; set; }
public ICollection<EmailViewModel> New { get; set; }
public ICollection<EmailViewModel> Open { get; set; }
public ICollection<EmailViewModel> Closed { get; set; }
public bool UserIsManager { get; set; }
}
}
|
/*
Dataphor
© Copyright 2000-2008 Alphora
This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt
*/
//#define USECLEANUPNODES // Part of cleanup processing, currently disabled because cleanup processing is done with InstructionNodeBase.CleanupOperand
using System;
using System.Reflection;
using System.Reflection.Emit;
using Alphora.Dataphor.DAE.Language;
using Alphora.Dataphor.DAE.Language.D4;
using Alphora.Dataphor.DAE.Compiling;
using Alphora.Dataphor.DAE.Compiling.Visitors;
using Alphora.Dataphor.DAE.Server;
using Alphora.Dataphor.DAE.Streams;
using Alphora.Dataphor.DAE.Runtime;
using Alphora.Dataphor.DAE.Runtime.Data;
using Schema = Alphora.Dataphor.DAE.Schema;
namespace Alphora.Dataphor.DAE.Runtime.Instructions
{
/*
InstructionNode prepares the AArguments set for use in virtual resolution.
Passing an argument by value (in or no modifier) is a copy. For local table
variables this is accomplished as it is for all other variable types, by
executing the argument node. For non-local table variables, this is accomplished
by converting the result to a local table variable for passing into the operator.
Passing an argument by reference (var, out or const) is not a copy. For local
table variables this is accomplished as it is for all other variable types, by
referencing the object from the current stack frame in the argument set.
Non-local table variables cannot be passed by reference.
*/
public abstract class InstructionNodeBase : PlanNode
{
// constructor
public InstructionNodeBase() : base()
{
// InstructionNodes are by default not breakable (because for 99% of instructions this would be the
// equivalent of breaking into the multiplication instruction in the processor, for example.
//IsBreakable = true;
ExpectsTableValues = true;
}
// Operator
// The operator this node is implementing
[Reference]
private Schema.Operator _operator;
public Schema.Operator Operator
{
get { return _operator; }
set { _operator = value; }
}
protected override void InternalClone(PlanNode newNode)
{
base.InternalClone(newNode);
var newInstructionNode = (InstructionNode)newNode;
newInstructionNode.Operator = _operator;
}
public override Statement EmitStatement(EmitMode mode)
{
if (_operator.IsBuiltin && (NodeCount > 0) && (NodeCount <= 2))
{
Expression expression;
if (Nodes.Count == 1)
expression =
new UnaryExpression
(
_operator.OperatorName,
_operator.Operands[0].Modifier == Modifier.Var ?
new ParameterExpression(Modifier.Var, (Expression)Nodes[0].EmitStatement(mode)) :
(Expression)Nodes[0].EmitStatement(mode)
);
else
expression =
new BinaryExpression
(
_operator.Operands[0].Modifier == Modifier.Var ?
new ParameterExpression(Modifier.Var, (Expression)Nodes[0].EmitStatement(mode)) :
(Expression)Nodes[0].EmitStatement(mode),
_operator.OperatorName,
_operator.Operands[1].Modifier == Modifier.Var ?
new ParameterExpression(Modifier.Var, (Expression)Nodes[1].EmitStatement(mode)) :
(Expression)Nodes[1].EmitStatement(mode)
);
expression.Modifiers = Modifiers;
return expression;
}
else
{
CallExpression expression = new CallExpression();
expression.Identifier = Schema.Object.EnsureRooted(_operator.OperatorName);
for (int index = 0; index < NodeCount; index++)
if (_operator.Operands[index].Modifier == Modifier.Var)
expression.Expressions.Add(new ParameterExpression(Modifier.Var, (Expression)Nodes[index].EmitStatement(mode)));
else
expression.Expressions.Add((Expression)Nodes[index].EmitStatement(mode));
expression.Modifiers = Modifiers;
return expression;
}
}
#if USECLEANUPNODES
protected PlanNodes FCleanupNodes;
public PlanNodes CleanupNodes { get { return FCleanupNodes; } }
#endif
public override void DetermineCharacteristics(Plan plan)
{
if (Modifiers != null)
{
IsLiteral = Convert.ToBoolean(LanguageModifiers.GetModifier(Modifiers, "IsLiteral", Operator.IsLiteral.ToString()));
IsFunctional = Convert.ToBoolean(LanguageModifiers.GetModifier(Modifiers, "IsFunctional", Operator.IsFunctional.ToString()));
IsDeterministic = Convert.ToBoolean(LanguageModifiers.GetModifier(Modifiers, "IsDeterministic", Operator.IsDeterministic.ToString()));
IsRepeatable = Convert.ToBoolean(LanguageModifiers.GetModifier(Modifiers, "IsRepeatable", Operator.IsRepeatable.ToString()));
IsNilable = Convert.ToBoolean(LanguageModifiers.GetModifier(Modifiers, "IsNilable", Operator.IsNilable.ToString()));
}
else
{
IsLiteral = Operator.IsLiteral;
IsFunctional = Operator.IsFunctional;
IsDeterministic = Operator.IsDeterministic;
IsRepeatable = Operator.IsRepeatable;
IsNilable = Operator.IsNilable;
}
for (int index = 0; index < Operator.Operands.Count; index++)
{
IsLiteral = IsLiteral && Nodes[index].IsLiteral;
IsFunctional = IsFunctional && Nodes[index].IsFunctional;
IsDeterministic = IsDeterministic && Nodes[index].IsDeterministic;
IsRepeatable = IsRepeatable && Nodes[index].IsRepeatable;
IsNilable = IsNilable || Nodes[index].IsNilable;
}
IsOrderPreserving = Convert.ToBoolean(MetaData.GetTag(Operator.MetaData, "DAE.IsOrderPreserving", IsOrderPreserving.ToString()));
}
public override void DetermineDataType(Plan plan)
{
DetermineModifiers(plan);
if (Operator != null)
{
_dataType = Operator.ReturnDataType;
for (int index = 0; index < Operator.Operands.Count; index++)
{
switch (Operator.Operands[index].Modifier)
{
case Modifier.In : break;
case Modifier.Var :
if (Nodes[index] is ParameterNode)
Nodes[index] = Nodes[index].Nodes[0];
if (!(Nodes[index] is StackReferenceNode) || plan.Symbols[((StackReferenceNode)Nodes[index]).Location].IsConstant)
throw new CompilerException(CompilerException.Codes.ConstantObjectCannotBePassedByReference, plan.CurrentStatement(), Operator.Operands[index].Name);
((StackReferenceNode)Nodes[index]).ByReference = true;
break;
case Modifier.Const :
if (Nodes[index] is ParameterNode)
Nodes[index] = Nodes[index].Nodes[0];
if (Nodes[index] is StackReferenceNode)
((StackReferenceNode)Nodes[index]).ByReference = true;
else if (Nodes[index] is StackColumnReferenceNode)
((StackColumnReferenceNode)Nodes[index]).ByReference = true;
break;
}
}
}
}
protected override void InternalBindingTraversal(Plan plan, PlanNodeVisitor visitor)
{
base.InternalBindingTraversal(plan, visitor);
#if USECLEANUPNODES
if (CleanupNodes != null)
foreach (PlanNode node in CleanupNodes)
node.BindingTraversal(APlan, visitor);
#endif
}
public override void BindToProcess(Plan plan)
{
if (Operator != null)
{
plan.CheckRight(Operator.GetRight(Schema.RightNames.Execute));
plan.EnsureApplicationTransactionOperator(Operator);
}
base.BindToProcess(plan);
}
// TODO: This should be compiled and added as cleanup nodes
// TODO: Handle var arguments for more than just stack references
protected void CleanupOperand(Program program, Schema.SignatureElement signatureElement, PlanNode argumentNode, object argumentValue)
{
switch (signatureElement.Modifier)
{
case Modifier.In :
DataValue.DisposeValue(program.ValueManager, argumentValue);
break;
case Modifier.Var :
if (argumentNode.DataType is Schema.ScalarType)
argumentValue = ValueUtility.ValidateValue(program, (Schema.ScalarType)argumentNode.DataType, argumentValue, _operator);
program.Stack.Poke(((StackReferenceNode)argumentNode).Location, argumentValue);
break;
}
}
public override string Category
{
get { return "Instruction"; }
}
}
public abstract class NilaryInstructionNode : InstructionNodeBase
{
public abstract object NilaryInternalExecute(Program program);
public override object InternalExecute(Program program)
{
#if USECLEANUPNODES
try
{
#endif
if (IsBreakable)
{
program.Stack.PushWindow(0, this, Operator.Locator);
try
{
return NilaryInternalExecute(program);
}
finally
{
program.Stack.PopWindow();
}
}
else
{
return NilaryInternalExecute(program);
}
#if USECLEANUPNODES
}
finally
{
if (FCleanupNodes != null)
for (int index = 0; index < FCleanupNodes.Count; index++)
FCleanupNodes[index].Execute(AProgram);
}
#endif
}
}
public abstract class UnaryInstructionNode : InstructionNodeBase
{
public abstract object InternalExecute(Program program, object argument1);
public override object InternalExecute(Program program)
{
object argument = Nodes[0].Execute(program);
try
{
if (IsBreakable)
{
program.Stack.PushWindow(0, this, Operator.Locator);
try
{
return InternalExecute(program, argument);
}
finally
{
program.Stack.PopWindow();
}
}
else
{
return InternalExecute(program, argument);
}
}
finally
{
if (Operator != null)
CleanupOperand(program, Operator.Signature[0], Nodes[0], argument);
#if USECLEANUPNODES
if (FCleanupNodes != null)
for (int index = 0; index < FCleanupNodes.Count; index++)
FCleanupNodes[index].Execute(AProgram);
#endif
}
}
}
public abstract class BinaryInstructionNode : InstructionNodeBase
{
public abstract object InternalExecute(Program program, object argument1, object argument2);
public override object InternalExecute(Program program)
{
object argument1 = Nodes[0].Execute(program);
object argument2 = Nodes[1].Execute(program);
try
{
if (IsBreakable)
{
program.Stack.PushWindow(0, this, Operator.Locator);
try
{
return InternalExecute(program, argument1, argument2);
}
finally
{
program.Stack.PopWindow();
}
}
else
{
return InternalExecute(program, argument1, argument2);
}
}
finally
{
if (Operator != null)
{
CleanupOperand(program, Operator.Signature[0], Nodes[0], argument1);
CleanupOperand(program, Operator.Signature[1], Nodes[1], argument2);
}
#if USECLEANUPNODES
if (FCleanupNodes != null)
for (int index = 0; index < FCleanupNodes.Count; index++)
FCleanupNodes[index].Execute(AProgram);
#endif
}
}
}
public abstract class TernaryInstructionNode : InstructionNodeBase
{
public abstract object InternalExecute(Program program, object argument1, object argument2, object argument3);
public override object InternalExecute(Program program)
{
object argument1 = Nodes[0].Execute(program);
object argument2 = Nodes[1].Execute(program);
object argument3 = Nodes[2].Execute(program);
try
{
if (IsBreakable)
{
program.Stack.PushWindow(0, this, Operator.Locator);
try
{
return InternalExecute(program, argument1, argument2, argument3);
}
finally
{
program.Stack.PopWindow();
}
}
else
{
return InternalExecute(program, argument1, argument2, argument3);
}
}
finally
{
if (Operator != null)
{
CleanupOperand(program, Operator.Signature[0], Nodes[0], argument1);
CleanupOperand(program, Operator.Signature[1], Nodes[1], argument2);
CleanupOperand(program, Operator.Signature[2], Nodes[2], argument3);
}
#if USECLEANUPNODES
if (FCleanupNodes != null)
for (int index = 0; index < FCleanupNodes.Count; index++)
FCleanupNodes[index].Execute(AProgram);
#endif
}
}
}
public abstract class InstructionNode : InstructionNodeBase
{
public abstract object InternalExecute(Program program, object[] arguments);
public override object InternalExecute(Program program)
{
object[] arguments = new object[NodeCount];
for (int index = 0; index < arguments.Length; index++)
arguments[index] = Nodes[index].Execute(program);
try
{
if (IsBreakable)
{
program.Stack.PushWindow(0, this, Operator.Locator);
try
{
return InternalExecute(program, arguments);
}
finally
{
program.Stack.PopWindow();
}
}
else
{
return InternalExecute(program, arguments);
}
}
finally
{
// TODO: Compile the dispose calls and var argument assignment calls
if (Operator != null)
for (int index = 0; index < Operator.Operands.Count; index++)
CleanupOperand(program, Operator.Signature[index], Nodes[index], arguments[index]);
#if USECLEANUPNODES
if (FCleanupNodes != null)
for (int index = 0; index < FCleanupNodes.Count; index++)
FCleanupNodes[index].Execute(AProgram);
#endif
}
}
}
}
|
namespace ODL.DomainModel.Adress
{
public class Gatuadress
{
public Gatuadress()
{
}
public Gatuadress(string adressRad1, string postnummer, string stad, string land)
{
AdressRad1 = adressRad1;
Postnummer = postnummer;
Stad = stad;
Land = land;
}
public int AdressId { get; private set; }
public string AdressRad1 { get; internal set; }
public string AdressRad2 { get; internal set; }
public string AdressRad3 { get; internal set; }
public string AdressRad4 { get; internal set; }
public string AdressRad5 { get; internal set; }
public string Postnummer { get; internal set; }
public string Stad { get; internal set; }
public string Land { get; internal set; }
public virtual Adress Adress { get;}
}
}
|
using System;
using System.Collections.Generic;
using Engine;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace TanksUnderAttack3D
{
public abstract class EngineGame : Game
{
public Scene CurrentScene;
protected GraphicsDeviceManager graphics;
public EngineGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
public abstract void Begin();
protected override void Initialize()
{
base.Initialize();
graphics.PreferredBackBufferHeight = 800;
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferMultiSampling = true;
graphics.ApplyChanges();
IsFixedTimeStep = false;
Content.RootDirectory = "Content";
GameState.GraphicsDevice = graphics.GraphicsDevice;
GameState.Font = Content.Load<SpriteFont>("Fonts/StencilSmall");
GameState.CurrentContentManager = Content;
GameState.DefaultEffect = Content.Load<Effect>("Effects/EffectPointLight");
GameState.DefaultSkinnedEffect = Content.Load<Effect>("Effects/SkinnedtEffectPointLight");
GameState.GameTime = new GameTime();
CurrentScene = new Scene();
CurrentScene.Root = new GameObject();
CurrentScene.Root.Scene = CurrentScene;
Begin();
CurrentScene.CallRecursive("Start");
}
protected override void Update(GameTime gameTime)
{
if (this.IsActive)
{
GameState.PointLights = new List<PointLight>(CurrentScene.Root.GetComponentsInChildren<PointLight>());
GameState.GameTime = gameTime;
GameState.KeyboardState = Keyboard.GetState();
CurrentScene.CallRecursive("Update");
CurrentScene.AddObjects();
CurrentScene.DestroyObjects();
base.Update(gameTime);
}
}
protected override void Draw(GameTime gameTime)
{
foreach (Camera cam in CurrentScene.Root.GetComponentsInChildren<Camera>())
{
cam.RenderScene(GraphicsDevice);
}
GameState.FpsDateTime = DateTime.Now;
base.Draw(gameTime);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using MoviesDemo.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
namespace MoviesDemo
{
public class Query
{
private readonly IMongoCollection<Movie> _movies;
public Query(IOptions<MoviesDatabaseConfiguration> config)
{
var configMongo = config.Value;
var client = new MongoClient(configMongo.ConnectionString);
var database = client.GetDatabase(configMongo.DatabaseName);
_movies = database.GetCollection<Movie>(configMongo.MoviesCollectionName);
}
public List<Movie> GetMovies()
{
Console.WriteLine("The request to the mongo DB for all movies is done");
return _movies.Find(movie => true).ToList();
}
public Movie GetMovie(string id) {
Console.WriteLine($"The request to the mongo DB for movie {id} is done");
return _movies.Find<Movie>(movie => movie.MovieId == id).FirstOrDefault();
}
public Movie Create(Movie movie)
{
_movies.InsertOne(movie);
return movie;
}
public void Update(string id, Movie movieIn) => _movies.ReplaceOne(movie => movie.MovieId == id, movieIn);
public void Remove(string id) => _movies.DeleteOne(movie => movie.MovieId == id);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dropkick;
using dropkick.DeploymentModel;
using dropkick.FileSystem;
using System.Text.RegularExpressions;
namespace dropkick.Tasks.Files
{
public class OpenFolderShareAuthenticationTask : Task
{
private readonly string _to;
private readonly string _userName;
private readonly string _password;
public OpenFolderShareAuthenticationTask(string to, string userName, string password)
{
_to = to;
_userName = userName;
_password = password;
}
public string Name
{
get { return "Creating new empty folder '{0}' with user name '{1}'".FormatWith(_to, _userName); }
}
public DeploymentResult VerifyCanRun()
{
var result = new DeploymentResult();
var to = new DotNetPath().GetFullPath(_to);
string toParent = GetRootShare(to);
try
{
using (var context = FileShareAuthenticator.BeginFileShareAuthentication(toParent, _userName, _password))
{
result.AddGood(System.IO.Directory.Exists(to) ? "'{0}' already exists.".FormatWith(to) : Name);
}
}
catch (Exception err)
{
result.AddError("Failed to access '{0}' as user '{1}'".FormatWith(toParent, _userName), err);
}
//TODO figure out a good verify step...
return result;
}
private string GetRootShare(string to)
{
var regex = new Regex(@"\\\\[^\\]*\\[^\\]*");
var match = regex.Match(to);
if (!match.Success)
{
throw new Exception("Unable to parse root share from " + to);
}
return match.Value;
}
public DeploymentResult Execute()
{
var result = new DeploymentResult();
var to = new DotNetPath().GetFullPath(_to);
var toParent = GetRootShare(to);
try
{
using (var context = FileShareAuthenticator.BeginFileShareAuthentication(toParent, _userName, _password))
{
result.AddGood("'{0}' authenticated with {1}.".FormatWith(to, _userName));
}
}
catch (Exception err)
{
result.AddError("Failed to access '{0}' as user '{1}'".FormatWith(toParent, _userName), err);
}
return result;
}
}
}
|
namespace Fingo.Auth.Domain.Projects.Interfaces
{
public interface IGetAddressForSetPassword
{
string Invoke(int projectId);
}
} |
using MmsDb;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MmsApi.Models
{
public class ModelFactory
{
public UserModel Create(UserEntity user)
{
return new UserModel()
{
Id = user.Id,
Name = user.Name,
Username = user.Username,
Password = user.Password,
IsAdmin = user.IsAdmin
};
}
public ImageModel Create(ImageEntity image)
{
return new ImageModel()
{
Id = image.Id,
Description = image.Description,
Location = image.Location,
Ratio = 0
};
}
}
} |
using BLL;
using DAL;
using DAL.Entities;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
public class DbInitializer
{
public static async Task Initialize(AppDbContext context, UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
{
//context.Database.EnsureDeleted();
//context.Database.EnsureCreated();
// Look for any students.
if (context.Users.Any())
{
return; // DB has been seeded
}
var userRole = new IdentityRole { Name = "User" };
var adminRole = new IdentityRole { Name = "Admin" };
// Creating Roles
await roleManager.CreateAsync(userRole);
await roleManager.CreateAsync(adminRole);
// Creating users
var admin = new AppUser
{
Email = "admin@gmail.com",
UserName = "AdamAdmin"//,
//FirstName = "Adam",
//LastName = "Adamson"
};
string adminPassword = "P@ssw0rd";
var adminResult = await userManager.CreateAsync(admin, adminPassword);
var user = new AppUser
{
Email = "student@gmail.com",
UserName = "student@gmail.com"//,
//FirstName = "Sam",
//LastName = "Simpson"
};
string userPassword = "P@ssw0rd";
var userResult = await userManager.CreateAsync(user, userPassword);
if (adminResult.Succeeded && userResult.Succeeded)
{
await userManager.AddToRoleAsync(admin, adminRole.Name);
await userManager.AddToRoleAsync(user, userRole.Name);
//await userManager.AddToRoleAsync(admin, userRole.Name);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventDepartmentManager
{
[Serializable]
public class ListOfCustomers
{
public List<Customer> Cust { get; set; }
public ListOfCustomers(List<Customer> cust)
{
Cust = cust;
}
public ListOfCustomers()
{
}
}
}
|
using jaytwo.Common.Extensions;
using jaytwo.Common.Http;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace jaytwo.Common.Test.Http.UrlHelperTests
{
public static class SetSchemeHttpTests
{
private static IEnumerable<TestCaseData> UrlHelper_SetUriSchemeHttp_TestCases()
{
yield return new TestCaseData(null).Throws(typeof(ArgumentNullException));
yield return new TestCaseData("http://www.google.com").Returns("http://www.google.com/");
yield return new TestCaseData("https://www.google.com").Returns("http://www.google.com/");
}
[Test]
[TestCaseSource("UrlHelper_SetUriSchemeHttp_TestCases")]
public static string UrlHelper_SetUriSchemeHttp(string url)
{
var uri = TestUtility.GetUriFromString(url);
return UrlHelper.SetUriSchemeHttp(uri).ToString();
}
[Test]
[TestCaseSource("UrlHelper_SetUriSchemeHttp_TestCases")]
public static string UrlHelper_SetUrlSchemeHttp(string url)
{
return UrlHelper.SetUrlSchemeHttp(url);
}
[Test]
[TestCaseSource("UrlHelper_SetUriSchemeHttp_TestCases")]
public static string HttpExtensionMethods_WithSchemeHttp(string url)
{
var uri = TestUtility.GetUriFromString(url);
return uri.WithSchemeHttp().ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Repository.Repositorio;
namespace Interfaces.Interfaces
{
public interface ITradeBS
{
}
}
|
using Eda.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace Eda.Integrations.Delivery.DependencyInjection
{
/// <summary>
/// Contains <see cref="IServiceCollection"/> extensions for adding delivery.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the delivery.
/// </summary>
/// <param name="this">The service collection.</param>
/// <typeparam name="TDeliveryApplicationBlock">The application block type.</typeparam>
public static IServiceCollection AddDelivery<TDeliveryApplicationBlock>(this IServiceCollection @this)
where TDeliveryApplicationBlock : DeliveryApplicationBlock
{
@this.AddBlock<TDeliveryApplicationBlock>();
return @this;
}
/// <summary>
/// Adds the delivery.
/// </summary>
/// <param name="this">The service collection.</param>
/// <param name="block">The block.</param>
public static IServiceCollection AddDelivery(this IServiceCollection @this, DeliveryApplicationBlock block)
{
@this.AddBlock(block);
return @this;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeAutomation.BusinessServices
{
public class DoorSwitchReading
{
public int ID { get; set; }
public int SensorID { get; set; }
public bool DoorOpen { get; set; }
public DateTime ReadingDateTime { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using Microsoft.Extensions.Configuration;
namespace Core31DemoProject.Utility.ConsulExtend
{
public static class ConsulRegister
{
public static void RegisterConsul(this IConfiguration configuration)
{
#region 注册Consul
string ip = configuration["ip"] ?? "localhost";
//部署到不同服务器的时候不能写成127.0.0.1或0.0.0.0,因为这是让服务消费者调用的地址
int port = string.IsNullOrWhiteSpace(configuration["port"]) ? 44344 : int.Parse(configuration["port"]);
ConsulClient client = new ConsulClient(consulclientCon =>
{
consulclientCon.Address = new Uri("http://127.0.0.1:8500");
consulclientCon.Datacenter = "dc1";
});
//向consul注册服务
Task<WriteResult> result = client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = "apiserviceTest_" + Guid.NewGuid(),//服务编号,不能重复,用guid最简单
Name = "apiserviceTest",//服务的名称
Address = ip,
Port = port,
Tags = new string[] { },//可以用来设置权重
Check = new AgentServiceCheck
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务停止多久后反注册
Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
HTTP = $"http://{ip}:{port}/api/health",//健康检查地址
Timeout = TimeSpan.FromSeconds(5)
}
});
#endregion
}
}
}
|
using System;
using System.Text;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.UnifiedPlatform.Service.Common.Authentication;
namespace Microsoft.UnifiedPlatform.Service.Authentication
{
public class RedisClusterAuthenticator: IAuthenticator
{
private readonly string _audience;
private readonly string _issuer;
private readonly string _secret;
public RedisClusterAuthenticator(string audience, string issuer, string secret)
{
_audience = audience;
_issuer = issuer;
_secret = secret;
}
public Task<string> GenerateToken(string resourceId, Dictionary<string, string> additionalClaims)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>();
if (additionalClaims != null && additionalClaims.Any())
{
foreach (var claim in additionalClaims)
{
claims.Add(new Claim(claim.Key, claim.Value));
}
}
var jwtToken = new JwtSecurityToken(issuer: _issuer, audience: _audience, claims: claims, expires: DateTime.Now.AddMinutes(45), signingCredentials: credentials);
var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
return Task.FromResult(token);
}
}
}
|
using System.Collections.Generic;
using Assets.Scripts.Models.ResourceObjects;
using Assets.Scripts.Models.ResourceObjects.CraftingResources;
namespace Assets.Scripts.Models.Common
{
public class GardenBedBrick : BaseObject, IPlacement
{
public string PrefabTemplatePath { get; set; }
public string PrefabPath { get; set; }
public GardenBedBrick()
{
LocalizationName = "garden_bed";
Description = "garden_bed_descr";
IconName = "garden_bed_brick";
IsStackable = false;
PrefabTemplatePath = "Prefabs/Items/PlacedItems/GardenBed/GardenBedBrickTemplate";
PrefabPath = "Prefabs/Items/PlacedItems/GardenBed/GardenBedBrick";
CraftRecipe = new List<HolderObject>();
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Brick), 30));
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Manure), 20));
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(GroundResource), 30));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCoreDemo.Controllers
{
//[Route("v1/[controller]")]
public class ValuesController : ApiBaseController
{
private List<string> vals = new List<string>() { "One", "Two", "Three" };
// GET v1/values
[HttpGet]
public IActionResult Get()
{
return CustomData<List<string>>(vals);
}
// GET v1/values/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
return CustomData<string>(vals[id]);
}
// POST v1/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT v1/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE v1/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CarRental.API.BL.Models;
using CarRental.API.BL.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CarRental.API.BL.Services.Clients;
using CarRental.API.BL.Models.Clients;
using CarRental.API.DAL.Entities;
namespace CarRental.API.Controllers
{
[ApiController]
[Route("[controller]")]
public class ClientsController : ControllerBase
{
private readonly IClientsService _clientService;
public ClientsController(IClientsService clientService)
{
_clientService = clientService;
}
[HttpGet]
[Route("GetAllClients")]
/// <summary>
/// Get a list of items
/// </summary>
/// <returns>List with TodoModels</returns>
public virtual async Task<IEnumerable<ClientsModel>> GetAllClients()
{
return await _clientService.GetAllAsync();
}
/// <summary>
/// Get an item by its id.
/// </summary>
/// <param name="id">id of the item you want to get</param>
/// <returns>Item or StatusCode 404</returns>
[HttpGet("GetClient/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesDefaultResponseType]
public virtual async Task<ActionResult<ClientsModel>> GetOneClient(Guid id)
{
var item = await _clientService.GetAsync(id);
if (item is null)
{
return NotFound();
}
return item;
}
/// <summary>
/// Add an item
/// </summary>
/// <param name="item">Model to add, id will be ignored</param>
/// <returns>Id of created item</returns>
[Route("CreateClient")]
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesDefaultResponseType]
public virtual async Task<ClientsItem> CreateOneClient(CreateClientModel item)
{
return await _clientService.CreateAsync(item);
}
/// <summary>
/// Update or create an item
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
[Route("UpdateClient")]
[HttpPut]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesDefaultResponseType]
public virtual async Task<ActionResult<int>> Update(UpdateClientModel item)
{
var updateItemId = await _clientService.UpsertAsync(item);
return Ok(updateItemId);
}
/// <summary>
/// Delete an item
/// </summary>
/// <param name="id">Id of the item to delete</param>
/// <returns>StatusCode 200 or 404</returns>
[HttpDelete("DeleteClient/{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesDefaultResponseType]
public virtual async Task<ActionResult<bool>> Delete(Guid id)
{
var deletedItem = await _clientService.DeleteAsync(id);
return Ok(deletedItem);
}
}
}
|
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
namespace Euler_Logic.Problems {
public class Problem159 : ProblemBase {
private PrimeSieve _primes;
private Dictionary<ulong, ulong> _maxRootSum = new Dictionary<ulong, ulong>();
private Dictionary<ulong, ulong> _rootSums = new Dictionary<ulong, ulong>();
/*
mdrs(n) can be found by looping through each divisor of (n), and for each
divisor (d), calculating x = mdrs(d) + mdrs(n/d). Whichever (d) produces
the highest of (x) is the answer for (n).
Some optimizations can be made. The function that calculates the
digital root sum of a number, as well as mdrs(n), can both save their
results in a dictionary. Also, not every divisor of (n) needs to be found.
Rather, only the divisors up to sqrt(n). Also, if (n) is a prime number,
then the mdrs(n) equals the digital root sum of (n).
*/
public override string ProblemName {
get { return "159: Digital root sums of factorisations"; }
}
public override string GetAnswer() {
return Solve(1000000).ToString();
}
private ulong Solve(ulong maxN) {
ulong sum = 0;
_primes = new PrimeSieve(maxN);
for (ulong n = 2; n < maxN; n++) {
sum += GetMaxDigitalRootSum(n);
}
return sum;
}
private ulong GetMaxDigitalRootSum(ulong n) {
if (!_maxRootSum.ContainsKey(n)) {
var bestRootSum = DigitalRootSum(n);
if (!_primes.IsPrime(n)) {
var maxD = (ulong)Math.Sqrt(n);
for (ulong d = 2; d <= maxD; d++) {
if (n % d == 0) {
var next = GetMaxDigitalRootSum(n / d);
var dRootSum = DigitalRootSum(d);
if (dRootSum + next > bestRootSum) {
bestRootSum = dRootSum + next;
}
}
}
}
_maxRootSum.Add(n, bestRootSum);
}
return _maxRootSum[n];
}
private ulong DigitalRootSum(ulong n) {
if (!_rootSums.ContainsKey(n)) {
ulong sum = 0;
ulong remainder = n;
do {
do {
sum += remainder % 10;
remainder /= 10;
} while (remainder > 0);
if (sum < 10) {
_rootSums.Add(n, sum);
break;
}
remainder = sum;
sum = 0;
} while (true);
}
return _rootSums[n];
}
}
} |
using BoDi;
namespace AutoTests.Framework.Core.Utils
{
public class UtilsDependencies : Dependencies
{
public UtilsDependencies(ObjectContainer objectContainer) : base(objectContainer)
{
}
public ResourceUtils Resources => ObjectContainer.Resolve<ResourceUtils>();
}
} |
using System;
using System.Collections.Generic;
using IrsMonkeyApi.Models.DB;
namespace IrsMonkeyApi.Models.DAL
{
public interface IUploadFileDb
{
File UploadFile(string memberId, string resolution, string filename, string documentName);
List<File> ListFileByUser(Guid memberId);
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BSTree.Tests
{
[TestClass]
public class TestTests
{
[TestMethod]
public void CheckTestData()
{
var testData = TestDataGenerator.GetKeysAndValues(50);
for (int i = 0; i < 50; i++)
Assert.AreEqual(testData.Item1[i], Convert.ToInt32(testData.Item2[i]));
}
}
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// !!!!!! My solution here is way more complicated. Not recommended. Find the best answer in Round 2.
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return Helper(root, p, q).LCA;
}
public HelperClass Helper(TreeNode root, TreeNode p, TreeNode q) {
var ret = new HelperClass();
// exit
if (root == null) {
return ret;
}
if (root.left == null && root.right == null) { // leaf
if (root.val == p.val) {
ret.HasLeftAncestor = true;
} else if (root.val == q.val) {
ret.HasRightAncestor = true;
}
return ret;
}
// divide
var leftRes = Helper(root.left, p, q);
var rightRes = Helper(root.right, p, q);
// merge
if (leftRes.LCA != null) { // find answer in left subtree
return leftRes;
} else if (rightRes.LCA != null) { // find answer in right subtree
return rightRes;
} else if (((leftRes.HasLeftAncestor || root.val == p.val) && (rightRes.HasRightAncestor || root.val == q.val)) || ((leftRes.HasRightAncestor || root.val == q.val) && (rightRes.HasLeftAncestor || root.val == p.val))) {
ret.HasLeftAncestor = true;
ret.HasRightAncestor = true;
ret.LCA = root;
} else {
ret.HasLeftAncestor = leftRes.HasLeftAncestor || rightRes.HasLeftAncestor || root.val == p.val;
ret.HasRightAncestor = leftRes.HasRightAncestor || rightRes.HasRightAncestor || root.val == q.val;
ret.LCA = ret.HasLeftAncestor && ret.HasRightAncestor ? root : null;
}
return ret;
}
}
public class HelperClass {
public bool HasLeftAncestor {get; set;} = false;
public bool HasRightAncestor {get; set;} = false;
public TreeNode LCA {get; set;} = null;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Data;
using EasyDev.Util;
using System.Threading;
using System.Text.RegularExpressions;
using System.Configuration;
using log4net;
using EasyDev.BL;
namespace EasyDev.SQMS
{
public class PermissionModule : IHttpModule
{
private ILog logger = LogManager.GetLogger(typeof(PermissionModule));
//private PassportService passportSrv = null;
//private NativeServiceManager ServiceManager = null;
#region IHttpModule 成员
public void Dispose()
{
}
public void Init(HttpApplication context)
{
//ServiceManager = ServiceManagerFactory.CreateNativeServiceManager();
//passportSrv = ServiceManager.CreateService<PassportService>();
context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
context.Error += new EventHandler(context_Error);
}
/// <summary>
/// 出错处理机制
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void context_Error(object sender, EventArgs e)
{
if (ConvertUtil.ToStringOrDefault(ConfigurationManager.AppSettings["global_exception_handler"]).Equals("true"))
{
HttpContext context = ((HttpApplication)sender).Context;
logger.DebugFormat("[YinPSoft-Debug-{0}] - {1}", DateTime.Now.ToString(), context.Error.Message);
logger.DebugFormat("[YinPSoft-Debug-{0}] - {1}", DateTime.Now.ToString(), context.Error.StackTrace);
context.Response.Redirect("~/" +
ConfigurationManager.AppSettings["ErrorPage"] + "?id=" + context.Error.Message);
}
}
void context_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
UserInfo userInfo = null;
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
UserIdentity uid = new UserIdentity(context.User.Identity.Name);
if (context.Session != null)
{
if (context.Session["USER_INFO"] != null)
{
//uid.UserInfo = context.Session["USER_INFO"] as UserInfo;
userInfo = context.Session["USER_INFO"] as UserInfo;
}
else
{
//如果用户已经通过FORMS验证,但是SESSION中的用户信息不存在
//context.Response.Redirect(FormsAuthentication.LoginUrl+"?status=q&p=__pub__");
}
}
uid.UserInfo = userInfo;
Thread.CurrentPrincipal = new PassportPrincipal(uid);
//判断有没有权限访问当前页
if (Regex.IsMatch(context.Request.RawUrl,
"/Views/Security\\.*|/Views/Components\\.*|/Views/External\\.*") == false)
{
CheckPermission(context);
}
}
else
{
//authCookie为空则说明未登录或已经注销
}
}
#endregion
public void CheckPermission(HttpContext context)
{
UserInfo ui = null;
try
{
if (context.Session != null)
{
ui = context.Session["USER_INFO"] as UserInfo;
if (ui != null)
{
string permission = "__pub__";
string querystring = "";
//从参数中取得权限信息,如果没有参数,则将请求中的页面名称作为权限信息
if (context.Request.QueryString.Count > 0)
{
if (context.Request.QueryString["p"] != null)
{
permission = context.Request.QueryString["p"].ToString(); //URL中的权限信息
}
//else
//{
// throw new Exception("_missing_permission_argument");
//}
querystring = context.Request.Url.Query.Substring(1);//context.Request.RawUrl.Substring(context.Request.RawUrl.IndexOf('?'));
}
else
{
//throw new Exception("_missing_permission_argument");
//对权限判断进行严格处理(去掉此处的注释可放宽对权限的判断条件)
permission = context.Request.Url.Segments[context.Request.Url.Segments.Length - 1].Replace(".aspx", "");
}
if (permission.Equals("__pub__") == false)
{
DataRow[] rows = ui.Permissions.Select("RESIDENTITY='" + permission + "'");
if (rows.Length > 0)
{
DataRow dr = rows[0];
context.RewritePath(
ConvertUtil.ToStringOrDefault(dr["VIEWNAME"]), "", querystring);
}
else
{
throw new Exception("_no_permission");
}
}
}
else
{
//DO NOTHING
}
}
else
{
//DO NOTHING
}
}
catch (Exception e)
{
throw e;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UIAFramework.Exceptions
{
public class UIA_GenericException : Exception
{
public UIA_GenericException(string sMessage) : base(sMessage) { }
}
public class UIA_InvalidSearchParameterFormat : Exception
{
public UIA_InvalidSearchParameterFormat(string searchParameters)
: base(string.Format("Search Parameter Format is not valid -> '{0}', should be like 'sKey1=sValue1;sKey2=sValue2;'.", searchParameters))
{ }
}
public class UIA_WrongPageExpectedException : Exception
{
public UIA_WrongPageExpectedException(string sMessage) : base(sMessage) { }
}
public class UIA_InvalidSearchKey : Exception
{
public UIA_InvalidSearchKey(string sKey, string searchParameters, List<string> controlProperties)
: base(string.Format("Search Pattern Key not supported -> '{0}' in '{1}'. Available Properties: {2}", sKey, searchParameters,
string.Join(", ", controlProperties)))
{ }
}
public class UIA_InvalidTraversal : Exception
{
public UIA_InvalidTraversal(string sMessage)
: base(string.Format("You are trying to traverse to an element/control which is not present in the tree: {0}", sMessage))
{ }
}
public class UI_NullElement : Exception
{
public UI_NullElement(string controlName, string searchAttribute)
: base(controlName + " is not found with search attribute " + searchAttribute)
{
}
}
}
|
using Microsoft.AspNetCore.SignalR;
namespace WitsmlExplorer.Api.Services
{
public class NotificationsHub: Hub
{
}
}
|
using System.Collections.Generic;
using System.Linq;
using Cradiator.Config;
using Cradiator.Model;
namespace Cradiator.Audio
{
public class DiscJockey : IConfigObserver
{
IEnumerable<ProjectStatus> _previousBuildData = new List<ProjectStatus>();
readonly IAudioPlayer _audioPlayer;
readonly SpeechMaker _speechMaker;
string _brokenBuildSound;
string _fixedBuildSound;
public DiscJockey(IConfigSettings configSettings, IAudioPlayer audioPlayer, SpeechMaker speechMaker)
{
_audioPlayer = audioPlayer;
_speechMaker = speechMaker;
_brokenBuildSound = configSettings.BrokenBuildSound;
_fixedBuildSound = configSettings.FixedBuildSound;
configSettings.AddObserver(this);
}
public void PlaySounds(IEnumerable<ProjectStatus> currentBuildData)
{
var currentBuildDataList = currentBuildData as IList<ProjectStatus> ?? currentBuildData.ToList();
var newlyBrokenBuilds =
currentBuildDataList.Where(proj => proj.IsBroken)
.Intersect(_previousBuildData.Where(proj => !proj.IsBroken)).ToList();
if (newlyBrokenBuilds.Any())
{
_audioPlayer.Play(_brokenBuildSound);
_audioPlayer.Say(_speechMaker.BuildIsBroken(newlyBrokenBuilds));
}
else
{
var newlyFixedBuilds =
currentBuildDataList.Where(proj => proj.IsSuccessful)
.Intersect(_previousBuildData.Where(proj => !proj.IsSuccessful)).ToList();
if (newlyFixedBuilds.Any())
{
_audioPlayer.Play(_fixedBuildSound);
_audioPlayer.Say(_speechMaker.BuildIsFixed(newlyFixedBuilds));
}
}
_previousBuildData = currentBuildDataList;
}
public void ConfigUpdated(ConfigSettings newSettings)
{
_brokenBuildSound = newSettings.BrokenBuildSound;
_fixedBuildSound = newSettings.FixedBuildSound;
}
}
} |
using Discord;
using JhinBot.Conversation;
using JhinBot.DiscordObjects;
using JhinBot.Utils;
using System;
using System.Collections.Generic;
namespace JhinBot.Services
{
public class EmbedService : IEmbedService
{
private readonly IBotConfig _botConfig;
private readonly IResourceService _resources;
public EmbedService(IBotConfig botConfig, IResourceService resources)
{
_botConfig = botConfig;
_resources = resources;
}
public EmbedBuilder CreateEmbed(string title, string colorCode, IUser author = null, string desc = "", string thumbnailURL = "", string footerText = "")
{
return new EmbedBuilder
{
Title = title,
Color = new Color(Convert.ToUInt32(colorCode, 16)),
Description = desc,
Footer = new EmbedFooterBuilder
{
IconUrl = author == null ? "" : author.GetAvatarUrl(),
Text = author == null ? $"{footerText}" : $"{author.Username} {footerText}"
},
ThumbnailUrl = thumbnailURL,
Timestamp = DateTime.UtcNow
};
}
public EmbedBuilder CreateEmbedWithList(string resxTitle, string colorCode, IEnumerable<(string, string)> list, IUser author = null, string resxDesc = "",
string thumbnailURL = "", params string[] descArgs)
{
var desc = GetDescString(resxDesc, descArgs);
var title = _resources.GetString(resxTitle);
var embedBuilder = CreateEmbed(title, colorCode, author, desc, thumbnailURL);
foreach (var pair in list)
{
embedBuilder.AddField(pair.Item1, pair.Item2);
}
return embedBuilder;
}
public PagedEmbed CreatePagedEmbed(string resxTitle, string colorCode, List<(string, string)> list, IOwnerLogger ownerLogger,
IBotConfig botConfig, IUser author, string resxDesc = "", params string[] descArgs)
{
var desc = GetDescString(resxDesc, descArgs);
var title = _resources.GetString(resxTitle);
var embedBuilder = CreateEmbed(_resources.GetString(resxTitle), colorCode, author, resxDesc);
var pagedEmbed = new PagedEmbed(ownerLogger, botConfig);
pagedEmbed.CreatePagedEmbed(embedBuilder, list, author.Id);
return pagedEmbed;
}
public EmbedBuilder CreateInfoEmbed(string resxTitle, string resxDesc, IUser author, params string[] descArgs)
{
var desc = resxDesc == "" ? "" : GetDescString(resxDesc, descArgs);
var title = _resources.GetString(resxTitle);
return CreateEmbed(title, _botConfig.InfoColor, author, desc);
}
public EmbedBuilder CreateTagEmbed(Dictionary<string, string> tagBody)
{
var title = tagBody["title"];
var desc = tagBody["desc"];
var thumbURL = tagBody["thumbURL"];
var embed = CreateEmbed(title, _botConfig.EventColor, null, desc, thumbURL);
string[] subTitles = tagBody["subTitles"].Split(";");
string[] subDescs = tagBody["subDescs"].Split(";");
for (int i = 0; i < subTitles.Length; ++i)
{
embed.AddField(subTitles[i], subDescs[i]);
}
return embed;
}
private string GetDescString(string resxDesc, string[] args)
{
if (args.Length == 0)
return _resources.GetString(resxDesc);
else if (resxDesc == "")
return "";
else
return _resources.GetFormattedString(resxDesc, args);
}
}
}
|
using System;
namespace BlazorShared.Models.Patient
{
public class DeletePatientResponse : BaseResponse
{
public DeletePatientResponse(Guid correlationId) : base(correlationId)
{
}
public DeletePatientResponse()
{
}
}
} |
using Alabo.Datas.Stores.Distinct.EfCore;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Alabo.Datas.Stores.Exist.EfCore {
public abstract class ExistsAsyncEfCoreStore<TEntity, TKey> : DistinctEfCoreStore<TEntity, TKey>,
IExistsAsyncStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected ExistsAsyncEfCoreStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
/// <summary>
/// 判断是否存在
/// </summary>
/// <param name="predicate">条件</param>
public async Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> predicate) {
if (predicate == null) {
return false;
}
return await Set.AnyAsync(predicate);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _02._Dungeons_Dark
{
class Program
{
static void Main(string[] args)
{
List<string> input = Console.ReadLine().Split("|", StringSplitOptions.RemoveEmptyEntries).ToList();
int health = 100;
int coins = 0;
for (int i = 0; i < input.Count; i++)
{
string currentCommand = input[i];
List<string> current = currentCommand.Split().ToList();
if (current[0]=="chest")
{
coins += int.Parse(current[1]);
Console.WriteLine($"You found {current[1]} coins.");
}
else if (current[0]=="potion")
{
int initialHealth = health;
health += int.Parse(current[1]);
int healedFor = int.Parse(current[1]);
if (health>100)
{
health = 100;
healedFor = 100 - initialHealth;
}
Console.WriteLine($"You healed for {healedFor} hp.");
Console.WriteLine($"Current health: {health} hp.");
}
else
{
health -= int.Parse(current[1]);
if (health<=0)
{
Console.WriteLine($"You died! Killed by {current[0]}.");
Console.WriteLine($"Best room: {i+1}");
return;
}
else
{
Console.WriteLine($"You slayed {current[0]}.");
}
}
}
Console.WriteLine("You've made it!");
Console.WriteLine($"Coins: {coins}");
Console.WriteLine($"Health: {health}");
}
}
}
|
using System;
using UnityEngine;
public class BitMaskMap
{
/*
Supermap knows of itself and of 8 surrounding tiles
Supermap needs these:
- rooms: bits 1 - 9
- roads: bits 11 - 19
- walls: bits 21 - 29
- walkable: bit 30, only this square
- checkedbit for regionfinding floodfill
bit 32
This leaves bits 10, 20, unused
First bit is always current tile, and rest eight are surroundin tiles,
from topleft, row by row.
*/
// These should be moved somewhere else, but now they are here for time being
// these refer to surrounding tiles around current tile
const int topLeft = 1,
topMid = 2,
topRight = 4,
midLeft = 8,
midRight = 16,
bottomLeft = 32,
bottomMid = 64,
bottomRight = 128;
// use these with surrounding tiles
const int groundShift = 1,
roadShift = 11,
wallShift = 21;
// these refer to bit in which is stored if this tile has that tile in it
const int groundBit = 1 << 0,
roadBit = 1 << 10,
wallBit = 1 << 20;
int walkableBit = 1 << 29;
// This is used in region separating to check if tile has been looked already
int checkedBit = 1 << 31;
public Vector2Int size { get; private set; }
private Int32[,] map;
public BitMaskMap (int sizeX, int sizeY) {
map = new int[sizeX, sizeY];
size = new Vector2Int (sizeX, sizeY);
}
public bool GetGround (int x, int y) {
return (map [x, y] & groundBit) == groundBit;
}
public void SetGround (int x, int y) {
map [x, y] |= groundBit;
map [x - 1, y - 1] |= (topRight << groundShift);
map [x, y - 1] |= (topMid << groundShift);
map [x + 1, y - 1] |= (topLeft << groundShift);
map [x - 1, y] |= (midRight << groundShift);
map [x + 1, y] |= (midLeft << groundShift);
map [x - 1, y + 1] |= (bottomRight << groundShift);
map [x, y + 1] |= (bottomMid << groundShift);
map [x + 1, y + 1] |= (bottomLeft << groundShift);
}
public void ClearGround (int x, int y) {
map [x, y] &= ~groundBit;
map [x - 1, y - 1] &= ~(topRight << groundShift);
map [x, y - 1] &= ~(topMid << groundShift);
map [x + 1, y - 1] &= ~(topLeft << groundShift);
map [x - 1, y] &= ~(midRight << groundShift);
map [x + 1, y] &= ~(midLeft << groundShift);
map [x - 1, y + 1] &= ~(bottomRight << groundShift);
map [x, y + 1] &= ~(bottomMid << groundShift);
map [x + 1, y + 1] &= ~(bottomLeft << groundShift);
}
public bool GetRoad (int x, int y)
{
return (map [x, y] & roadBit) == roadBit;
}
public void SetRoad (int x, int y)
{
map [x, y] |= roadBit;
map [x - 1, y - 1] |= (topRight << roadShift);
map [x, y - 1] |= (topMid << roadShift);
map [x + 1, y - 1] |= (topLeft << roadShift);
map [x - 1, y] |= (midRight << roadShift);
map [x + 1, y] |= (midLeft << roadShift);
map [x - 1, y + 1] |= (bottomRight << roadShift);
map [x, y + 1] |= (bottomMid << roadShift);
map [x + 1, y + 1] |= (bottomLeft << roadShift);
}
public void ClearRoad (int x, int y)
{
map [x, y] &= ~roadBit;
map [x - 1, y - 1] &= ~(topRight << roadShift);
map [x, y - 1] &= ~(topMid << roadShift);
map [x + 1, y - 1] &= ~(topLeft << roadShift);
map [x - 1, y] &= ~(midRight << roadShift);
map [x + 1, y] &= ~(midLeft << roadShift);
map [x - 1, y + 1] &= ~(bottomRight << roadShift);
map [x, y + 1] &= ~(bottomMid << roadShift);
map [x + 1, y + 1] &= ~(bottomLeft << roadShift);
}
public bool GetWall (int x, int y)
{
return (map [x, y] & wallBit) == wallBit;
}
public void SetWall (int x, int y)
{
map [x, y] |= wallBit;
map [x - 1, y - 1] |= (topRight << wallShift);
map [x, y - 1] |= (topMid << wallShift);
map [x + 1, y - 1] |= (topLeft << wallShift);
map [x - 1, y] |= (midRight << wallShift);
map [x + 1, y] |= (midLeft << wallShift);
map [x - 1, y + 1] |= (bottomRight << wallShift);
map [x, y + 1] |= (bottomMid << wallShift);
map [x + 1, y + 1] |= (bottomLeft << wallShift);
}
public void ClearWall (int x, int y)
{
map [x, y] &= ~wallBit;
map [x - 1, y - 1] &= ~(topRight << wallShift);
map [x, y - 1] &= ~(topMid << wallShift);
map [x + 1, y - 1] &= ~(topLeft << wallShift);
map [x - 1, y] &= ~(midRight << wallShift);
map [x + 1, y] &= ~(midLeft << wallShift);
map [x - 1, y + 1] &= ~(bottomRight << wallShift);
map [x, y + 1] &= ~(bottomMid << wallShift);
map [x + 1, y + 1] &= ~(bottomLeft << wallShift);
}
public bool GetWalkable (int x, int y)
{
return (map [x, y] & walkableBit) == walkableBit;
}
public void SetWalkable (int x, int y)
{
map [x, y] |= walkableBit;
}
}
|
using System;
using System.Security.Cryptography;
using System.Text;
namespace Web.Libraries
{
public class Encryption
{
/// <summary>
/// Performs a Sha 256 Hash function on a supplied value
/// </summary>
/// <param name="value"></param>
/// <returns>string</returns>
public static string Hash(string value)
{
var result = new SHA256CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(value));
return Convert.ToBase64String(result, 0, result.Length);
}
}
} |
using aairvid.Model;
using aairvid.Utils;
using Android.Content;
using Android.Views;
using Android.Widget;
using System.Collections.Generic;
namespace aairvid.History
{
public class HistoryItemJavaAdapter : Java.Lang.Object
{
public HistoryItem Details { get; set; }
}
public class RecentlyItemListAdapter : BaseAdapter<HistoryItemJavaAdapter>
{
private readonly Context _ctx;
private readonly List<HistoryItemJavaAdapter> _items = new List<HistoryItemJavaAdapter>();
public RecentlyItemListAdapter(Context context)
{
_ctx = context;
}
public override int Count
{
get { return _items.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return _items[position];
}
public override long GetItemId(int position)
{
return position;
}
public string GetVideoName(int position)
{
return position < _items.Count ? _items[position].Details.VideoName : "";
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
if (convertView == null) // otherwise create a new one
{
var inflater = LayoutInflater.From(_ctx);
convertView = inflater.Inflate(Resource.Layout.recently_item, null);
}
var itemDesc = convertView
.FindViewById<TextView>(Resource.Id.tvVideoBaseName);
var item = _items[position];
itemDesc.Text = item.Details.VideoName + " @ " + item.Details.FolderPath;
return convertView;
}
internal void AddItem(string videoBasename, HistoryItem historyItem)
{
if (string.IsNullOrEmpty(historyItem.Server))
{
return;//old version.
}
_items.Add(new HistoryItemJavaAdapter()
{
Details = historyItem
});
NotifyDataSetChanged();
}
internal void RemoveItem(int p)
{
var item = _items[p];
_items.RemoveAt(p);
HistoryMaiten.HistoryItems.Remove(item.Details.VideoId);
HistoryMaiten.SaveAllItems();
NotifyDataSetChanged();
}
public override HistoryItemJavaAdapter this[int position]
{
get
{
return position >= _items.Count ? null : _items[position];
}
}
}
} |
using Allyn.Application.Dto.Manage.Front;
using Allyn.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Allyn.Application.Front
{
/// <summary>
/// 表示会员组织应用服务类型.
/// </summary>
public interface IOrganizeService
{
/// <summary>
/// 获取一个会员组织.
/// </summary>
/// <param name="key">会员组织标识</param>
/// <returns>会员组织</returns>
OrganizeDto GetOrganizeByKey(Guid key);
/// <summary>
/// 获取指定会员所在的会员组织.
/// </summary>
/// <param name="userKey">会员标识</param>
/// <returns>会员组织</returns>
OrganizeDto GetOrganizeByMemberKey(Guid userKey);
/// <summary>
/// 获取一个用于修改的会员组织数据传输对象.
/// </summary>
/// <param name="key">会员组织标识</param>
/// <returns></returns>
OrganizeEditDto GetOrganizeEditDto(Guid key);
/// <summary>
/// 获取会员组织分页集合.
/// </summary>
/// <param name="pageNumber">页码</param>
/// <param name="pageSize">分页大小</param>
/// <returns>会员组织分页集合</returns>
PagedResult<OrganizeDto> GetPrOrganizes(int pageNumber, int pageSize);
/// <summary>
/// 获取会员组织分页集合.
/// </summary>
/// <param name="strWhere">条件</param>
/// <param name="pageNumber">页码</param>
/// <param name="pageSize">分页大小</param>
/// <returns>会员组织分页集合</returns>
PagedResult<OrganizeDto> GetPrOrganizes(string strWhere, int pageNumber, int pageSize);
/// <summary>
/// 更新一个会员组织.
/// </summary>
/// <param name="model">会员组织聚合给类型</param>
void UpdateOrganize(OrganizeEditDto model);
/// <summary>
/// 新增一个会员组织
/// </summary>
/// <param name="model">会员组织聚合给类型</param>
void AddOrganize(OrganizeAddDto model);
/// <summary>
/// 根据指定标识列表删除会员组织.
/// </summary>
/// <param name="keys">会员组织标识列表</param>
void DeleteOrganize(List<Guid> keys);
}
}
|
using System;
using System.Collections.Generic;
class Palindromes
{
static void Main()
{
string[] inputStr = Console.ReadLine().Split(new char[] { ' ', ',', '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries);
List<string> palindromes = new List<string>();
for (int i = 0; i < inputStr.Length; i++)
{
if (IsPalindrome(inputStr[i]))
{
palindromes.Add(inputStr[i]);
}
}
palindromes.Sort();
Console.WriteLine(string.Join(", ", palindromes));
}
private static bool IsPalindrome(string p)
{
int min = 0;
int max = p.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char ch1 = p[min];
char ch2 = p[max];
if (!ch1.Equals(ch2))
{
return false;
}
min++;
max--;
}
}
} |
using System;
using System.Windows;
using System.Windows.Input;
using Beeffective.Commands;
using Beeffective.Extensions;
using Beeffective.Views;
using MaterialDesignThemes.Wpf;
namespace Beeffective.ViewModels
{
class ExpandableViewModel : ClosableViewModel
{
private string customIcon;
private bool isExpanded;
private double expandedLeft;
private double collapsedLeft;
protected ExpandableViewModel(IMainView mainView)
: base(mainView)
{
CustomIcon = nameof(PackIconKind.ArrowLeft);
ShowHideCommand = new DelegateCommand(obj => ShowOrHide());
ShowCommand = new DelegateCommand(obj => Show());
HideCommand = new DelegateCommand(obj => Hide());
}
private const int ExpansionOffset = 40;
public bool IsExpanded
{
get => isExpanded;
set
{
if (Equals(isExpanded, value)) return;
isExpanded = value;
CustomIcon = isExpanded ? nameof(PackIconKind.ArrowRight) : nameof(PackIconKind.ArrowLeft);
isExpanded.IfTrue(RaiseExpanded).IfFalse(RaiseCollapsed);
OnPropertyChanged();
}
}
public double ExpandedLeft
{
get => expandedLeft;
set
{
if (Equals(expandedLeft, value)) return;
expandedLeft = value;
}
}
public double CollapsedLeft
{
get => collapsedLeft;
set
{
if (Equals(collapsedLeft, value)) return;
collapsedLeft = value;
OnPropertyChanged();
}
}
public string CustomIcon
{
get => customIcon;
set
{
if (Equals(customIcon, value)) return;
customIcon = value;
OnPropertyChanged();
}
}
public ICommand ShowHideCommand { get; }
public ICommand ShowCommand { get; }
public ICommand HideCommand { get; }
public void SetWorkArea(Rect workArea)
{
ExpandedLeft = workArea.Width - View.Width;
CollapsedLeft = workArea.Width - ExpansionOffset;
View.Top = workArea.Height / 5;
}
public event EventHandler Expanded;
private void RaiseExpanded() => Expanded?.Invoke(this, EventArgs.Empty);
public event EventHandler Collapsed;
private void RaiseCollapsed() => Collapsed?.Invoke(this, EventArgs.Empty);
protected void ShowOrHide() => IsExpanded = !IsExpanded;
protected void Show() => IsExpanded = true;
protected void Hide() => IsExpanded = false;
}
} |
using System.Data.Entity;
using DAL.Models;
using Microsoft.AspNet.Identity.EntityFramework;
namespace DAL
{
public class MoviesContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Movie> Movies { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<People> Peoples { get; set; }
public DbSet<Career> Careers { get; set; }
public DbSet<Country> Countries { get; set; }
public DbSet<CastAndCrew> CastAndCrews { get; set; }
public DbSet<Rating> Ratings { get; set; }
public DbSet<UserComment> UserComments { get; set; }
public MoviesContext()
: base("MoviesContext")
{
Database.SetInitializer(new ApplicationDbInitializer(/*this*/));
//Database.SetInitializer(new CreateDatabaseIfNotExists<MoviesContext>());
}
public static MoviesContext Create()
{
return new MoviesContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Movie>()
.Property(f => f.PremiereDate)
.HasColumnType("datetime2");
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Tianhai.OujiangApp.Schedule.Services{
public class ScheduleService:DataService{
public ScheduleService(){}
public static async Task<Models.Schedule> fetchCurrent(string token){
Models.GeneralReturn<Models.Schedule> result=await DataFetch.post<Models.Schedule>(String.Format(urlGetScheduleCurrent,urlBase,token),new Dictionary<string,string>{});
if(result.Status==200){
return result.Data;
}else{
throw new Exception(result.Return);
}
}
public static async Task<List<Models.Lesson>> RefreshCurrentLessons(){
Models.Preferences.Token token=App.PreferenceDatabase.GetToken();
if(token==null || !token.IsLoggedIn){
throw new Exceptions.SessionTimeoutException();
}
Models.Schedule schedule=await fetchCurrent(token.AccessToken);
if(schedule!=null){
App.CurrentInfoDatabase.ResetAsync(schedule.Lessons);
return schedule.Lessons;
}else{
return null;
}
}
public static async Task<List<Models.Lesson>> GetCurrentLessons(){
return await App.CurrentInfoDatabase.GetAsync();
}
}
}
|
using System;
using System.Runtime.CompilerServices;
using AbilityUser;
using Verse;
using RimlightArchive.Defs;
using RimlightArchive.Needs;
namespace RimlightArchive.Comps
{
/// <summary>
/// Handler for Investiture-based abilities.
/// </summary>
[CompilerGenerated]
[Serializable]
[StaticConstructorOnStartup]
public class CompAbilityUser_Investiture : CompAbilityUser
{
private bool firstTick = true;
private bool abilitiesInitialized = false;
private RadiantData radiantData;
public float CoolDown { get; set; } = 0f;
public float MaxStormlight => 1f * this.RadiantLevel;
public float RadiantLevel => (this.AbilityUser?.health.hediffSet.GetFirstHediffOfDef(RadiantDefOf.RA_KnightRadiant, false)?.Severity).GetValueOrDefault(0f);
public Need_Stormlight Stormlight => !this.AbilityUser.DestroyedOrNull() && !this.AbilityUser.Dead ? this.AbilityUser.needs.TryGetNeed<Need_Stormlight>() : null;
public RadiantData RadiantData
{
get
{
if (this.radiantData == null && Utils.IsPawnRadiant(this.AbilityUser, out var comp))
{
this.radiantData = new RadiantData(this);
return this.radiantData;
}
return null;
}
}
public override void CompTick()
{
if (this.AbilityUser == null
|| !this.AbilityUser.Spawned
|| !Utils.IsPawnRadiant(this.AbilityUser, out var comp)
|| this.Pawn.NonHumanlikeOrWildMan())
{
return;
}
if (this.firstTick)
{
this.PostInitializeTick();
}
base.CompTick();
if (!this.Pawn.IsColonist)
return;
//ResolveSquires();
//ResolveSustainers();
//ResolveEffecter();
//this.ResolveClassSkills();
}
public override void PostInitialize()
{
base.PostInitialize();
if (!this.abilitiesInitialized)
{
this.AssignAbilities();
}
this.abilitiesInitialized = true;
base.UpdateAbilities();
}
public override void PostPreApplyDamage(DamageInfo dinfo, out bool absorbed)
{
base.PostPreApplyDamage(dinfo, out absorbed);
}
public override void PostExposeData()
{
base.PostExposeData();
}
public void PostInitializeTick()
{
if (this.AbilityUser == null || !this.AbilityUser.Spawned || this.AbilityUser.story == null)
return;
this.firstTick = false;
this.Initialize();
if (this.Stormlight != null)
return;
var firstHediffOfDef = this.AbilityUser.health.hediffSet.GetFirstHediffOfDef(RadiantDefOf.RA_KnightRadiant, false);
if (firstHediffOfDef != null)
{
firstHediffOfDef.Severity = 1f;
return;
}
Log.Message("don't get here!");
var hediff = HediffMaker.MakeHediff(RadiantDefOf.RA_KnightRadiant, this.AbilityUser, null);
hediff.Severity = 1f;
this.AbilityUser.health.AddHediff(hediff, null, null);
}
private void AssignAbilities()
{
if (!Utils.IsPawnRadiant(this.AbilityUser, out var comp))
return;
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Bondsmith))
{
Log.Message("Initializing RA_Bondsmith Abilities");
// add adhesion
// add tension
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Dustbringer))
{
Log.Message("Initializing RA_Dustbringer Abilities");
// add Division
// add Abrasion
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Edgedancer))
{
Log.Message("Initializing RA_Edgedancer Abilities");
// add Abrasion
// add Progression
this.RemovePawnAbility(RadiantDefOf.RA_Regrowth);
this.AddPawnAbility(RadiantDefOf.RA_Regrowth);
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Elsecaller))
{
Log.Message("Initializing RA_Elsecaller Abilities");
// add Transformation
// add Transportation
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Lightweaver))
{
Log.Message("Initializing RA_Lightweaver Abilities");
// add Illumination
// add Transformation
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Skybreaker))
{
Log.Message("Initializing RA_Skybreaker Abilities");
// add Division
// add gravitation
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Stoneward))
{
Log.Message("Initializing RA_Stoneward Abilities");
// add Cohesion
// add Tension
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Truthwatcher))
{
Log.Message("Initializing RA_Truthwatcher Abilities");
// add Progression
// add Illumination
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Willshaper))
{
Log.Message("Initializing RA_Willshaper Abilities");
// add Transportation
// add Cohesion
}
if (this.AbilityUser.story.traits.HasTrait(RadiantDefOf.RA_Windrunner))
{
Log.Message("Initializing Windrunner Abilities");
// add adhesion
this.RemovePawnAbility(RadiantDefOf.RA_Adhesion);
this.AddPawnAbility(RadiantDefOf.RA_Adhesion);
// add gravitation
this.RemovePawnAbility(RadiantDefOf.RA_Flight);
this.AddPawnAbility(RadiantDefOf.RA_Flight);
this.RemovePawnAbility(RadiantDefOf.RA_Launch);
this.AddPawnAbility(RadiantDefOf.RA_Launch);
// add resonance
if (this.RadiantLevel > 1)
{
this.RemovePawnAbility(RadiantDefOf.RA_MakeWindrunnerSquire);
this.AddPawnAbility(RadiantDefOf.RA_MakeWindrunnerSquire);
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ELearningPlatform.Models
{
public class Inscription
{
public int Id { get; set; }
public int IdUser { get; set; }
public int IdCourse { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using DnsHelperUI.WindowsFormsApplication_CS;
using Newtonsoft.Json;
namespace DnsHelperUI
{
public partial class MainForm : Form
{
/// <summary>
/// The currently selected Network interface card
/// </summary>
private string _currentNic;
public string CurrentNic
{
get { return _currentNic; }
set
{
_currentNic = value;
// Update the DNS values to the currently applied ones
var dnsServers = RefreshDNSValues();
SetDnsTextBoxValues(dnsServers != null && dnsServers.Length > 0 ? dnsServers[0] : string.Empty,
dnsServers != null && dnsServers.Length > 1 ? dnsServers[1] : string.Empty);
}
}
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// Append the version number to the form title
var version = typeof(MainForm).Assembly.GetName().Version;
if (version != null)
this.Text += $" | v{version}";
// Load the DNS server config from the file
ReloadContextMenuItems();
// Get all the nics and load them into a drop down,
// if we have any NICs, fill dropdown and
// select the first one from the list as current.
var nics = NetworkManagement.GetAllNicDescriptions();
cmbNics.Items.AddRange(nics.Length > 0 ? nics : new string[] { "No Available NiCs" });
cmbNics.SelectedIndex = 0;
}
private string[] RefreshDNSValues()
{
var dnsServers = NetworkManagement.GetNameservers(CurrentNic);
UpdateCurrentDNSLabelValues(dnsServers);
return dnsServers;
}
private void SetDnsTextBoxValues(string dns01, string dns02)
{
tbDns01.Text = dns01;
tbDns02.Text = dns02;
}
private void btnRefresh_Click(object sender, EventArgs e)
{
RefreshDNSValues();
}
private void UpdateCurrentDNSLabelValues(string[] dnsServers)
{
// First reset them
lblDns01Current.Text = lblDns02Current.Text = "(Auto)";
if (dnsServers != null)
{
if (dnsServers.Length > 0 && !dnsServers[0].EndsWith("1.1"))
lblDns01Current.Text = dnsServers[0];
if (dnsServers.Length > 1 && !dnsServers[1].EndsWith("1.1"))
lblDns02Current.Text = dnsServers[1];
}
}
private void btnClearDns_Click(object sender, EventArgs e)
{
UpdateCurrentDNSLabelValues(new[] { "(Waiting)", "(Waiting)" });
NetworkManagement.SetNameservers(CurrentNic, null, restart: true);
tbDns01.Text = tbDns02.Text = "";
RefreshDNSValues();
}
private void btnApplyDns_Click(object sender, EventArgs e)
{
string dns01 = tbDns01.Text?.Trim();
if (!string.IsNullOrWhiteSpace(dns01) && !IsValidIPv4(dns01))
{
MessageBox.Show(this, "DNS 1 is not a valid IPv4 address", "Invalid IPv4", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string dns02 = tbDns02.Text?.Trim();
if (!string.IsNullOrWhiteSpace(dns02) && !IsValidIPv4(dns02))
{
MessageBox.Show(this, "DNS 2 is not a valid IPv4 address", "Invalid IPv4", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
UpdateCurrentDNSLabelValues(new[] { "(Waiting)", "(Waiting)" });
NetworkManagement.SetNameservers(CurrentNic, new[] { dns01, dns02 }, restart: true);
RefreshDNSValues();
}
public static bool IsValidIPv4(string value)
{
// First check to see if there are at least three periods in the value
if (value.Count(x => x == '.') != 3)
return false;
IPAddress address;
return IPAddress.TryParse(value, out address) && address.AddressFamily == AddressFamily.InterNetwork;
}
private void btnOpenConnectionList_Click(object sender, EventArgs e)
{
// Open the network connections window
Process.Start("ncpa.cpl");
}
private void btnChooseDns_Click(object sender, EventArgs e)
{
// Invoke the context menu on left mouse as well as right, needs a work-around due to bugs with the menu
// not disappearing propertly when clicked outside of it, caching the method invocation first
this.ctxMenuChooseDns.Show(btnChooseDns, 10, 10);
}
private void ctxMenuItemEditJSON_Click(object sender, EventArgs e)
{
EditJSONFile();
}
private void EditJSONFile()
{
//Process.Start(new ProcessStartInfo("dns.json") { Verb = "edit" });
Process.Start("notepad", "dns.json");
}
private void ctxMenuItemReloadJSON_Click(object sender, EventArgs e)
{
ReloadContextMenuItems();
}
private void ReloadContextMenuItems()
{
try
{
var json = LoadJsonData("dns.json");
if (json == null)
return;
// Remove stuff from the context menu
ctxMenuChooseDns.Items.Clear();
foreach (var entry in json)
{
ctxMenuChooseDns.Items.Add(CreateSubMenu(entry));
}
// Add the fixed items at the end
ctxMenuChooseDns.Items.Add(ctxMenuItemSeparatorForReload);
ctxMenuChooseDns.Items.Add(ctxMenuItemAdvanced);
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
MessageBox.Show(this, "Error loading DNS information from dns.json: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private ToolStripMenuItem CreateSubMenu(DnsProvider entry)
{
var sub = new ToolStripMenuItem(entry.Title);
foreach (var server in entry.Servers)
{
var item = new ToolStripMenuItem(server.Title) { Tag = new Tuple<string, DnsServers>(""/*entry.IpUpdateUrl*/, server) };
item.Click += (sender, args) =>
{
var data = ((ToolStripMenuItem)sender)?.Tag as Tuple<string, DnsServers>;
if (data != null)
{
SetDnsTextBoxValues(data.Item2.Dns1, data.Item2.Dns2);
// If there is a url specified in the string tuple item then it is a dns update url
// which should be visited right now
}
};
sub.DropDownItems.Add(item);
}
if (!string.IsNullOrWhiteSpace(entry.Website) && Uri.IsWellFormedUriString(entry.Website, UriKind.Absolute))
{
// Add separator
sub.DropDownItems.Add(new ToolStripSeparator());
// Add website if available
var web = new ToolStripMenuItem("Website") { Tag = entry.Website };
web.Click += (sender, args) =>
{
var data = ((ToolStripMenuItem)sender)?.Tag as string;
if (data != null)
Process.Start(data); // TODO: Defensive coding around non URLs!!!!
};
sub.DropDownItems.Add(web);
}
return sub;
}
private List<DnsProvider> LoadJsonData(string jsonFilePath)
{
try
{
using (var sr = new StreamReader(jsonFilePath))
{
return JsonConvert.DeserializeObject<List<DnsProvider>>(sr.ReadToEnd());
}
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return null;
}
}
private void cmbNics_SelectedIndexChanged(object sender, EventArgs e)
{
CurrentNic = cmbNics.Text;
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using Alabo.Domains.Entities;
using Alabo.Domains.Repositories.Mongo.Extension;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson;
using Newtonsoft.Json;
namespace Alabo.Industry.Shop.Orders.Dtos
{
/// <summary>
/// 快递信息
/// </summary>
[Table("Order_Deliver")]
[ClassProperty(Name = "快递")]
public class Deliver : AggregateMongodbRoot<Deliver>
{
/// <summary>
/// 快递单号
/// </summary>
public string ExpressNum { get; set; }
/// <summary>
/// 快递识别号
/// </summary>
public string ExpressNo { get; set; }
/// <summary>
/// 快递公司
/// </summary>
public string ExpressName { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 订单Id
/// </summary>
public long OrderId { get; set; }
/// <summary>
/// 店铺Id
/// </summary>
[JsonConverter(typeof(ObjectIdConverter))] public ObjectId StoreId { get; set; }
/// <summary>
/// 用户Id
/// </summary>
public long UserId { get; set; }
/// <summary>
/// 收货姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 收货地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 地区id
/// </summary>
public long RegionId { get; set; }
}
} |
using System;
namespace DelegatesAndEvents
{
public class ExampleDelegates
{
public delegate int Comparison<in T>(T left, T right);
public Comparison<int> comparator;
public void CallDelegate(int a, int b)
{
comparator.Invoke(a, b);
}
/// <summary>
/// Delegate como parametro.
/// </summary>
/// <returns>The como parametro.</returns>
/// <param name="delegate">Delegate.</param>
private int DelegateComoParametro(Comparison<int> @delegate)
{
return @delegate.Invoke(2, 3);
}
public static void Run()
{
ExampleDelegates exampleDelegates = new ExampleDelegates();
exampleDelegates.comparator += (left, right) =>
{
var result = left + right;
Console.WriteLine(result);
return result;
};
exampleDelegates.comparator += (left, right) =>
{
var result = left * right;
Console.WriteLine(result);
return result;
};
exampleDelegates.CallDelegate(1, 2);
//Assert.Equal(460, DelegateComoParametro((a,b) => a + b));
//Assert.Equal(3, exampleDelegates.comparator(1, 2));
int[] inteiros = new int[] { 1, 2, 3, 4, 5 };
var number = Array.Find(inteiros, (int n) =>
{
return n == 3;
});
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.