text stringlengths 13 6.01M |
|---|
using Project_NotesDeFrais.Models;
using Project_NotesDeFrais.Models.Reposirery;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Project_NotesDeFrais.Controllers
{
public class EmployeesController : Controller
{
//add employer formulaire
[Authorize]
public ActionResult Index()
{
EmployeesModel empModel = new EmployeesModel();
EmployesRepositery empRp = new EmployesRepositery();
empModel.AspNetUsersList = empRp.getAllUsers().ToList();
empModel.polesList = empRp.getAllPoles().ToList();
if (empRp.getAllUsers().ToList().Count() == 0)
{
ViewData["erreur"] = "Utilisateurs et des Poles ";
return View("ErrorEmptyElement");
}
return View("EmployesFormulaire" , empModel);
}
//add employer to the database
[Authorize]
public ActionResult CreateEmploye(EmployeesModel empModel)
{
EmployesRepositery empRp = new EmployesRepositery();
Employees emp = new Employees();
if (!ModelState.IsValidField("FirstName") || !ModelState.IsValidField("LastName") ||
!ModelState.IsValidField("Email") || !ModelState.IsValidField("Telephone"))
{
empModel.AspNetUsersList = empRp.getAllUsers().ToList();
empModel.polesList = empRp.getAllPoles().ToList();
return View("EmployesFormulaire",empModel);
}
emp.Employee_ID = Guid.NewGuid();
String userUmail = Convert.ToString(Request.Form["userList"]);
emp.User_ID = empRp.getUserByMail(userUmail);
if (empRp.getAllPoles().ToList().Count() == 0)
{
emp.Pole_ID = null;
}
else {
emp.Pole_ID = new Guid(Convert.ToString(Request.Form["poleList"]));
}
emp.FirstName = Convert.ToString(Request.Form["FirstName"]);
emp.LastName = Convert.ToString(Request.Form["LastName"]);
emp.Email= Convert.ToString(Request.Form["Email"]);
emp.Telephone = Convert.ToString(Request.Form["Telephone"]);
empRp.AddEmployes(emp);
return RedirectToAction("AllEmployees");
}
//get all employer from database
[Authorize]
public ActionResult AllEmployees(int? pageIndex)
{
var countElementPage = 10;
EmployesRepositery empRp = new EmployesRepositery();
AspNetUsers user = new AspNetUsers();
PolesRepository poleRepo = new PolesRepository();
var employers = empRp.allEmployees();
if (employers.Count() == 0)
{
ViewData["erreurMessage"] = "Aucun employer !";
ViewData["create"] = "false";
return View("ErrorEmptyList");
}
List<EmployeesModel> employersModel = new List<EmployeesModel>();
foreach (var emp in employers)
{
EmployeesModel empModel = new EmployeesModel();
empModel.Email = emp.Email;
empModel.Employee_ID = emp.Employee_ID;
empModel.FirstName = emp.FirstName;
empModel.LastName = emp.LastName;
empModel.Telephone = emp.Telephone;
empModel.User_ID = emp.User_ID;
empModel.AspNetUsers = empRp.getUserById(emp.User_ID);
if (emp.Poles == null)
{
PolesModel pole = new PolesModel();
pole.Name = "inconnu";
empModel.Poles = pole;
}
else {
PolesModel pole = new PolesModel();
pole.Pole_ID = emp.Poles.Pole_ID;
pole.Name = emp.Poles.Name;
empModel.Poles = pole;
}
employersModel.Add(empModel);
}
IQueryable<EmployeesModel> listEmp = employersModel.AsQueryable();
PaginatedList<EmployeesModel> lst = new PaginatedList<EmployeesModel>(listEmp, pageIndex, countElementPage);
return View("AllEmployes", lst);
}
//searche some employer in the database by name
[Authorize]
public ActionResult Searche(int? pageIndex , String query)
{
var countElementPage = 10;
EmployesRepositery empRp = new EmployesRepositery();
AspNetUsers user = new AspNetUsers();
PolesModel pole = new PolesModel();
var employers = empRp.getSerachingemployees(query);
List<EmployeesModel> employersModel = new List<EmployeesModel>();
foreach (var emp in employers)
{
var polId = emp.Pole_ID != null ? emp.Pole_ID : null;
EmployeesModel empModel = new EmployeesModel();
empModel.Email = emp.Email;
empModel.Employee_ID = emp.Employee_ID;
empModel.FirstName = emp.FirstName;
empModel.LastName = emp.LastName;
empModel.Telephone = emp.Telephone;
empModel.User_ID = emp.User_ID;
empModel.Pole_ID = emp.Pole_ID;
empModel.AspNetUsers = empRp.getUserById(emp.User_ID);
empModel.Poles.Name = empRp.getPoleById(emp.Pole_ID).Name;
employersModel.Add(empModel);
}
IQueryable<EmployeesModel> listEmp = employersModel.AsQueryable();
PaginatedList<EmployeesModel> lst = new PaginatedList<EmployeesModel>(listEmp, pageIndex, countElementPage);
return View("Allmployes", lst);
}
//select user to add to the employer
[Authorize]
public ActionResult createUserRole()
{
EmployeesModel empModel = new EmployeesModel();
EmployesRepositery empRp = new EmployesRepositery();
empModel.AspNetUsersList = empRp.getAllUsers().ToList();
empModel.polesList = empRp.getAllPoles().ToList();
return View("EmployesFormulaire", empModel);
}
[Authorize]
public ActionResult CreateUserRoles(EmployeesModel empModel)
{
EmployesRepositery empRp = new EmployesRepositery();
Employees emp = new Employees();
if (!ModelState.IsValidField("FirstName") || !ModelState.IsValidField("LastName") ||
!ModelState.IsValidField("Email") || !ModelState.IsValidField("Telephone"))
{
empModel.AspNetUsersList = empRp.getAllUsers().ToList();
empModel.polesList = empRp.getAllPoles().ToList();
return View("EmployesFormulaire", empModel);
}
emp.Employee_ID = Guid.NewGuid();
String userUmail = Convert.ToString(Request.Form["userList"]);
String userName = Convert.ToString(Request.Form["polesList"]);
emp.User_ID = empRp.getUserByMail(userUmail);
emp.Pole_ID = empRp.getPoleByName(userName);
emp.FirstName = Convert.ToString(Request.Form["FirstName"]);
emp.LastName = Convert.ToString(Request.Form["LastName"]);
emp.Email = Convert.ToString(Request.Form["Email"]);
emp.Telephone = Convert.ToString(Request.Form["Telephone"]);
empRp.AddEmployes(emp);
return RedirectToAction("AllEmployees");
}
//show popup to confirm delete employer
[Authorize]
public ActionResult confirmDelete(Guid id)
{
ViewData["confirmDelete"] = "/Employees/AllEmployees";
return PartialView("_confirmDelet");
}
}
} |
namespace Contoso.Parameters.Expressions
{
public class GreaterThanOrEqualsBinaryOperatorParameters : BinaryOperatorParameters
{
public GreaterThanOrEqualsBinaryOperatorParameters()
{
}
public GreaterThanOrEqualsBinaryOperatorParameters(IExpressionParameter left, IExpressionParameter right) : base(left, right)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AulaReposicao
{
abstract class Conta
{
public static double cotacaoDolar = 3.0;
public int saldo = 0;
public Conta(int saldo)
{
this.saldo = saldo;
}
public virtual string GerarExtrato()
{
return "";
}
public virtual string GerarExtrato(String mes)
{
return "";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MyCore
{
public class Rotater : MonoBehaviour
{
[SerializeField]float m_rotateSpeed;
[SerializeField] Vector3 m_rotateAxis;
public float rotateSpeed { get { return m_rotateSpeed; } set { m_rotateSpeed = value; } }
public Vector3 rotateAxis { get { return m_rotateAxis; } set { m_rotateAxis = value; } }
private void Update()
{
transform.Rotate(m_rotateAxis * m_rotateSpeed * Time.deltaTime);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CheckPwd
{
class Program
{
static void Main(string[] args)
{
string sPassword;
//Console.WriteLine("请输入一个密码:");
//sPassword = Console.ReadLine();
sPassword = args[0];
switch (CheckPassword.PasswordStrength(sPassword))
{
case Strength.Invalid: Console.WriteLine("false\n"); break;
case Strength.Weak: Console.WriteLine("false\n"); break;
case Strength.Normal: Console.WriteLine("false\n"); break;
case Strength.Strong: Console.WriteLine("false\n"); break;
case Strength.Valid: Console.WriteLine("true\n"); break;
}
}
}
}
|
using System.Collections.Generic;
namespace Alarmy.Common
{
internal class AlarmEqualityComparer : IEqualityComparer<IAlarm>
{
public bool Equals(IAlarm x, IAlarm y)
{
return x != null && y != null &&
object.Equals(x.Status, y.Status) &&
object.Equals(x.Time, y.Time) &&
object.Equals(x.Title, y.Title) &&
object.Equals(x.IsHushed, y.IsHushed);
}
public int GetHashCode(IAlarm obj)
{
return obj.Status.GetHashCode() ^ obj.Time.GetHashCode() ^ obj.Title.GetHashCode() ^ obj.IsHushed.GetHashCode();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastSQL.Core.UI.Interfaces
{
public interface IPageManager
{
string Id { get; }
string Name { get; }
string Description { get; }
IPageManager Apply();
}
}
|
namespace PriorityQueueImplementation
{
public enum PriorityQueueOrder
{
MaxPriority,
MinPriority
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
using System.IO;
using Excel;
public class DoExcel {
public static DataSet ReadExcel(string path)
{
Debug.Log(path);
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
Debug.Log(excelReader.ResultsCount);
return result;
}
public static List<DepenceTableData> Load(string path)
{
List<DepenceTableData> _data = new List<DepenceTableData>();
DataSet resultds = ReadExcel(path);
int column = resultds.Tables[0].Columns.Count;
int row = resultds.Tables[0].Rows.Count;
Debug.LogWarning(column + " " + row);
for(int i=1;i<row;i++)
{
DepenceTableData temp_data;
temp_data.instruct = resultds.Tables[0].Rows[i][0].ToString();
temp_data.word = resultds.Tables[0].Rows[i][1].ToString();
temp_data.winstruct = resultds.Tables[0].Rows[i][2].ToString();
temp_data.wword = resultds.Tables[0].Rows[i][3].ToString();
Debug.Log(temp_data.instruct + " " + temp_data.word + " " + temp_data.winstruct + " " + temp_data.wword);
_data.Add(temp_data);
}
return _data;
}
}
public struct DepenceTableData
{
public string word;
public string instruct;
public string wword;
public string winstruct;
}
|
//Write a method that calculates the number of workdays between today and given date, passed as parameter. Consider that workdays are all days from Monday to Friday except a fixed list of public holidays specified preliminary as array.
using System;
class WorkDays
{
public static void CalcHolidays(DateTime date, out int days, out int holidays)
{
DateTime dateToday = DateTime.Today;
int currentYear = DateTime.Today.Year;
holidays = 0;
days = 0;
//array with holidays
DateTime[] hdays =
{
new DateTime(currentYear, 1, 1),
new DateTime(currentYear, 3, 3),
new DateTime(currentYear, 5, 1),
new DateTime(currentYear, 5, 2),
new DateTime(currentYear, 5, 6),
new DateTime(currentYear, 5, 24),
new DateTime(currentYear, 9, 22),
new DateTime(currentYear, 12, 24),
new DateTime(currentYear, 12, 25),
new DateTime(currentYear, 12, 26),
new DateTime(currentYear, 12, 31)
};
while (dateToday <= date)
{
if (dateToday.DayOfWeek == DayOfWeek.Saturday || dateToday.DayOfWeek == DayOfWeek.Sunday)
{
holidays++;
}
else
{
foreach (var element in hdays)
{
if (element.DayOfYear == dateToday.DayOfYear)
{
holidays++;
}
}
}
days++;
dateToday = dateToday.AddDays(1);
}
}
static void Main()
{
DateTime date2;
int days = 0;
int holidays = 0;
do
{
Console.WriteLine("Please, enter the final date in the following format: dd mm yyyy: ");
date2 = DateTime.Parse(Console.ReadLine());
} while (date2 < DateTime.Today);
CalcHolidays(date2, out days, out holidays);
Console.WriteLine("{0} days in the time interval", days);
Console.WriteLine("{0} holidays in the time interval", holidays);
Console.WriteLine("{0} workdays in the time interval", days - holidays);
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using PlayTennis.Bll;
using PlayTennis.Model;
using PlayTennis.Model.Dto;
using PlayTennis.Utility;
namespace PlayTennis.WebApi
{
public class LogRequestMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var rLog = MapperHelper.MyMapper.Map<RequestLog>(request);
if (request.Content.Headers.ContentLength > 0 && request.Content.Headers.ContentLength < 1024)
{
var stream = new MemoryStream();
await request.Content.CopyToAsync(stream);
StreamReader reader = new StreamReader(stream);
stream.Position = 0;
string text = reader.ReadToEnd();
rLog.HttpContent = text;
}
// Call the inner handler.
// 调用内部处理器。
var response = await base.SendAsync(request, cancellationToken);
var resp = MapperHelper.MyMapper.Map<ResponseLog>(response);
//记录每次的请求(返回
var logService = new LogService();
var log = new LogHttpRequest()
{
Requst = JsonConvert.SerializeObject(rLog),
Response = JsonConvert.SerializeObject(resp),
};
logService.LogHttpResquestAsync(log);
return response;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Entidades
{
public class factura
{
public int ID_FACTURAS { get; set; }
public int ID_CLIENTE { get; set; }
public int ID_PRODUCTO { get; set; }
public int ID_VENDEDOR { get; set; }
public float SALDOINICIAL { get; set; }
public float SALDOFINAL { get; set; }
public List<facturadetalle> FACTURADETALLE { get; set; }
public factura()
{
FACTURADETALLE = new List<facturadetalle>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace NetFabric.Hyperlinq
{
public static partial class ValueEnumerableExtensions
{
public static bool Any<TEnumerable, TEnumerator, TSource>(this TEnumerable source)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
{
using var enumerator = source.GetEnumerator();
return enumerator.MoveNext();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Any<TEnumerable, TEnumerator, TSource>(this TEnumerable source, Func<TSource, bool> predicate)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
=> source.Any<TEnumerable, TEnumerator, TSource, FunctionWrapper<TSource, bool>>(new FunctionWrapper<TSource, bool>(predicate));
public static bool Any<TEnumerable, TEnumerator, TSource, TPredicate>(this TEnumerable source, TPredicate predicate = default)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
where TPredicate : struct, IFunction<TSource, bool>
{
using var enumerator = source.GetEnumerator();
while (enumerator.MoveNext())
{
if (predicate.Invoke(enumerator.Current))
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Any<TEnumerable, TEnumerator, TSource>(this TEnumerable source, Func<TSource, int, bool> predicate)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
=> source.AnyAt<TEnumerable, TEnumerator, TSource, FunctionWrapper<TSource, int, bool>>(new FunctionWrapper<TSource, int, bool>(predicate));
public static bool AnyAt<TEnumerable, TEnumerator, TSource, TPredicate>(this TEnumerable source, TPredicate predicate = default)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
where TPredicate : struct, IFunction<TSource, int, bool>
{
using var enumerator = source.GetEnumerator();
checked
{
for (var index = 0; enumerator.MoveNext(); index++)
{
if (predicate.Invoke(enumerator.Current, index))
return true;
}
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace LegoDimensions.Models
{
public class Pack
{
public int ID {get; set;}
public int PackID { get; set; }
public string PackName { get; set; }
public string PackType { get; set; }
public double Wave { get; set; }
[NotMapped]
public ICollection<int> CharacterList { get; set; }
public string CharacterIDs
{
get { return string.Join(",", CharacterList); }
set { CharacterList = value.Split(',').Select(Int32.Parse).ToList(); }
}
}
} |
using SprintFour.HUD;
namespace SprintFour.Commands
{
public class DownPressedCommand : ICommand
{
public void Execute()
{
if(SprintFourGame.GetInstance().CurrentGameState == SprintFourGame.GameState.HighScore) HighScore.DownPressed();
else SprintFourGame.GetInstance().Mario.CurrentState.DownPressed();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrbaCommerce.Modelo;
using FrbaCommerce.Conexion;
using System.Data.SqlClient;
using System.Data;
namespace FrbaCommerce.DAO
{
class DaoVisibilidad
{
public DaoVisibilidad() { }
static public Visibilidad getVisibilidad(Decimal p_idVisibilidad)
{
String query = "SELECT * FROM DD.visibilidad " +
"where id_visibilidad = " + p_idVisibilidad + "%' ";
SqlConnection conn = DBConexion.getConn();
SqlCommand sql = new SqlCommand(query, conn);
SqlDataReader rs = sql.ExecuteReader();
Visibilidad visibilidad = new Visibilidad();
while (rs.Read())
{
if (!rs.IsDBNull(0))
{
visibilidad.idVisibilidad = rs.GetDecimal(rs.GetOrdinal("id_visibilidad"));
visibilidad.codigo = rs.GetDecimal(rs.GetOrdinal("codigo"));
visibilidad.descripcion = rs.GetString(rs.GetOrdinal("descripcion"));
visibilidad.porcentaje = rs.GetDecimal(rs.GetOrdinal("precio"));
visibilidad.precio = rs.GetDecimal(rs.GetOrdinal("porcentaje"));
visibilidad.cantidadDias = rs.GetDecimal(rs.GetOrdinal("cant_dias"));
}
}
conn.Close();
return visibilidad;
}
static public List<Visibilidad> getVisibilidades(String p_codigo, String p_descripcion)
{
List<Visibilidad> visibilidades = new List<Visibilidad>();
String query = "";
// codigo descripcion
if ((p_codigo == null || p_codigo == "") && (p_descripcion == null || p_descripcion == ""))
{
query = "select * from DD.visibilidad";
}
else
{
//logica para construir la query
query = "SELECT * FROM DD.visibilidad " +
"where codigo like '%" + p_codigo + "%' " +
"and descripcion like '%" + p_descripcion + "%' ";
}
SqlConnection conn = DBConexion.getConn();
SqlCommand sql = new SqlCommand(query, conn);
SqlDataReader rs = sql.ExecuteReader();
while (rs.Read())
{
if (!rs.IsDBNull(0))
{
Visibilidad visibilidad = new Visibilidad();
visibilidad.idVisibilidad= rs.GetDecimal(rs.GetOrdinal("id_visibilidad"));
visibilidad.codigo = rs.GetDecimal(rs.GetOrdinal("codigo"));
visibilidad.descripcion = rs.GetString(rs.GetOrdinal("descripcion"));
visibilidad.porcentaje = rs.GetDecimal(rs.GetOrdinal("precio"));
visibilidad.precio = rs.GetDecimal(rs.GetOrdinal("porcentaje"));
visibilidad.cantidadDias = rs.GetDecimal(rs.GetOrdinal("cant_dias"));
visibilidades.Add(visibilidad);
}
}
conn.Close();
return visibilidades;
}
static public List<Visibilidad> getAllVisibilidades() {
return getVisibilidades(null, null);
}
static public void persistir(Visibilidad visibilidad)
{
if (visibilidad.idVisibilidad == 0)
{
insertVisibilidad(visibilidad);
}
else {
updateVisibilidad(visibilidad);
}
}
private static void updateVisibilidad(Visibilidad visibilidad)
{
String sql =
"update DD.visibilidad " +
"set codigo = '" + visibilidad.codigo + "', " +
"descripcion = '" + visibilidad.descripcion + "', " +
"precio = '" + visibilidad.precio + "', " +
"porcentaje = '" + visibilidad.porcentaje + "', " +
"cant_dias = '" + visibilidad.cantidadDias + "' " +
"where id_visibilidad = " + visibilidad.idVisibilidad;
SqlConnection conn = DBConexion.getConn();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
;
}
private static Decimal getProximoIdVisibilidad()
{
String query = "select isnull((select MAX(id_visibilidad)+1), 1) as id_visibilidad from DD.visibilidad";
SqlConnection conn = DBConexion.getConn();
SqlCommand sql = new SqlCommand(query, conn);
SqlDataReader rs = sql.ExecuteReader();
Decimal idVisibilidad = 0;
while (rs.Read())
{
if (!rs.IsDBNull(0))
{
idVisibilidad = rs.GetInt32(rs.GetOrdinal("id_visibilidad"));
}
}
conn.Close();
return idVisibilidad;
}
private static void insertVisibilidad(Visibilidad visibilidad)
{
Decimal nuevoIdVisibilidad = getProximoIdVisibilidad();
String sql =
"insert into DD.visibilidad " +
"(id_visibilidad, codigo, descripcion, " +
"precio, porcentaje, cant_dias) " +
"values " +
nuevoIdVisibilidad + ", " +
visibilidad.codigo + ", '" +
visibilidad.descripcion + "', '" +
visibilidad.precio + "', '" +
visibilidad.porcentaje + "', '" +
visibilidad.cantidadDias+ "')";
SqlConnection conn = DBConexion.getConn();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
internal static void eliminar(Visibilidad visibilidad)
{
String sql =
"delete from DD.visibilidad " +
"where id_visibilidad = " + visibilidad.idVisibilidad;
SqlConnection conn = DBConexion.getConn();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Session;
using Microsoft.PowerShell.EditorServices.Test.Console;
using System;
using System.IO;
using Microsoft.PowerShell.EditorServices.Utility;
using Microsoft.PowerShell.EditorServices.Console;
using System.Threading;
using System.Threading.Tasks;
using System.Management.Automation.Host;
namespace Microsoft.PowerShell.EditorServices.Test
{
internal static class PowerShellContextFactory
{
public static PowerShellContext Create(ILogger logger)
{
PowerShellContext powerShellContext = new PowerShellContext(logger, isPSReadLineEnabled: false);
powerShellContext.Initialize(
PowerShellContextTests.TestProfilePaths,
PowerShellContext.CreateRunspace(
PowerShellContextTests.TestHostDetails,
powerShellContext,
new TestPSHostUserInterface(powerShellContext, logger),
logger),
true);
return powerShellContext;
}
}
public class TestPSHostUserInterface : EditorServicesPSHostUserInterface
{
public TestPSHostUserInterface(
PowerShellContext powerShellContext,
ILogger logger)
: base(
powerShellContext,
new SimplePSHostRawUserInterface(logger),
Logging.NullLogger)
{
}
public override void WriteOutput(string outputString, bool includeNewLine, OutputType outputType, ConsoleColor foregroundColor, ConsoleColor backgroundColor)
{
}
protected override ChoicePromptHandler OnCreateChoicePromptHandler()
{
throw new NotImplementedException();
}
protected override InputPromptHandler OnCreateInputPromptHandler()
{
throw new NotImplementedException();
}
protected override Task<string> ReadCommandLineAsync(CancellationToken cancellationToken)
{
return Task.FromResult("USER COMMAND");
}
protected override void UpdateProgress(long sourceId, ProgressDetails progressDetails)
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using Powerups;
using UnityEditor;
using UnityEngine;
using Random = UnityEngine.Random;
public class Enemy : MonoBehaviour {
[SerializeField] private int _scoreValue = 10;
[SerializeField] public float _speed = 4.0f;
private bool _isAlive = true;
private Vector3 direction = Vector3.down;
private Player _player;
private Animator _animator;
[SerializeField] private GameObject _projectilePrefab;
private AudioSource _audioSource;
[SerializeField] private AudioClip _projectileAudioClip;
[SerializeField] private AudioClip _explosionAudioClip;
[SerializeField] private float _fastestFireRate = 3.0f;
[SerializeField] private float _slowestRate = 7.0f;
private void Start() {
_player = GameObject.Find("Player").GetComponent<Player>();
if (_player == null) {
Debug.LogError("Failed to find player.");
}
_animator = GetComponent<Animator>();
if (_animator == null) {
Debug.LogError("Failed to find animator component.");
}
_audioSource = GetComponent<AudioSource>();
if (_audioSource == null) {
Debug.LogError("Failed to find audio source component.");
}
StartCoroutine(ShootProjectile());
}
void Update() {
HandleMovement();
}
private void OnTriggerEnter2D(Collider2D other) {
if (other.transform.CompareTag("Player")) {
_isAlive = false;
StopCoroutine(nameof(ShootProjectile));
var player = other.GetComponent<Player>();
if (player != null) {
player.Damage();
}
if (_animator != null) {
_animator.SetTrigger("OnEnemyDeath");
}
_speed = 0f;
GetComponent<BoxCollider2D>().enabled = false;
_audioSource.PlayOneShot(_explosionAudioClip);
Destroy(gameObject, 2.3f);
} else if (other.transform.CompareTag("Projectile")) {
_isAlive = false;
StopCoroutine(nameof(ShootProjectile));
Destroy(other.gameObject);
if (_animator != null) {
_animator.SetTrigger("OnEnemyDeath");
}
if (_player != null) {
_player.AddScore(_scoreValue);
}
_speed = 0f;
GetComponent<BoxCollider2D>().enabled = false;
_audioSource.PlayOneShot(_explosionAudioClip);
Destroy(gameObject, 2.3f);
}
}
IEnumerator ShootProjectile() {
yield return new WaitForSeconds(1f);
while (_isAlive) {
Instantiate(_projectilePrefab, transform.position, Quaternion.identity);
_audioSource.PlayOneShot(_projectileAudioClip);
yield return new WaitForSeconds(Random.Range(_fastestFireRate, _slowestRate));
}
}
void HandleMovement() {
transform.Translate(direction * (_speed * Time.deltaTime));
CheckBoundaries();
}
void CheckBoundaries() {
if (transform.position.y < -10.0f) {
transform.position = new Vector3(Random.Range(-9.0f, 9.0f), 8.0f, transform.position.z);
}
}
}
|
using System;
using System.Collections.Generic;
using SubSonic.BaseClasses;
using SubSonic.Extensions;
using SubSonic.SqlGeneration.Schema;
namespace Pes.Core
{
[SubSonicTableNameOverride("SystemObjects")]
public partial class SystemObject : EntityBase<SystemObject>
{
#region Properties
public override object Id
{
get { return SystemObjectID; }
set { SystemObjectID = (int)value; }
}
[SubSonicPrimaryKey]
public int SystemObjectID { get; set; }
public System.Data.Linq.Binary Timestamp { get; set; }
public string Name { get; set; }
#endregion
public SystemObject()
{
}
public SystemObject(object id)
{
if (id != null)
{
SystemObject entity = Single(id);
if (entity != null)
entity.CopyTo<SystemObject>(this);
else
this.SystemObjectID = 0;
}
}
public bool Save()
{
bool rs = false;
if (SystemObjectID > 0)
rs = Update(this) > 0;
else
rs = Add(this) != null;
return rs;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Tsu.MVVM
{
/// <summary>
/// Implements a few utility functions for a ViewModel base
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>
/// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and
/// also sets the value of the field)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="newValue"></param>
/// <param name="propertyName"></param>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void SetField<T> ( ref T field, T newValue, [CallerMemberName] String propertyName = null )
{
if ( EqualityComparer<T>.Default.Equals ( field, newValue ) )
return;
field = newValue;
this.OnPropertyChanged ( propertyName );
}
/// <summary>
/// Invokes <see cref="PropertyChanged"/>
/// </summary>
/// <param name="propertyName"></param>
/// <exception cref="ArgumentNullException">
/// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't
/// auto-filled by the compiler)
/// </exception>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void OnPropertyChanged ( [CallerMemberName] String propertyName = null ) =>
this.PropertyChanged?.Invoke (
this,
new PropertyChangedEventArgs ( propertyName ?? throw new ArgumentNullException ( nameof ( propertyName ) ) ) );
}
} |
using AutoMapper;
using DEMO_DDD.APPLICATION.Interfaces;
using DEMO_DDD.DOMAIN.Entidades;
using DEMO_DDD.DOMAIN.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace DEMO_DDD.APPLICATION.Services
{
public class AppServiceBase<TEntity> : IDisposable, IAppServiceBase<TEntity> where TEntity : Entity
{
private readonly IServiceBase<TEntity> _serviceBase;
public AppServiceBase(IServiceBase<TEntity> serviceBase)
{
_serviceBase = serviceBase;
}
public async Task Adcionar(TEntity entity)
{
await _serviceBase.Adcionar(entity);
}
public async Task Atualizar(TEntity entity)
{
await _serviceBase.Atualizar(entity);
}
public async Task<IEnumerable<TEntity>> Buscar(Expression<Func<TEntity, bool>> predicate)
{
return await _serviceBase.Buscar(predicate);
}
public Task<TEntity> ObetrPorId(int id)
{
return _serviceBase.ObetrPorId(id);
}
public async Task<IEnumerable<TEntity>> ObterTodos()
{
return await _serviceBase.ObterTodos();
}
public async Task Remover(int id)
{
await _serviceBase.Remover(id);
}
public void Dispose()
{
_serviceBase?.Dispose();
}
}
}
|
using HardwareInventoryManager.Models;
using System;
using System.Collections.Generic;
using System.Web;
namespace HardwareInventoryManager.ViewModels
{
public class BulkUploadViewModel
{
public string BatchId { get; set; }
public IEnumerable<AssetViewModel> Assets { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public IEnumerable<List<string>> Errors { get; set; }
public IEnumerable<TenantViewModel> Tenants { get; set; }
public TenantViewModel SelectedTenant { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace netfx
{
class effects
{
public Blur CustomBlur = new Blur(); //the use in Form1.cs for example: "layer1 = effects.CustomBlur.Gaussain(layer1, 10);"
BitmapW convolve(BitmapW image, float[,] kernel, int kw, int kh)
{
BitmapW temp = image.Clone();
// int kh = kernel;
//int kw = kh; //kernel[0].Length / 2;
int i = 0, j = 0, n = 0, m = 0, cr, cg, cb, ca,
h = image.Height(),
w = image.Width();
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++)
{
//kernel loop
float r = 0, g = 0, b = 0, a = 0;
for (n = -kh; n <= kh; n++)
{
for (m = -kw; m <= kw; m++)
{
if (i + n >= 0 && i + n < h)
{
if (j + m >= 0 && j + m < w)
{
float f = kernel[m + kw, n + kh];
if (f == 0) { continue; }
Color colortemp = image.GetPixel(j + m, i + n);
cr = colortemp.R; cg = colortemp.G; cb = colortemp.B; ca = colortemp.A;
r += cr * f;
g += cg * f;
b += cb * f;
a += ca * f;
}
}
}
}
//kernel loop end
temp.SetPixel(j, i, Color.FromArgb((int)Util.clamp(a, 0, 255), (int)Util.clamp(r, 0, 255), (int)Util.clamp(g, 0, 255), (int)Util.clamp(b, 0, 255)));
}
}
return temp;
}
/// <summary>
/// #### Adjust [-255,255 for each channel]
/// </summary>
/// <param name="image"></param>
/// <param name="pr"></param>
/// <param name="pg"></param>
/// <param name="pb"></param>
/// <param name="pa"></param>
/// <returns></returns>
public BitmapW adjust(BitmapW image, float pr, float pg, float pb, float pa)
{
float cr = 0, cg = 0, cb = 0, ca = 0;
pr /= 100; pg /= 100; pb /= 100; pa /= 100;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
if (pr > 0) cr += (255 - cr) * pr; else cr -= cr * Math.Abs(pr);
if (pg > 0) cg += (255 - cg) * pg; else cg -= cg * Math.Abs(pg);
if (pb > 0) cb += (255 - cb) * pb; else cb -= cb * Math.Abs(pb);
if (pa > 0) ca += (255 - ca) * pa; else ca -= ca * Math.Abs(pa);
/*
cr *= (1.0f + pr);
cg *= (1.0f + pg);
cb *= (1.0f + pb);
ca *= (1.0f + ca);
*/
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255), (int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Brighten [-100, 100]
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW brighten(BitmapW image, float p)
{
p = Util.normalize(p, -255, 255, -100, 100);
float cr = 0, cg = 0, cb = 0, ca = 0;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr += (p);
cg += (p);
cb += (p);
ca += (p);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255), (int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Alpha [-100, 100]
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW alpha(BitmapW image, float p)
{
p = Util.normalize(p, 0, 255, -100, 100);
float cr = 0, cg = 0, cb = 0, ca =0;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
ca = (p);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Saturate [-100, 100]
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW saturate(BitmapW image, float p)
{
p = Util.normalize(p, 0, 2, -100, 100);
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
float avg = (cr + cg + cb) / 3;
cr = avg + p * (cr - avg);
cg = avg + p * (cg - avg);
cb = avg + p * (cb - avg);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Invert
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public BitmapW invert(BitmapW image)
{
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr = 255 - cr;
cg = 255 - cg;
cb = 255 - cb;
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Posterize [1, 255]
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW posterize(BitmapW image, float p)
{
p = Util.clamp(p, 1, 255);
int step = (int)Math.Floor(255 / p);
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr = (float)Math.Floor(cr / (float)(step)) * step;
cg = (float)Math.Floor(cg / (float)(step)) * step;
cb = (float)Math.Floor(cb / (float)(step)) * step;
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Gamma [-100, 100]
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW gamma(BitmapW image, float p)
{
p = Util.normalize(p, 0, 2, -100, 100);
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr = (float)Math.Pow(cr, p);
cg = (float)Math.Pow(cg, p);
cb = (float)Math.Pow(cb, p);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
float contrastc(float f, float c) { return (f - 0.5f) * c + 0.5f; }
/// <summary>
/// #### Constrast [-100, 100]
/// </summary>
/// <param name="f"></param>
/// <param name="c"></param>
/// <returns></returns>
public BitmapW contrast(BitmapW image, float p)
{
p = Util.normalize(p, 0, 2, -100, 100);
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr = 255 * contrastc(cr / 255, p);
cg = 255 * contrastc(cg / 255, p);
cb = 255 * contrastc(cb / 255, p);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Sepia
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public BitmapW sepia(BitmapW image)
{
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
float tcr = cr, tcg = cg, tcb = cb;
cr = (tcr * 0.393f) + (tcg * 0.769f) + (tcb * 0.189f);
cg = (tcr * 0.349f) + (tcg * 0.686f) + (tcb * 0.168f);
cb = (tcr * 0.272f) + (tcg * 0.534f) + (tcb * 0.131f);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Subtract [No Range]
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public BitmapW subtract(BitmapW image)
{
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr -= cr;
cg -= cg;
cb -= cb;
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Fill [No Range]
/// </summary>
/// <param name="image"></param>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
public BitmapW fill(BitmapW image, int r, int g, int b)
{
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr = r;
cg = g;
cb = b;
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Blur ['simple', 'gaussian']
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW blur(BitmapW image, string p)
{
BitmapW result;
if (p == "simple")
{
result = convolve(image, new float[,]{
{1.0f/9, 1.0f/9, 1.0f/9},
{1.0f/9, 1.0f/9, 1.0f/9},
{1.0f/9, 1.0f/9, 1.0f/9}
}, 1, 1
);
}
else //gaussian
{
result = convolve(image, new float[,]{
{1.0f/273, 4.0f/273, 7.0f/273, 4.0f/273, 1.0f/273},
{4.0f/273, 16.0f/273, 26.0f/273, 16.0f/273, 4.0f/273},
{7.0f/273, 26.0f/273, 41.0f/273, 26.0f/273, 7.0f/273},
{4.0f/273, 16.0f/273, 26.0f/273, 16.0f/273, 4.0f/273},
{1.0f/273, 4.0f/273, 7.0f/273, 4.0f/273, 1.0f/273}
}, 2, 2);
}
return result;
}
/// <summary>
/// #### Sharpen
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public BitmapW sharpen(BitmapW image)
{
BitmapW result;
result = convolve(image, new float[,]{
{0.0f, -0.2f, 0.0f},
{-0.2f, 1.8f, -0.2f},
{0.0f, -0.2f, 0.0f}
}, 1, 1
);
return result;
}
BitmapW curves(BitmapW image, Point s, Point c1, Point c2, Point e)
{
Util.Bezier bezier = new Util.Bezier(s, c1, c2, e);
int[] points = bezier.genColorTable();
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
cr = points[(int)cr];
cg = points[(int)cg];
cb = points[(int)cb];
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
/// <summary>
/// #### Expose [-100, 100]
/// </summary>
/// <param name="image"></param>
/// <param name="p"></param>
/// <returns></returns>
public BitmapW expose(BitmapW image, float p)
{
p = Util.normalize(p, -1, 1, -100, 100);
Point c1 = new Point(0, (int)(255 * p));
Point c2 = new Point((int)(255 - (255 * p)), 255);
return curves(image, new Point(0, 0), c1, c2, new Point(255, 255));
}
/// <summary>
/// #### Vignette
/// (red,green,blue) of the vignette effect to apply
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public BitmapW vignette(BitmapW image, int r, int g, int b)
{
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width(),
centerw = w / 2,
centerh = h / 2,
maxdist = dist(0, 0, centerw, centerh);
maxdist = (int)(maxdist*0.6f);
int radius = maxdist / 2;
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
int distance = dist(i, j, centerw, centerh);
distance = (distance>radius)?distance-radius:0;
float ratio = ((distance / (float)(maxdist)));
cr = (1 - ratio) * cr + (ratio * r);
cg = (1 - ratio) * cg + (ratio * g);
cb = (1 - ratio) * cb + (ratio * b);
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
int dist(int x1, int y1, int x2, int y2)
{
return (int) Math.Sqrt((Math.Abs(x1-x2)*Math.Abs(x1-x2) + Math.Abs(y1-y2)*Math.Abs(y1-y2)));
//return approx_distance(Math.Abs(x1 - x2), Math.Abs(y1 - y2));
}
/*FAST APPROX OF DISTANCE
http://www.flipcode.com/archives/Fast_Approximate_Distance_Functions.shtml
*/
int approx_distance(int dx, int dy)
{
int min, max, approx;
if (dx < 0) dx = -dx;
if (dy < 0) dy = -dy;
if (dx < dy)
{
min = dx;
max = dy;
}
else
{
min = dy;
max = dx;
}
approx = (max * 1007) + (min * 441);
if (max < (min << 4))
approx -= (max * 40);
// add 512 for proper rounding
return ((approx + 512) >> 10);
}
/// <summary>
/// #### Noise [0 - 100]
/// </summary>
/// <param name="image"></param>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
public BitmapW noise(BitmapW image, int p)
{
int adjust = (int)(p * 2.55f);
Random rand = new Random(adjust);
int temprand = 0;
float cr = 0, cg = 0, cb = 0, ca;
int i = 0, j = 0,
h = image.Height(),
w = image.Width();
for (i = 0; i < w; i++)
{
for (j = 0; j < h; j++)
{
Color temp = image.GetPixel(i, j);
cr = temp.R; cg = temp.G; cb = temp.B; ca = temp.A;
temprand = rand.Next(adjust * -1, adjust);
cr += temprand;
cg += temprand;
cb += temprand;
image.SetPixel(i, j, Color.FromArgb((int)Util.clamp(ca, 0, 255), (int)Util.clamp(cr, 0, 255),
(int)Util.clamp(cg, 0, 255), (int)Util.clamp(cb, 0, 255)));
}
}
return image;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace HotelManagement
{
public partial class Report : Form
{
String connectionstring = ConfigurationManager.ConnectionStrings["Demo"].ToString();
SqlConnection connection = null;
SqlCommand command = null;
public Report()
{
//Load += Report_Load;
InitializeComponent();
//Tú Anh
connection = new SqlConnection(connectionstring);
namtb.Enabled = false;
}
//kiểm tra chuỗi có phải số
private void ChonBaoCao_Option_Click(object sender, EventArgs e)
{
try
{
//B1: tạo đối tưỡng kết nối với cơ sở dữ liệu và mở kết nối
connection = new SqlConnection(connectionstring);
connection.Open();
//B2: xây dụng câu lệnh sql để thực hiện chức năng mong muốn
String procname = "SP_RevenueReport ";
//B3: tạo đối tượng thực thi câu lệnh SQL
command = new SqlCommand(procname);
command.CommandType = CommandType.StoredProcedure;
command.Connection = connection;
//Truyền tham số vào proc
command.Parameters.Add("@option", SqlDbType.NVarChar);
command.Parameters.Add("@hotelname", SqlDbType.NVarChar);
command.Parameters.Add("@m", SqlDbType.Int);
command.Parameters.Add("@y", SqlDbType.Int);
//truyền giá trị cho tham số
if (thangcb.Checked && !namcb.Checked) //chọn thống kê theo tháng
command.Parameters["@option"].Value = "Tháng";
else if (!thangcb.Checked && namcb.Checked) //chọn thống kê theo năm
command.Parameters["@option"].Value = "Năm";
else if (thangcb.Checked && namcb.Checked) //chọn thóng kê theo tháng và năm
command.Parameters["@option"].Value = "Tháng, Năm";
command.Parameters["@hotelname"].Value = tenkstb.Text;
if (thangtb.Text != "") //tháng đúng định dạng là số vả khác null
command.Parameters["@m"].Value = Int32.Parse(thangtb.Text); //chuyển thàng Int vào truyền vào tham số m
else //nếu là null
command.Parameters["@m"].Value = DBNull.Value; //truyền vào giá trị null
//kiểm tra đk tháng có nghĩa
if (thangtb.Text != "" && Int32.Parse(thangtb.Text) > 12)
{
MessageBox.Show("Tháng không hợp lệ!!!");
return;
}
//tương tự như trên
if (namtb.Text != "")
command.Parameters["@y"].Value = Int32.Parse(namtb.Text);
else
command.Parameters["@y"].Value = DBNull.Value;
//đưa dữ liệu lên datagridview
DataTable table = new DataTable();
table.Columns.Add("Mã khách sạn", typeof(int));
table.Columns.Add("Tên khách sạn", typeof(String));
SqlDataReader reader = command.ExecuteReader();
DataRow row = null;
//tùy loại thống kê mà có bảng dử liệu trả về khác nhau
//dựa vào proc đã viết để xét các bảng dữ liệu trả về
if (thangcb.Checked && !namcb.Checked)
{
table.Columns.Add("Tháng", typeof(int));
table.Columns.Add("Doanh thu", typeof(decimal));
while (reader.Read())
{
row = table.NewRow();
row["Mã khách sạn"] = reader["maKS"];
row["Tên khách sạn"] = reader["tenKS"];
row["Tháng"] = reader["Thang"];
row["Doanh thu"] = reader["DoanhThu"];
table.Rows.Add(row);
}
}
else if (thangcb.Checked && namcb.Checked)//báo cáo theo tháng, năm
{
table.Columns.Add("Tháng", typeof(int));
table.Columns.Add("Năm", typeof(int));
table.Columns.Add("Doanh thu", typeof(decimal));
while (reader.Read())
{
row = table.NewRow();
row["Mã khách sạn"] = reader["maKS"];
row["Tên khách sạn"] = reader["tenKS"];
row["Tháng"] = reader["Thang"];
row["Năm"] = reader["Nam"];
row["Doanh thu"] = reader["DoanhThu"];
table.Rows.Add(row);
}
}
else //báo cáo theo năm
{
table.Columns.Add("Năm", typeof(int));
table.Columns.Add("Doanh thu", typeof(decimal));
while (reader.Read())
{
row = table.NewRow();
row["Mã khách sạn"] = reader["maKS"];
row["Tên khách sạn"] = reader["tenKS"];
row["Năm"] = reader["Nam"];
row["Doanh thu"] = reader["DoanhThu"];
table.Rows.Add(row);
}
}
reader.Close();
danhsachbaocao.DataSource = null;
danhsachbaocao.DataSource = table;
//thay đổi độ rộng cột
//MessageBox.Show(danhsachbaocao.Columns.Count.ToString());
if (danhsachbaocao.Columns.Count == 4)
{
danhsachbaocao.Columns[0].Width = 260;
danhsachbaocao.Columns[1].Width = 292;
danhsachbaocao.Columns[2].Width = 260;
danhsachbaocao.Columns[3].Width = 292;
}
else
{
danhsachbaocao.Columns[0].Width = 170;
danhsachbaocao.Columns[1].Width = 292;
danhsachbaocao.Columns[2].Width = 170;
danhsachbaocao.Columns[3].Width = 180;
danhsachbaocao.Columns[4].Width = 292;
}
}
catch (SqlException ex) //bắt ngoại lệ
{
MessageBox.Show(ex.Message);
}
finally
{
//B5: đóng kết nối
connection.Close();
}
}
//chỉ cho phép nhập số vào ô Tháng
private void thangtb_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
{
e.Handled = true;
}
}
//chỉ cho phép nhập số vào ô Năm
private void namtb_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
{
e.Handled = true;
}
}
private void QuayLaisv_Option_Click(object sender, EventArgs e)
{
Option_sv option = new Option_sv();
option.Show();
this.Hide();
}
private void thangcb_CheckedChanged(object sender, EventArgs e)
{
if (thangcb.Checked && !namcb.Checked)
{
namtb.Text = "";
namtb.Enabled = false;
}
if (!thangcb.Checked && namcb.Checked)
{
thangtb.Text = "";
thangtb.Enabled = false;
}
if (thangcb.Checked && namcb.Checked)
{
namtb.Enabled = true;
thangtb.Enabled = true;
}
if (!thangcb.Checked && !namcb.Checked)
{
namtb.Text = "";
thangcb.Checked = true;
namcb.Checked = false;
namtb.Enabled = false;
thangtb.Enabled = true;
}
}
private void namcb_CheckedChanged(object sender, EventArgs e)
{
if (thangcb.Checked && !namcb.Checked)
{
namtb.Text = "";
namtb.Enabled = false;
}
if (!thangcb.Checked && namcb.Checked)
{
thangtb.Text = "";
thangtb.Enabled = false;
}
if (thangcb.Checked && namcb.Checked)
{
namtb.Enabled = true;
thangtb.Enabled = true;
}
if (!thangcb.Checked && !namcb.Checked)
{
namtb.Text = "";
thangcb.Checked = true;
namcb.Checked = false;
namtb.Enabled = false;
thangtb.Enabled = true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Webcorp.rx_mvvm
{
public interface IWhereFluidCommand<T>
{
void Where(IObservable<bool> observer);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ExtMeth.Extensions
{
static class StringExtensions
{
public static string Cut(this string thisObj, int n)
{
if (thisObj.Length <= n)
{
return thisObj;
} else
{
return thisObj.Substring(0, n) + "...";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using PlebBot.Data.Models;
using PlebBot.Data.Repository;
namespace PlebBot.Modules
{
[Group("Roles")]
[Alias("Role")]
[Summary("Manage server roles")]
public class Roles : BaseModule
{
private readonly Repository<Role> roleRepo;
private readonly Repository<Server> serverRepo;
public Roles(Repository<Role> roleRepo, Repository<Server> serverRepo)
{
this.roleRepo = roleRepo;
this.serverRepo = serverRepo;
}
[Command]
[Name("roles")]
[Summary("Get a list of the self-assignable roles")]
public async Task GetAssignable()
{
var roles = await GetServerRolesAsync();
if (roles.Any())
{
var response = new EmbedBuilder()
.WithTitle("List of self-assignable roles:")
.WithColor(Color.Green);
var description = "";
var i = 1;
foreach (var role in roles)
{
description += $"{i}. {role.Name}\n";
i++;
}
response.WithDescription(description);
await ReplyAsync("", embed: response.Build());
}
else
{
await Error("This server doesn't have any self-assignable roles.");
}
}
[Command]
[Alias("get")]
[Name("roles get")]
[Summary("Get a self-assignable role")]
public async Task GetRole([Summary("The name of the role you wish to obtain")] string role)
{
var roles = await GetServerRolesAsync();
if (roles.Any())
{
var roleResult =
roles.Find(r => String.Equals(r.Name, role, StringComparison.CurrentCultureIgnoreCase));
if (roleResult != null)
{
var userRoles = (Context.User as IGuildUser)?.RoleIds;
var contains = userRoles?.Contains((ulong) roleResult.DiscordId);
if (!contains.GetValueOrDefault())
{
var assign =
Context.Guild.Roles.SingleOrDefault(
r => String.Equals(r.Name, role, StringComparison.CurrentCultureIgnoreCase));
if (roleResult.IsColour)
{
var colours = roles.Where(r => r.IsColour).ToList();
foreach (var colour in colours)
{
contains = userRoles?.Contains((ulong) colour.DiscordId);
if (!contains.GetValueOrDefault()) continue;
var unassign =
Context.Guild.Roles.SingleOrDefault(
r => r.Id == (ulong) colour.DiscordId);
await ((IGuildUser)Context.User).RemoveRoleAsync(unassign);
}
}
await ((IGuildUser)Context.User).AddRoleAsync(assign);
await Success($"Good job! You managed to get the '{assign?.Name}' role!");
}
else await Error("You already have this role assigned to you.");
}
else await Error($"There isn't a self-assignable role called '{role}'.");
}
else await Error("There are no self-assignable roles for the server.");
}
[Command("remove")]
[Name("roles remove")]
[Summary("Removes a role from you")]
public async Task RemoveRole([Summary("The name of the role you want to remove")] string role)
{
var roleResult = await roleRepo.FindFirst("Name", role.ToLowerInvariant());
if (roleResult == null)
{
await Error($"No role with the name {role} was found.");
return;
}
var user = Context.User as IGuildUser;
Debug.Assert(user != null, "user != null");
var userRole = user.RoleIds.FirstOrDefault(r => r == (ulong) roleResult.DiscordId);
if (userRole == 0)
{
await Error($"You don't have '{roleResult.Name}' assigned to you.");
return;
}
var guildRole = Context.Guild.Roles.FirstOrDefault(x => x.Id == userRole);
await user.RemoveRoleAsync(guildRole);
await Success($"Removed '{roleResult.Name}' from your roles.");
}
[Command("self")]
[Name("roles self")]
[Summary("Make a role self-assignable")]
[RequireUserPermission(GuildPermission.ManageRoles)]
public async Task SetAssignable(
[Summary("The role you want to make self-assignable")] string role,
[Summary(
"Marks the role as a colour role. Enables automatic colour removal and assigning of colours for users. Example: roles self Blue -c")] string colour = "")
{
var serverRoles = Context.Guild.Roles.ToList();
var roleFind =
serverRoles.Find(r => String.Equals(r.Name, role, StringComparison.CurrentCultureIgnoreCase));
if (roleFind != null)
{
var roleDb = await roleRepo.FindFirst("Name", role.ToLower());
if (roleDb == null)
{
var server = await serverRepo.FindByDiscordId((long) Context.Guild.Id);
var serverId = server.Id;
var isColour = colour == "-c";
string[] columns = { "ServerId", "DiscordId", "Name", "IsColour" };
object[] values = { serverId, (long) roleFind.Id, roleFind.Name, isColour };
await roleRepo.Add(columns, values);
await Success($"Added '{roleFind.Name}' to the list of self-assignable roles.");
}
else
{
await Error($"The '{roleFind.Name}' role is already set as self-assignable.");
}
}
else
{
await Error($"No role with the name '{role}' was found in the server.");
}
}
[Command("removeself")]
[Name("roles remove self")]
[Summary("Remove a role from the self-assignable list")]
[RequireUserPermission(GuildPermission.ManageRoles)]
public async Task RemoveAssignable([Summary("The role whose name you wish to remove")] string role)
{
var roleToRemove = await roleRepo.FindFirst("Name", role.ToLower());
if (roleToRemove != null)
{
await roleRepo.DeleteFirst("Id", roleToRemove.Id);
await Success(
$"The '{roleToRemove.Name}' role has been successfully removed from the self-assignable list");
return;
}
await Error($"No role with the name '{role}' has been found in the self-assignable list");
}
private async Task<List<Role>> GetServerRolesAsync()
{
var server = await serverRepo.FindByDiscordId((long) Context.Guild.Id);
var roles = await roleRepo.FindAll("ServerId", server.Id) as List<Role>;
return roles;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Audio;
public class PauseMenu : MonoBehaviour
{
public static bool GameIsPaused = false;
public static bool InOptionsMenu = false;
public static bool InCreditsMenu = false;
public static bool InVolumeMenu = false;
public static bool InControlsMenu = false;
public GameObject pauseMenuUI;
public GameObject menuUI;
public GameObject creditsUI;
public GameObject volumeUI;
public GameObject controlsUI;
// Update is called once per frame
void Update()
{ //checks for cases where you are in the main menu
//and decided where to go next after your button push
if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("ESC pressed");
if (GameIsPaused == true && InOptionsMenu == true)
{
BackToPauseMenu();
}
else if (GameIsPaused == true)
{
Resume();
}
else if (GameIsPaused == true && InCreditsMenu == true)
{
ExitCreditsMenu();
}
else if (GameIsPaused == true && InVolumeMenu == true)
{
ExitVolumeMenu();
}
else if (GameIsPaused == true && InControlsMenu == true)
{
ExitControlsMenu();
}
else if (GameIsPaused == false)
{
Paused();
}
}
}
//what to do for each condition
//usually it is stop/start time and stop/start audio
//and open different objects or different scenes depending what you push.
public void ExitCreditsMenu()
{
Time.timeScale = 0f;
pauseMenuUI.SetActive(true);
creditsUI.SetActive(false);
}
public void ExitVolumeMenu()
{
Time.timeScale = 0f;
pauseMenuUI.SetActive(true);
volumeUI.SetActive(false);
}
public void ExitControlsMenu()
{
Time.timeScale = 0f;
pauseMenuUI.SetActive(true);
controlsUI.SetActive(false);
}
public void BackToPauseMenu()
{
Time.timeScale = 0f;
pauseMenuUI.SetActive(true);
menuUI.SetActive(false);
}
public void Resume()
{
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
GameIsPaused = false;
AudioListener.pause = false;
//AudioListener.pause = false;
}
public void Paused()
{
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
GameIsPaused = true;
AudioListener.pause = true;
//AudioListener.pause = true;
}
public void LoadMenu()
{
pauseMenuUI.SetActive(false);
Time.timeScale = 0f;
GameIsPaused = true;
menuUI.SetActive(true);
SceneManager.LoadScene("Menu");
InOptionsMenu = true;
}
public void QuitGame()
{
Debug.Log("Quit Game");
SceneManager.LoadScene(0);
Time.timeScale = 1f;
AudioListener.pause = false;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemAndWeapon : MonoBehaviour {
public GameObject itemObj3DPrefab;
public GameObject weaponObj3DPrefab;
public AreaBase area;
public int itemAmount = 10;
// private List<ItemObj3D> item3DObjList = new List<ItemObj3D>();
public int weaponAmount = 10;
//private List<WeaponObj3D> weapon3DObjList = new List<WeaponObj3D>();
private Point temP;
public bool inEgde;
public float itemStayTime = 60;
//实例化ItemObj3D
public void InstantiateItemObj3D(int itemID, Vector3 pos)
{
GameObject itemObj3D = Instantiate(itemObj3DPrefab) as GameObject;
itemObj3D.transform.SetParent(this.transform);
itemObj3D.transform.position = pos;//设置位置
itemObj3D.transform.localScale = Vector3.one; //比例设为1
itemObj3D.GetComponent<ItemObj3D>().SetItem(InventoryManager.Instance.GetItemById(itemID));//设置item
}
//实例化Weaponj3D
public void InstantiateWeapon3D(int weaponId, Vector3 pos)
{
GameObject itemObj3D = Instantiate(weaponObj3DPrefab) as GameObject;
itemObj3D.transform.SetParent(this.transform);
itemObj3D.transform.position = pos;//设置位置
itemObj3D.transform.localScale = Vector3.one; //比例设为1
itemObj3D.GetComponent<WeaponObj3D>().SetWeapon(InventoryManager.Instance.GetWeaponById(weaponId));//设置item
}
//初始化随机生成
public void InitInstantiateItemAndWeapon()
{
for (int i = 0; i < itemAmount; i++)
{
int id = Random.Range(0, 3);//随机ID
//Debug.Log("物品" + id);
temP = inEgde ? area.GetRandomPointInEdge() : area.GetRandomPointInArea();
InstantiateItemObj3D(id, temP.position);
}
for (int i = 0; i < weaponAmount; i++)
{
int id = Random.Range(1, 6);//随机ID
//Debug.Log("武器" + id);
temP = inEgde ? area.GetRandomPointInEdge() : area.GetRandomPointInArea();
InstantiateWeapon3D(id, temP.position);
}
}
////清除所有物体
//public void ClearAll()
//{
// var go = transform.GetComponentsInChildren<Transform>();
// foreach (Transform g in go)
// {
// Destroy(g.gameObject);
// }
//}
}
|
using System;
using Common;
namespace MoneyTracking.User
{
public class UserId : EntityId
{
public UserId(Guid id) : base(id)
{
}
public static UserId New => new UserId(Guid.NewGuid());
}
} |
using System.Reactive;
using System.Reactive.Linq;
using MVVMSidekick.ViewModels;
using MVVMSidekick.Views;
using MVVMSidekick.Reactive;
using MVVMSidekick.Services;
using MVVMSidekick.Commands;
using IndoorMap;
using IndoorMap.ViewModels;
using System;
using System.Net;
using System.Windows;
namespace MVVMSidekick.Startups
{
internal static partial class StartupFunctions
{
static Action SubMapPageConfig =
CreateAndAddToAllConfig(ConfigSubMapPage);
public static void ConfigSubMapPage()
{
ViewModelLocator<SubMapPage_Model>
.Instance
.Register(context =>
new SubMapPage_Model())
.GetViewMapper()
.MapToDefault<SubMapPage>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Ben added - Projectile collector
public class ProjectileCol : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.tag == "Projectile")
{
other.gameObject.SetActive(false);
}
if (other.gameObject.tag == "Coin")
{
other.gameObject.SetActive(false);
}
}
}
|
using Blockchair.Models;
namespace Blockchair.Interfaces
{
public interface IBlockchairClient
{
Dashboard BitCoinAddressInfo(string address);
Dashboard BitCoinTransactionInfo(string transaction);
}
}
|
using System;
using Infrastructure.EventSourcing;
namespace Customer.Service
{
class Customer : EventSourced
{
bool deleted;
string name;
string email;
string vatNumber;
public Customer(Guid id)
: base(id)
{
Handles<CustomerCreated>(OnCreated);
Handles<CustomerDeleted>(OnDeleted);
Handles<CustomerRenamed>(OnRenamed);
Handles<CustomerEmailChanged>(OnEmailChanged);
Handles<CustomerVatNumberChanged>(OnVatNumberChanged);
}
public Customer(Guid id, string name, string vatNumber, string email)
: this(id)
{
Apply(new CustomerCreated
{
Name = name,
VatNumber = vatNumber,
Email = email
});
}
public void Delete()
{
Apply(new CustomerDeleted());
}
public void SetName(string newName)
{
AssertNotDeleted();
if (name != newName) Apply(new CustomerRenamed
{
OldName = name,
NewName = newName
});
}
public void SetEmail(string newEmail)
{
AssertNotDeleted();
if (email != newEmail) Apply(new CustomerEmailChanged
{
OldEmail = email,
NewEmail = newEmail
});
}
public void SetVatNumber(string newVatNumber)
{
AssertNotDeleted();
if (vatNumber != newVatNumber) Apply(new CustomerVatNumberChanged
{
OldVatNumber = vatNumber,
NewVatNumber = newVatNumber
});
}
void AssertNotDeleted()
{
if (deleted)
throw new InvalidOperationException("Customer already deleted.");
}
void OnCreated(CustomerCreated @event)
{
name = @event.Name;
email = @event.Email;
vatNumber = @event.VatNumber;
deleted = false;
}
void OnRenamed(CustomerRenamed @event)
{
name = @event.NewName;
}
void OnEmailChanged(CustomerEmailChanged @event)
{
email = @event.NewEmail;
}
void OnVatNumberChanged(CustomerVatNumberChanged @event)
{
vatNumber = @event.NewVatNumber;
}
void OnDeleted(CustomerDeleted @event)
{
deleted = true;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Linq;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
[System.Serializable]
public class Soal
{
[TextArea]
public string soal;
public string type;
public bool jawabanYa;
}
[System.Serializable]
public class SoalProperties
{
public GameObject listSoal;
public GameObject listButton;
public bool listActive;
}
public class SoalManager : MonoBehaviour
{
[Header("Pengaturan Soal")]
public List<string> gayaBelajar;
public List<Soal> recordSoal;
[Header("Properties (Jangan Diubah)")]
public GameObject card;
public GameObject buttonNavigasi;
public GameObject panelSoal;
public RectTransform navigasi;
public PanelSoal listView;
private TMP_Text textSoal;
private SoalProperties properties;
public List<Soal> randomedSoal;
// Start is called before the first frame update
void Start()
{
randomedSoal = new List<Soal>();
SetSoal();
}
void Restart(){
SceneManager.LoadScene("2 kuisioner");
}
public void SetSoal(){
RandomSoal();
foreach (Soal soal in randomedSoal)
{
properties = new SoalProperties();
GameObject obj = Instantiate(card, panelSoal.GetComponent<RectTransform>(), false) as GameObject;
obj.transform.SetParent(panelSoal.GetComponent<RectTransform>());
GameObject nvgs = Instantiate(buttonNavigasi, navigasi, false) as GameObject;
nvgs.transform.SetParent(navigasi);
obj.GetComponentInChildren<TMP_Text>().text = soal.soal;
obj.GetComponent<SoalBehaviour>().soal = soal.soal;
obj.GetComponent<SoalBehaviour>().type = soal.type;
properties.listSoal = obj;
properties.listButton = nvgs;
properties.listActive = false;
listView.soalProperties.Add(properties);
}
listView.SetFirstSoal();
//listView.SetButtonNumber();
}
void RandomSoal(){
while(recordSoal.Count != 0){
int tempAngka = Random.Range(0,recordSoal.Count);
Soal temp = recordSoal[tempAngka];
randomedSoal.Add(temp);
recordSoal.RemoveAt(tempAngka);
};
}
}
|
using GeoSnap.Providers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace GeoSnap.Controllers
{
public class UserController : ApiController
{
// GET: api/User
public HttpResponseMessage Get()
{
IEnumerable<string> headerValues = Request.Headers.GetValues("Authorization");
string accessToken = (string)headerValues.FirstOrDefault();
string userId = GraphProvider.getUserId(accessToken);
if (userId == null)
{
return Request.CreateResponse(HttpStatusCode.Unauthorized);
}
string username = UserDataProvider.getUsername(Int64.Parse(userId));
if(username == null)
{
return Request.CreateResponse(HttpStatusCode.NoContent);
}
return Request.CreateResponse(HttpStatusCode.OK, username);
}
// POST: api/User
public HttpResponseMessage Post(string username)
{
IEnumerable<string> headerValues = Request.Headers.GetValues("Authorization");
string accessToken = (string)headerValues.FirstOrDefault();
string userId = GraphProvider.getUserId(accessToken);
if (userId == null)
{
return Request.CreateResponse(HttpStatusCode.Unauthorized);
}
UserDataProvider.userOperationResult result = UserDataProvider.registerUser(Int64.Parse(userId), username);
switch (result) {
case UserDataProvider.userOperationResult.UserRegistrationSuccess:
return Request.CreateResponse(HttpStatusCode.Created);
case UserDataProvider.userOperationResult.UsernameIsTaken:
return Request.CreateResponse(HttpStatusCode.Conflict);
case UserDataProvider.userOperationResult.UserRegistrationFailed:
return Request.CreateResponse(HttpStatusCode.InternalServerError);
case UserDataProvider.userOperationResult.UserAlreadyRegistered:
return Request.CreateResponse(HttpStatusCode.MethodNotAllowed);
default:
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
// PUT: api/User/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/User/5
public void Delete(int id)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ToDo.Infrastructure;
namespace Karnitsky_Dubodel_DummyToManager.dll
{
public class ToDoProxyManager : IToDoManager
{
public ToDoProxyManager()
{
//ProcessStartInfo procStartInfo = new ProcessStartInfo("ConsoleApplication1.exe");
//procStartInfo.RedirectStandardOutput = true;
//procStartInfo.UseShellExecute = false;
//procStartInfo.CreateNoWindow = true;
//Process proc = new Process();
//proc.StartInfo = procStartInfo;
//proc.Start();
}
public void CreateToDoItem(IToDoItem item)
{
var client = new ToDoProxyService.Service1Client();
var toDoItem = new ToDoProxyService.ToDoItem()
{
Name = item.Name,
IsCompleted = item.IsCompleted,
ToDoId = item.ToDoId,
UserId = item.UserId
};
client.CreateToDoItem(toDoItem);
}
public int CreateUser(string name)
{
var client = new ToDoProxyService.Service1Client();
var id = client.CreateUser(name);
return id;
}
public void DeleteToDoItem(int todoItemId)
{
var client = new ToDoProxyService.Service1Client();
client.DeleteToDoItem(todoItemId);
}
public List<IToDoItem> GetTodoList(int userId)
{
var client = new ToDoProxyService.Service1Client();
var userList = client.GetTodoList(userId);
return new List<IToDoItem>();
//return userList.Select(x => new Item()
//{
// IsCompleted = x.IsCompleted,
// Name = x.Name,
// ToDoId = x.ToDoId,
// UserId = x.UserId
//}).ToList();
}
public void UpdateToDoItem(IToDoItem item)
{
var client = new ToDoProxyService.Service1Client();
var toDoItem = new ToDoProxyService.ToDoItem()
{
Name = item.Name,
IsCompleted = item.IsCompleted,
ToDoId = item.ToDoId,
UserId = item.UserId
};
client.UpdateToDoItem(toDoItem);
}
}
public class Item : IToDoItem
{
public bool IsCompleted { get; set; }
public string Name { get; set; }
public int ToDoId { get; set; }
public int UserId { get; set; }
}
}
|
namespace ServiceBase.Notification.Smtp
{
using System;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Logging;
using MimeKit;
using MimeKit.Text;
using ServiceBase.Notification.Email;
public class SmtpEmailSender : IEmailSender
{
private readonly SmtpOptions options;
private readonly ILogger<SmtpEmailSender> logger;
public SmtpEmailSender(
SmtpOptions options,
ILogger<SmtpEmailSender> logger)
{
this.logger = logger;
this.options = options;
}
public async Task SendEmailAsync(EmailMessage message)
{
MimeMessage mimeMsg = new MimeMessage();
mimeMsg.From.Add(new MailboxAddress(
String.IsNullOrWhiteSpace(message.EmailFrom) ?
this.options.EmailFrom :
message.EmailFrom));
mimeMsg.To.Add(new MailboxAddress(message.EmailTo));
mimeMsg.Subject = message.Subject;
if (!String.IsNullOrWhiteSpace(message.Html))
{
mimeMsg.Body = new TextPart(TextFormat.Html)
{
Text = message.Html
};
}
else if (!String.IsNullOrWhiteSpace(message.Text))
{
mimeMsg.Body = new TextPart(TextFormat.Text)
{
Text = message.Text
};
}
using (var client = new SmtpClient())
{
#if DEBUG
// For demo-purposes, accept all SSL certificates (in case
// the server supports STARTTLS)
client.ServerCertificateValidationCallback =
(s, c, h, e) => true;
#endif
client.Connect(
this.options.Host,
this.options.Port,
this.options.UseSsl
);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
if (!String.IsNullOrWhiteSpace(this.options.UserName) &&
!String.IsNullOrWhiteSpace(this.options.Password))
{
client.Authenticate(
this.options.UserName,
this.options.Password
);
}
client.Send(mimeMsg);
client.Disconnect(true);
}
await Task.CompletedTask;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProyectoLiquidexSA.Entities;
using ProyectoLiquidexSA.DataAccessLayer;
namespace ProyectoLiquidexSA.BusinessLayer
{
public class AsistenciaService
{
private AsistenciaDao oAsistenciaDao;
public AsistenciaService()
{
oAsistenciaDao = new AsistenciaDao();
}
public IList<AsistenciaUsuarios> ObtenerTodos()
{
return oAsistenciaDao.GetAll();
}
public bool CrearAsistencia(AsistenciaUsuarios oAsistenciaUsuario)
{
return oAsistenciaDao.Create(oAsistenciaUsuario);
}
public bool ActualizarAsistencia(AsistenciaUsuarios oAsistenciaUsuariosSelected)
{
return oAsistenciaDao.Update(oAsistenciaUsuariosSelected);
}
public bool BorrarAsistencia(AsistenciaUsuarios oAsistenciaUsuarioSelected)
{
return oAsistenciaDao.Delete(oAsistenciaUsuarioSelected);
}
public bool ModificarEstadoAsistencia(AsistenciaUsuarios oAsistenciaUsuarioSelected)
{
//throw new NotImplementedException();
return oAsistenciaDao.Update(oAsistenciaUsuarioSelected);
}
public object ObtenerAsistencia(string asistencia)
{
//CON PARAMETROS
return oAsistenciaDao.GetAsistenciaConParametros(asistencia);
//SIN PARAMETROS
//return oUsuarioDao.GetUserSinParametros(usuario);
}
internal IList<AsistenciaUsuarios> ConsultarConFiltrosSinParametros(String condiciones)
{
return oAsistenciaDao.GetByFiltersSinParametros(condiciones);
}
internal IList<AsistenciaUsuarios> ConsultarConFiltrosConParametros(Dictionary<string, object> filtros)
{
return oAsistenciaDao.GetByFiltersConParametros(filtros);
}
}
}
|
using Shop.Data.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shop.BusinnesLogic.Services.Fuctory
{
public abstract class TransactionCreator
{
public virtual Transaction CreateTransaction()
{
return new Transaction();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.Encryption
{
/**
* This class provides access to files encryption apps.
*
* @since 8.1.0
*/
public interface IManager {
/**
* Check if encryption is available (at least one encryption module needs to be enabled)
*
* @return bool true if enabled, false if not
* @since 8.1.0
*/
bool isEnabled();
/**
* Registers an callback function which must return an encryption module instance
*
* @param string id
* @param string displayName
* @param callable callback
* @throws ModuleAlreadyExistsException
* @since 8.1.0
*/
void registerEncryptionModule(string id, string displayName, Action callback);
/**
* Unregisters an encryption module
*
* @param string moduleId
* @since 8.1.0
*/
void unregisterEncryptionModule(string moduleId);
/**
* get a list of all encryption modules
*
* @return array [id => ['id' => id, 'displayName' => displayName, 'callback' => callback]]
* @since 8.1.0
*/
IDictionary<string,object> getEncryptionModules();
/**
* get a specific encryption module
*
* @param string moduleId Empty to get the default module
* @return IEncryptionModule
* @throws ModuleDoesNotExistsException
* @since 8.1.0
*/
IEncryptionModule getEncryptionModule(string moduleId = "");
/**
* get default encryption module Id
*
* @return string
* @since 8.1.0
*/
string getDefaultEncryptionModuleId();
/**
* set default encryption module Id
*
* @param string moduleId
* @return string
* @since 8.1.0
*/
string setDefaultEncryptionModule(string moduleId);
}
} |
using System.Collections.Generic;
using HarmonyInTheHome.Models;
namespace HarmonyInTheHome.Interfaces
{
public interface ICategoryService
{
void AddCategory(Category cat);
void DeleteCategory(int id);
Category GetCategory(int id);
Category GetCategoryWithoutRests(int id);
List<Category> ListCategories();
void UpdateCategory(Category cat);
}
} |
using System;
using System.Windows.Forms;
namespace DipDemo.Cataloguer.Infrastructure.Presentation.EventBinding.WinForms
{
public class ListBoxItemSelectEventBinder : IEventBinder
{
public void Bind(IPresenter presenter)
{
BindingHelper.FindAndConnectMethodsWithOneParameterFor<ListBox>(
presenter, ConnctListBoxItemSelect, Convensions.ListBoxItemSelectedSuffix, Convensions.ListBoxPrefix);
}
private void ConnctListBoxItemSelect(ListBox lb, Delegate action)
{
lb.SelectedIndexChanged += (sender, args) =>
{
var item1 = ((ListBox)sender).SelectedItem;
if (item1 == null)
return;
action.DynamicInvoke(item1);
};
}
}
} |
using Spotzer.Model.Inputs;
using Spotzer.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Spotzer.API.Controllers
{
[RoutePrefix("api/order")]
public class OrderController : ApiController
{
private IOrderService _orderService;
public OrderController(IOrderService orderService)
{
_orderService = orderService;
}
[Route("InsertOrder")]
[HttpPost]
public IHttpActionResult InsertOrder([FromBody]InsertOrderInput input)
{
_orderService.InsertOrder(input);
return Ok();
}
[Route("getOrders")]
[HttpGet]
public IHttpActionResult GetOrders()
{
return Ok(_orderService.GetOrders());
}
}
}
|
using UnityEngine;
using System.Collections;
public class Character : MonoBehaviour
{
[SerializeField]
private int items = 4;
public int Items
{
get { return items; }
set
{
items = value;
inventory.Refresh();
}
}
private Inventory inventory;
[SerializeField]
private float speed = 10.0F;
[SerializeField]
private float jumpForce = 30.0F;
[SerializeField] public GameObject text;
[SerializeField] public GameObject respawn;
public Rigidbody2D rb;
private bool isGrounded = false;
float time = 5.0F;
private CharState State
{
get { return (CharState)animator.GetInteger("State"); }
set { animator.SetInteger("State", (int)value); }
}
private Animator animator;
private SpriteRenderer sprite;
private void Awake()
{
inventory = FindObjectOfType<Inventory>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
sprite = GetComponentInChildren<SpriteRenderer>();
}
private void FixedUpdate()
{
CheckGround();
}
private void Update()
{
if (isGrounded) State = CharState.Idle;
if (Input.GetButton("Horizontal")) Run();
if (isGrounded && Input.GetButtonDown("Jump")) Jump();
if (Input.GetKey(KeyCode.R)) transform.position = respawn.transform.position;
if (text.activeSelf==true)
{
time -= Time.deltaTime;
if (time < 0)
{
text.SetActive(false);
}
}
}
private void Run()
{
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-speed, rb.velocity.y);
transform.localScale = new Vector2(-5, 6);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(speed, rb.velocity.y);
transform.localScale = new Vector2(5, 6);
}
if (isGrounded)
{
State = CharState.Run;
}
}
private void Jump()
{
rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
GetComponent<AudioSource>().Play();
}
private void CheckGround()
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.3F);
isGrounded = colliders.Length > 1;
if (!isGrounded) State = CharState.Jump;
}
}
public enum CharState
{
Idle,
Run,
Jump
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uygulama_Elektronik
{
abstract class Phone : Electronic
{
public int Processor { get; set; }
public int Ram { get; set; }
public int HDD { get; set; }
public int Camera { get; set; }
public ConnectionType ConnectionType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // need this namespace to work with files and directories
namespace ExistingDir
{
class Program
{
//Helper function to turn bytes to ...etc...
public static string FormatBytesToHumanReadable(long bytes)
{
if (bytes > 1073741824)
return Math.Ceiling(bytes / 1073741824M).ToString("#,### GB");
else if (bytes > 1048576)
return Math.Ceiling(bytes / 1048576M).ToString("#,### MB");
else if (bytes >= 1)
return Math.Ceiling(bytes / 1024M).ToString("#,### KB");
else if (bytes < 0)
return "";
else
return bytes.ToString("#,### B");
}
static void Main(string[] args)
{
string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
bool dirExists = Directory.Exists(thePath);
if (dirExists)
Console.WriteLine("The directory exists.\n");
else
Console.WriteLine("The directory does not exist.\n");
//==================================================================================
string[] files = Directory.GetFiles(thePath);
foreach (string s in files)
{
Console.WriteLine("Found file: " + s + "\n");
}
//==================================================================================
Console.WriteLine(" DRIVE INFORMATION \n");
Console.WriteLine("-----------Fixed Drives-----------");
foreach (DriveInfo d in DriveInfo.GetDrives())
{
if (d.DriveType == DriveType.Fixed)
{
Console.WriteLine("Drive Letter: {0}", d.Name);
Console.WriteLine("Drive Name: {0}", d.VolumeLabel);
Console.WriteLine("Free Space: {0}", FormatBytesToHumanReadable(d.TotalFreeSpace));
Console.WriteLine("Drive Type: {0}", d.DriveType + "\n");
}
}
Console.WriteLine("---------Removable Drives---------");
foreach (DriveInfo d in DriveInfo.GetDrives())
{
if (d.DriveType == DriveType.Removable)
{
Console.WriteLine("Drive Letter: {0}", d.Name);
Console.WriteLine("Drive Name: {0}", d.VolumeLabel);
Console.WriteLine("Free Space: {0}", FormatBytesToHumanReadable(d.TotalFreeSpace));
Console.WriteLine("Drive Type: {0}", d.DriveType + "\n");
}
}
}
/*
*
*
*/
}//END END
}
|
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System;
using System.Configuration;
using System.Runtime.Serialization;
namespace Framework.Remote
{
/// <summary>
/// Represents Exception that will be send to Client.
/// </summary>
[DataContract]
public class CxExceptionDetails
{
//----------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the CxExceptionDetails class.
/// </summary>
/// <param name="exception">Exception, whose details need to send.</param>
public CxExceptionDetails(Exception exception)
{
StackTrace = string.Empty;
Message = exception.Message;
Type = exception.GetType().Name;
AsString = exception.ToString();
bool showExceptionDetails =
Convert.ToBoolean(ConfigurationManager.AppSettings["ShowExceptionDetails"].ToLower());
if (showExceptionDetails)
{
StackTrace = exception.StackTrace;
}
if (exception.InnerException != null)
{
InnerException = new CxExceptionDetails(exception.InnerException);
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Gets the inner Exception details.
/// </summary>
[DataMember]
public CxExceptionDetails InnerException { get; set; }
//----------------------------------------------------------------------------
/// <summary>
/// Gets the Exception message.
/// </summary>
[DataMember]
public string Message { get; set; }
//----------------------------------------------------------------------------
/// <summary>
/// Gets the Exception Stack Trace.
/// </summary>
[DataMember]
public string StackTrace { get; set; }
//----------------------------------------------------------------------------
/// <summary>
/// Gets the Exception class type name.
/// </summary>
[DataMember]
public string Type { get; set; }
//-------------------------------------------------------------------------
/// <summary>
/// Represents the exception casted as a string.
/// </summary>
[DataMember]
public string AsString { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using aeffect_api.AeffectModel;
namespace aeffect_api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ChartController : ControllerBase
{
// GET api/Chart
[HttpGet]
public ActionResult<IEnumerable<Patient>> Get()
{
List<Patient> patients = new List<Patient>();
using (var DB = new AeffectContext())
{
patients = DB.Patient.ToList();
}
return patients;
}
}
}
// // GET api/values/5
// [HttpGet("{id}")]
// public ActionResult<string> Get(int id)
// {
// return "value";
// }
// // POST api/values
// [HttpPost]
// public void Post([FromBody] string value)
// {
// }
// // PUT api/values/5
// [HttpPut("{id}")]
// public void Put(int id, [FromBody] string value)
// {
// }
// // DELETE api/values/5
// [HttpDelete("{id}")]
// public void Delete(int id)
// {
// } |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;
using RMAT3.Models;
using Microsoft.AspNet.Identity;
using RMAT3.Data;
using RMAT3.Interfaces;
using RMAT3.Models.ViewModels;
using RMAT3.Common;
namespace RMAT3.Controllers
{
[Authorize]
public class AppController: Controller
{
private readonly IAppDal _appDal;
public AppController()
{
_appDal = new AppDal();
}
public ActionResult Tasks()
{
ViewBag.Current = "Tasks";
return View();
}
public ActionResult Accounts()
{
ViewBag.Current = "Accounts";
ViewBag.ClientName = "Energi";
return View();
}
public ActionResult Timelog()
{
ViewBag.Current = "Timelog";
return View();
}
public ActionResult Documents()
{
ViewBag.Current = "Documents";
return View();
}
public ActionResult Audits()
{
var section = new SectionType();
section.SectionQuestionTypes = _appDal.GetQuestionsForSection();
ViewBag.Current = "Audits";
return View(section);
}
public ActionResult Admin()
{
ViewBag.Current = "Admin";
return View();
}
public JsonResult GetTasks()
{
var userId = User.Identity.Name;
var tasks = _appDal.GetTasksForUser(userId);
//foreach (var task in tasks)
//{
// task.TaskId = ExtensionMethods.Encode(task.TaskId);
//}
return Json(tasks, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAccountDetails()
{
var tasks = new List<AuditHeader>
{
new AuditHeader
{
}
};
return Json(tasks, JsonRequestBehavior.AllowGet);
}
public JsonResult GetContacts()
{
var tasks = new List<AuditHeader>
{
new AuditHeader
{
}
};
return Json(tasks, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPolicies()
{
var tasks = new List<AuditHeader>
{
new AuditHeader
{
}
};
return Json(tasks, JsonRequestBehavior.AllowGet);
}
public JsonResult GetClients()
{
var clients = _appDal.GetOrganizations();
//foreach (var client in clients)
//{
// client.GuId = ExtensionMethods.Encode(client.GuId);
//}
return Json(clients, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAuditsForUser()
{
var userId = User.Identity.GetUserId();
var audits = _appDal.GetAuditsForUser(userId);
return Json(audits, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAppointments()
{
var userId = User.Identity.GetUserName();
var appointments = _appDal.GetAppointments(userId);
return Json(appointments, JsonRequestBehavior.AllowGet);
}
public void CreateAppointment(Appointment appointment)
{
var userId = User.Identity.GetUserName();
appointment.AppUser = new AppUser()
{
LoginTxt = userId
};
_appDal.CreateAppointment(appointment);
}
public JsonResult GetAuditCategories(int eventTypeId)
{
var categories = _appDal.GetAuditCategories(eventTypeId);
return Json(categories, JsonRequestBehavior.AllowGet);
}
public JsonResult GetQuestionsForSection()
{
var questions = new List<SectionQuestionType>();
return Json(questions, JsonRequestBehavior.AllowGet);
}
public JsonResult GetTaskTypes(int eventTypeId)
{
var events = _appDal.GetEventTypes().Where(x=>x.Id == eventTypeId);
return Json(events, JsonRequestBehavior.AllowGet);
}
public JsonResult GetEventTypes(bool? isBillable)
{
var events = _appDal.GetEventTypes().Where(x=>x.IsBillable == isBillable).GroupBy(x => x.TypeTxt).Select(y => y.First()).ToList();
return Json(events, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPartyByName(string name)
{
var party = _appDal.GetPartyByName(name);
return Json(party, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatusTypesByGroup(string groupName)
{
var party = _appDal.GetStatusTypesByGroup(groupName);
return Json(party, JsonRequestBehavior.AllowGet);
}
public bool CreateTask(TaskVm task)
{
task.AddedByUserId = User.Identity.GetUserName();
task.GuidClientId = Guid.Parse(task.SelectedClient.GuId);
var result = _appDal.CreateTask(task);
return result;
}
public bool UpdateTask(TaskVm task)
{
task.UpdatedByUserId = User.Identity.GetUserName();
var result = _appDal.UpdateTask(task);
return result;
}
public JsonResult GetTaskById(string taskId)
{
var guidTaskId = Guid.Parse(taskId);
var task = _appDal.GetTaskById(guidTaskId);
return Json(task, JsonRequestBehavior.AllowGet);
}
public JsonResult GetNotesForTask(string taskId)
{
var guidTaskId = Guid.Parse(taskId);
var notes = _appDal.GetNotesForTask(guidTaskId);
return Json(notes, JsonRequestBehavior.AllowGet);
}
public JsonResult AddOrUpdateNote(NoteVm note)
{
note.AddedByUserId = User.Identity.GetUserName();
note.UpdatedByUserId = User.Identity.GetUserName();
var result = _appDal.AddOrUpdateNote(note);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult GetTasksByClientCd(string clientCd)
{
var result = _appDal.GetTasksByClientCd(clientCd);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteTask(Guid taskId)
{
var updatedByUserId = User.Identity.GetUserName();
var result = _appDal.DeleteTask(taskId, updatedByUserId);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteNote(Guid noteId)
{
var updatedByUserId = User.Identity.GetUserName();
var result = _appDal.DeleteNote(noteId, updatedByUserId);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult GetNotesForAccount(TypeDataVm account)
{
var guidClientId = Guid.Parse(account.GuId);
var notes = _appDal.GetNotesForAccount(guidClientId, account.TypeCode);
return Json(notes, JsonRequestBehavior.AllowGet);
}
public JsonResult GetSubAuditCategories(int auditId)
{
var subCategories = _appDal.GetSubAuditCategories(auditId);
return Json(subCategories, JsonRequestBehavior.AllowGet);
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System.IO;
using System.IO.Compression;
#endregion
namespace DotNetNuke.HttpModules.Compression
{
/// <summary>
/// Summary description for DeflateFilter.
/// </summary>
public class DeflateFilter : CompressingFilter
{
private readonly DeflateStream m_stream;
public DeflateFilter(Stream baseStream) : base(baseStream)
{
m_stream = new DeflateStream(baseStream, CompressionMode.Compress);
}
public override string ContentEncoding
{
get
{
return "deflate";
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!HasWrittenHeaders)
{
WriteHeaders();
}
m_stream.Write(buffer, offset, count);
}
public override void Close()
{
m_stream.Close();
}
public override void Flush()
{
m_stream.Flush();
}
}
}
|
using System;
using UIKit;
using DeadDodo;
namespace StudyEspanol.iOS
{
public class PickerAdapter : UIPickerViewModel
{
#region Fields
private string[] options;
#endregion
#region Events
public event EventHandler<IndexSelectedEventArgs> ItemSelected;
#endregion
#region Initialziation
public PickerAdapter(params string[] options) : base()
{
this.options = options;
}
#endregion
#region Methods
public override string GetTitle(UIPickerView pickerView, nint row, nint component)
{
return options[row];
}
public override nint GetComponentCount(UIPickerView pickerView)
{
return 1;
}
public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
{
return options.Length;
}
public override void Selected(UIPickerView pickerView, nint row, nint component)
{
if (ItemSelected != null)
{
ItemSelected(this, new IndexSelectedEventArgs((int)row));
}
}
#endregion
#region Inner Classes
#endregion
}
}
|
using Autofac;
using Autofac.Integration.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using OnlineTabletop.Persistence;
using OnlineTabletop.Models;
using OnlineTabletop.Accounts;
using MongoDB.Driver;
namespace OnlineTabletop.Server
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var builder = new ContainerBuilder();
// Get your HttpConfiguration.
var config = GlobalConfiguration.Configuration;
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
//builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerRequest().WithParameter("client", new MongoClient(connectionString));
//builder.Register(c => new Repository<Player>(new MongoClient(connectionString))).As<IRepository<Player>>().InstancePerRequest();
builder.Register(c => new PlayerRepository(client)).As<IPlayerRepository<Player>>().InstancePerRequest();
builder.Register(c => new CharacterRepository(client)).As<ICharacterRepository<Character>>().InstancePerRequest();
builder.Register(c => new AccountManager(client)).As<IAccountManager<Account>>().InstancePerRequest();
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Set the dependency resolver to be Autofac.
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
NomBlankStringList lst = new NomBlankStringList();
lst.Add("Add at index 0");
lst[0] = "Item changed at 0";
lst.Add("Add at index 1");
lst.Insert(2, "Item changed at 2");
foreach (string item in lst)
{
Console.WriteLine(item);
}
}
}
}
|
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Effects;
namespace TableTopCrucible.Core.WPF.Converters
{
public class BlurConverter : IValueConverter
{
private BlurEffect _blur = new BlurEffect();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value == null || (value is bool bv && bv == false )? _blur : null;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SecondProject.Controllers.Services.Model.Domain
{
public class Logging
{
public bool IncludeScopes { get; set; }
public LogLevel LogLevel { get; set; }
}
}
|
#region copyright
/*
* Copyright (C) EnAble Games LLC - All Rights Reserved
* Unauthorized copying of these files, via any medium is strictly prohibited
* Proprietary and confidential
* fullserializer by jacobdufault is provided under the MIT license.
*/
#endregion
public class ParameterStrings
{
public static string STARTING_SPEED = "Player Starting Speed";
public static string GRAVITY = "Gravity";
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Beamore.DAL.Contents.Models
{
[Table("TempUserTable")]
public class TempUser : BaseModel
{
public string Email { get; set; }
public string TempGuid { get; set; }
// TODO: this willl change with real ecpiration time
public DateTime ExpirationTime { get; set; } = DateTime.UtcNow;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using CommonCore.Config;
using CommonCore.UI;
namespace CommonCore.UI
{
public class ConfigPanelController : MonoBehaviour
{
public Slider LookSpeedSlider;
public Slider GraphicsQualitySlider;
public Text GraphicsQualityLabel;
public Toggle AntialiasingToggle;
public Slider SoundVolumeSlider;
public Slider MusicVolumeSlider;
public Dropdown ChannelDropdown;
void OnEnable()
{
PaintValues();
}
private void PaintValues()
{
LookSpeedSlider.value = ConfigState.Instance.LookSpeed;
GraphicsQualitySlider.value = ConfigState.Instance.QualityLevel;
AntialiasingToggle.isOn = ConfigState.Instance.FxaaEnabled;
SoundVolumeSlider.value = ConfigState.Instance.SoundVolume;
MusicVolumeSlider.value = ConfigState.Instance.MusicVolume;
var cList = new List<string>(Enum.GetNames(typeof(AudioSpeakerMode)));
ChannelDropdown.AddOptions(cList);
ChannelDropdown.value = cList.IndexOf(AudioSettings.GetConfiguration().speakerMode.ToString());
}
public void OnQualitySliderChanged()
{
GraphicsQualityLabel.text = QualitySettings.names[(int)GraphicsQualitySlider.value];
}
public void OnClickConfirm()
{
UpdateValues();
ConfigState.Save();
ConfigModule.Apply();
Modal.PushMessageModal("Applied settings changes!", null, null, OnConfirmed);
}
private void OnConfirmed(ModalStatusCode status, string tag)
{
string sceneName = SceneManager.GetActiveScene().name;
if(sceneName == "MainMenuScene")
SceneManager.LoadScene(sceneName);
}
private void UpdateValues()
{
ConfigState.Instance.LookSpeed = LookSpeedSlider.value;
ConfigState.Instance.QualityLevel = (int)GraphicsQualitySlider.value;
ConfigState.Instance.FxaaEnabled = AntialiasingToggle.isOn;
ConfigState.Instance.SoundVolume = SoundVolumeSlider.value;
ConfigState.Instance.MusicVolume = MusicVolumeSlider.value;
ConfigState.Instance.SpeakerMode = (AudioSpeakerMode)Enum.Parse(typeof(AudioSpeakerMode), ChannelDropdown.options[ChannelDropdown.value].text);
}
}
} |
namespace PDV.DAO.Entidades
{
public class Configuracao
{
public decimal IDConfiguracao { get; set; }
public string Chave { get; set; }
public byte[] Valor { get; set; }
public object ValorJS { get; set; }
public Configuracao()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using System.Drawing;
namespace emgu
{
class Program
{
static void Main(string[] args)
{
//Image<Bgr, byte> image1 = new Image<Bgr, byte>(480, 320,new Bgr(255,0,0));
//Image<Gray,byte> image2=image1.Convert<Gray, byte>();
//Console.WriteLine(image2.Data[0,0,0]);
// image2.Save("image1.jpg");
Capture cap = new Capture("C:\\Users\\Hank\\Downloads\\camera1.mov");
Mat m = cap.QueryFrame();
int i = 0;
// // Console.Write(cap.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameCount));
// m.ToImage<Bgr, byte>().Save("test1.jpg");
while (m != null)
{
GC.Collect();
m = cap.QueryFrame();
i++;
Console.WriteLine(i);
}
// cap = new Capture("C:\\Users\\Hank\\Videos\\Captures\\运动1.mp4");
// m = cap.QueryFrame();
// m.Save("test2.jpg");
// i = 0;
//// GC.Collect();
// while (m != null)
// {
// m = cap.QueryFrame();
// i++;
// Console.WriteLine(i);
// }
//var temp1 = m.ToImage<Bgr, byte>();
//while (temp1 != null)
//{
// m = cap.QueryFrame();
// temp1 = m.ToImage<Bgr, byte>();
//}
//temp1.Save("test.jpg");
//cap = new Capture("C:\\Users\\Hank\\Videos\\Captures\\运动1.mp4");
//m = cap.QueryFrame();
//var temp2 = m.ToImage<Bgr, byte>();
//temp2.Save("test.jpg");
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
public class Gerenciamento_de_reservas
{
private List<Reservas> lista_de_reservas = new List<Reservas>();
public void Adicionar_Reserva(){
Reservas reserv = new Reservas();
reserv.Registrar_Reserva();
if (reserv.cliente == null)
{
Console.WriteLine("Ocorreu um erro no registro da reserva.");
return;
}
lista_de_reservas.Add(reserv);
}
public void Fechar_Conta(){
Listar_Reservas();
Console.WriteLine("\nEscreva o número do quarto que deseja fechar a reserva: ");
int room_number = int.Parse(Console.ReadLine());
Reservas reserva = Get_Reserva(room_number);
if(reserva == null){
return;
}
Console.WriteLine("\nObrigado por usar os nossos serviçoes, iremos dá o valor total da estádia: ");
Servico_de_controle_gastos serv = new Servico_de_controle_gastos();
Proxy_Serviço_De_Controle proxy = new Proxy_Serviço_De_Controle(serv);
Controle_financeiro cf = new Controle_financeiro();
double total = proxy.Calcular_Gasto(reserva);
Console.WriteLine("\nO gasto total da reserva com 5% incluso do nosso serviço é de: R${0:0.00}", total);
cf.Pagamento(total, total);
Gerenciamento_de_Quartos.GetInstancia().Desocupar_Quarto(reserva.Get_Quarto());
lista_de_reservas.Remove(reserva);
}
public void Listar_Reservas(){
Console.WriteLine("\nReservas registradas:");
foreach (var reserva in lista_de_reservas)
{
Console.WriteLine("Quarto {0} - Tipo: {1}, Reservado por {2}", reserva.Get_Quarto().Num_quarto, reserva.Get_Quarto().Tipo_quarto, reserva.cliente.Get_Nome());
}
}
public void Pedir_Serviço(){
Listar_Reservas();
Console.WriteLine("\nEscreva o número do quarto que deseja o pedido: ");
int room_number = int.Parse(Console.ReadLine());
Reservas reserva = Get_Reserva(room_number);
IQuarto quarto = reserva.Get_Quarto();
if(reserva == null){
return;
}
Console.WriteLine("\nGostaria de pedir qual serviço?");
Console.WriteLine("1 - Comida, 2 - Telefone");
int choice = int.Parse(Console.ReadLine());
if (choice < 0 || choice > 2)
{
Console.WriteLine("Serviço inválido");
return;
}
switch(choice){
case 1:{
quarto.pedir_comida();
break;
}
case 2:{
quarto.usar_telefone();
break;
}
default:
Console.WriteLine("\nOcorreu um problema na decisão do serviço\n");
break;
}
}
public Reservas Get_Reserva(int room_number){
foreach (var reserva in lista_de_reservas)
{
if(reserva.Get_Quarto().Num_quarto == room_number)
return reserva;
}
Console.WriteLine("\nO número do quarto está invalido.\n");
return null;
}
public void Listar_Gastos_Atuais(){
if(lista_de_reservas.Count == 0){
Console.WriteLine("\nNão possui nenhuma reserva registrada no sistema.\n");
return;
}
Console.WriteLine(lista_de_reservas.Count);
foreach (var reserva in lista_de_reservas)
{
int quarto_num = reserva.Get_Quarto().Num_quarto;
string cli_nome = reserva.cliente.Get_Nome();
Console.WriteLine("\nOs gastos atuais do quarto {0} do cliente {1}, são de:", quarto_num, cli_nome);
Servico_de_controle_gastos serv = new Servico_de_controle_gastos();
Proxy_Serviço_De_Controle proxy = new Proxy_Serviço_De_Controle(serv);
double total = proxy.Calcular_Gasto(reserva);
Console.WriteLine("\nO gasto total atual da reserva com 5% incluso do nosso serviço é de: R${0:0.00}\n", total);
}
}
}
|
using System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using kassasysteem.Classes;
namespace kassasysteem
{
public sealed partial class CheckoutPage : Page
{
private string _totalCost;
public CheckoutPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter == null) return;
_totalCost = e.Parameter.ToString();
}
private void BtContant_OnClick(object sender, RoutedEventArgs e)
{
//add SalesOrder
//var messageDialog = new MessageDialog("Totaal: " + _totalCost, "Contant betalen");
//await messageDialog.ShowAsync();
Frame.Navigate(typeof(ContantPage), _totalCost);
}
private async void BtPinnen_OnClick(object sender, RoutedEventArgs e)
{
//add SalesOrder
var messageDialog = new MessageDialog(_totalCost, "Betalen via pin");
await messageDialog.ShowAsync();
var messageDialogBevestiging = new MessageDialog("Betaling afgerond!", "Bevestiging");
await messageDialogBevestiging.ShowAsync();
CreatePrintPdf.CreateReceipt(Dashboard._cassiereName, Dashboard._number);
Frame.Navigate(typeof(Dashboard));
}
}
} |
using System;
namespace DDDSouthWest.Domain.Features.Public.News.NewsDetail
{
public class NewsDetailModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Filename { get; set; }
public string BodyHtml { get; set; }
public string BodyMarkdown { get; set; }
public bool IsLive { get; set; }
public DateTime DatePosted { get; set; }
}
} |
using Nancy;
using PingPongNS.Objects;
using System.Collections.Generic;
namespace PingPongNS
{
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/"] = _ => { return View["pingpong.cshtml", new List<string> {}];
};
Post["/pingpong"] = _ =>
{
List<string> model = PingPong.Play(Request.Form["number"]);
return View["pingpong.cshtml", model];
};
}
}
}
|
namespace XShare.WebForms.Cars
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.UI;
using System.Web.UI.WebControls;
using Data.Models;
using Ninject;
using Services.Data.Contracts;
public partial class CarDetails : System.Web.UI.Page
{
[Inject]
public ICarService CarService { get; set; }
protected void Page_PreInit(object sender, EventArgs e)
{
if (!this.User.Identity.IsAuthenticated)
{
this.Response.Redirect("~/Account/Login");
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
public Car ViewCarDetails_GetItem([QueryString("id")]int? carID)
{
if (carID == null)
{
Response.Redirect("~/");
}
var carToDisplay = this.CarService.CarById((int)carID);
return carToDisplay;
}
public IQueryable<int> GetCarRatings()
{
return (new[] { 1, 2, 3, 4, 5 }).AsQueryable();
}
protected void Btn_RateCar(object sender, EventArgs e)
{
var carRating = int.Parse(this.CarRateDropDown.SelectedValue);
var carId = int.Parse(this.Request.QueryString["id"]);
this.CarService.AddRating(carId, carRating);
this.UpdatePanelRating.DataBind();
}
}
} |
using System.Web;
namespace CurrencyConverter
{
public class Global : HttpApplication
{
protected void Application_Start()
{
}
}
}
/**
* Some of the most common Application Events:
* Application_Start() -> Only for first request.
* Application_End()
* Application_BeginRequest()
* Application_EndRequest()
* Session_Start()
* Session_End()
* Application_Error()
*/ |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightController : MonoBehaviour
{
public Light Light;
public PlayerShip Ship;
private float height = 4.5f;
private bool initialized;
private void Update()
{
if (initialized)
{
Light.transform.position = Ship.transform.position + new Vector3(0, height, 0);
}
}
public void Init(PlayerShip ship, Light light)
{
Ship = ship;
Light = light;
initialized = true;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class catNavigation : MonoBehaviour
{
[Header("Settings")]
public float stopDistance;
[Header("Runtime Variables")]
public GameObject target;
public GameObject spawn;
private NavMeshAgent nav;
private GameObject player;
private float distance;
private GameObject barrier;
private catHealth healthScript;
private gameManager managerScript;
// Start is called before the first frame update
void Start()
{
GameObject[] tmp = GameObject.FindGameObjectsWithTag("barrier");
GameObject closest = tmp[0];
for (int x = 0; x < tmp.Length; x++) {
if (Vector3.Distance(transform.position, tmp[x].transform.position) <
Vector3.Distance(transform.position, closest.transform.position)) {
closest = tmp[x];
}
}
barrier = closest;
player = GameObject.FindGameObjectWithTag("player");
target = barrier;
managerScript = GameObject.FindGameObjectWithTag("gameManager").GetComponent<gameManager>();
nav = GetComponent<NavMeshAgent>();
if (managerScript.difficulty == 0) {
nav.speed = managerScript.kittenSpeed;
} else if (managerScript.difficulty == 1) {
nav.speed = managerScript.catSpeed;
} else {
nav.speed = managerScript.wildcatSpeed;
}
healthScript = GetComponent<catHealth>();
StartCoroutine("TargetingLoop");
}
// Update is called once per frame
void Update()
{
if (!managerScript.isPaused) {
distance = Vector3.Distance(transform.position, target.transform.position);
if (distance <= stopDistance) {
nav.isStopped = true;
}
else {
nav.isStopped = false;
}
if (healthScript.currentHealth <= 0) {
target = spawn;
}
else if (barrier.GetComponent<barrierScript>().noPlanks) {
target = player;
}
else {
target = barrier;
}
} else {
nav.isStopped = true;
}
}
IEnumerator TargetingLoop() {
while (true) {
nav.SetDestination(target.transform.position);
yield return new WaitForSeconds(0.2f);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CoreFrameWork.EntityFrameworkCore.Sharding
{
class CoreEntityFrameworkServiceCollectionExtensions
{
}
}
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Breezy.Sdk")]
[assembly: AssemblyCompany("BreezyPrint Inc")]
[assembly: AssemblyProduct("Breezy.Sdk")]
[assembly: AssemblyCopyright("Copyright © Team Breezy 2017")]
[assembly: ComVisible(true)]
[assembly: Guid("f314e3c3-494e-4cb2-8381-c35d563ca710")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyDescription("C# wrapper for accessing the Breezy Cloud printing API")]
|
namespace PluginStudy.EntityFramework.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Add_Deptname : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Departments",
c => new
{
Guid = c.Guid(nullable: false),
DeptName = c.String(),
DeptParentId = c.Guid(nullable: false),
DeptIsDeleted = c.String(),
DeptRemark = c.String(),
})
.PrimaryKey(t => t.Guid);
}
public override void Down()
{
DropTable("dbo.Departments");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Core.DataAccess;
using Entities.Concrete;
using Entities.DTOs;
namespace DataAccess.Abstract
{
public interface IFavoriteDal:IEntityRepository<Favorite>
{
List<FavoriteDetailDto> GetAllDetails(Expression<Func<FavoriteDetailDto, bool>> filter = null);
}
} |
using Dapper;
using MISA.Core.Entities;
using MISA.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Infrastructure.Repository
{
public class CountryRepository : BaseRepository<Country>, ICountryRepository
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TopCoder
{
public class _12_07_02_KingdomAndTrees
{
/*
* http://apps.topcoder.com/wiki/display/tc/SRM+548
* http://community.topcoder.com/stat?c=problem_statement&pm=11967
* Problem Statement
* King Dengklek once planted N trees, conveniently numbered 0 through N-1, along the main highway in
* the Kingdom of Ducks. As time passed, the trees grew beautifully. Now, the height of the i-th tree is heights[i] units.
*
* King Dengklek now thinks that the highway would be even more beautiful if the tree heights were in strictly ascending
* order. More specifically, in the desired configuration the height of tree i must be strictly smaller than the height
* of tree i+1, for all possible i. To accomplish this, King Dengklek will cast his magic spell. If he casts magic spell
* of level X, he can increase or decrease the height of each tree by at most X units. He cannot decrease the height of
* a tree into below 1 unit. Also, the new height of each tree in units must again be an integer.
*
*
* Of course, a magic spell of a high level consumes a lot of energy. Return the smallest possible non-negative integer
* X such that King Dengklek can achieve his goal by casting his magic spell of level X.
*
Definition
Class: KingdomAndTrees
Method: minLevel
Parameters: int[]
Returns: int
Method signature: int minLevel(int[] heights)
(be sure your method is public)
Constraints
- heights will contain between 2 and 50 elements, inclusive.
- Each elements of heights will be between 1 and 1,000,000,000, inclusive.
Examples
0)
{9, 5, 11}
Returns: 3
One possible solution that uses magic spell of level 3:
Decrease the height of the first tree by 2 units.
Increase the height of the second tree by 3 units.
The resulting heights are {7, 8, 11}.
* 1)
{5, 8}
Returns: 0
These heights are already sorted in strictly ascending order.
* 2)
{1, 1, 1, 1, 1}
Returns: 4
Since King Dengklek cannot decrease the heights of the trees below 1,
the only possible solution is to cast his magic spell of level 4 to transform these heights into {1, 2, 3, 4, 5}.
* 3)
{548, 47, 58, 250, 2012}
Returns: 251
*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace br.com.weblayer.logistica.android.Helpers
{
public class DialogEventArgs
{
//you can put other properties here that may be relevant to check from activity
//for example: if a cancel button was clicked, other text values, etc.
public string ReturnValue { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StatsMain1
{
class MyRandom
{
private static Random rand;
static MyRandom()
{
rand = new Random();
}
public static double GetOneGaussianBySummation()
{
double result = -6.0;
for (int i = 0; i < 12; i++)
{
result += rand.NextDouble();
}
return result;
}
public static double GetOneGaussianByBoxMuller()
{
double x, y, size_squared;
do
{
x = 2.0 * rand.NextDouble() - 1;
y = 2.0 * rand.NextDouble() - 1;
size_squared = x * x + y * y;
} while (size_squared >= 1.0 || size_squared == 0);
return (x * Math.Sqrt(-2.0 * Math.Log(size_squared) / size_squared));
}
}
} |
using NBTM.Common;
namespace NBTM.Repository
{
public static class Enums
{
public enum CustomerClass : short
{
[EnumUtils.TextRepresentationAttribute("Strategic")]
Strategic = 1,
[EnumUtils.TextRepresentationAttribute("Collaborative")]
Collaborative = 2,
[EnumUtils.TextRepresentationAttribute("Transactional")]
Transactional = 3
}
public enum ProjectStatus : short
{
// New un-sponsored projects
[EnumUtils.TextRepresentationAttribute("New")]
New = 1,
// once they've been sponsored
[EnumUtils.TextRepresentationAttribute("Open")]
Open = 2,
[EnumUtils.TextRepresentationAttribute("Suspended")]
Suspended = 3,
[EnumUtils.TextRepresentationAttribute("Terminated")]
Terminated = 4,
[EnumUtils.TextRepresentationAttribute("Completed")]
Complete = 5,
}
public enum MarginClass : short
{
[EnumUtils.TextRepresentationAttribute("Low")]
Low = 1,
[EnumUtils.TextRepresentationAttribute("Mid-range")]
Midrange = 2,
[EnumUtils.TextRepresentationAttribute("High")]
High = 3
}
public enum VolumeClass : short
{
[EnumUtils.TextRepresentationAttribute("Low")]
Low = 1,
[EnumUtils.TextRepresentationAttribute("Mid-range")]
Midrange = 2,
[EnumUtils.TextRepresentationAttribute("High")]
High = 3
}
public enum ProjectActivityHealth : short
{
[EnumUtils.TextRepresentationAttribute("At Risk")]
AtRisk = 1,
[EnumUtils.TextRepresentationAttribute("Caution")]
Caution = 2,
[EnumUtils.TextRepresentationAttribute("Nominal")]
Nominal = 3,
[EnumUtils.TextRepresentationAttribute("Better")]
Better = 4,
[EnumUtils.TextRepresentationAttribute("On Track")]
OnTrack = 5
}
// Backtrack resolution (Suspended - Backtrack)
public enum BacktrackActions : short
{
[EnumUtils.TextRepresentationAttribute("Re-Open")]
ReOpen = 1,
[EnumUtils.TextRepresentationAttribute("Continue Suspension")]
ContinueSuspension = 2,
[EnumUtils.TextRepresentationAttribute("Terminate")]
Terminate = 3
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PayRoll.BLL
{
public class NoAffiliation:Affiliation
{
public double CalculateDeduction(PayCheck payCheck)
{
return 0;
}
}
}
|
namespace PDV.UTIL.Components.Custom
{
public class NavBarItem : DevExpress.XtraNavBar.NavBarItem
{
public decimal IDItemMenu { get; set; }
}
}
|
using BSEWalletClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BSEWalletClient.BAL;
using BSEWalletClient.BAL.Interface;
using BSEWalletClient.BAL.Repository;
using System.Data;
namespace BSEWalletClient.Controllers
{
public class HomeController : Controller
{
ICardRepository cardRepository = null;
ICustomerRepository customerRepository = null;
public HomeController()
{
cardRepository = new CardRepository();
customerRepository = new CustomerRepository();
}
public ActionResult Customer()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
Customer model = new Customer();
model.ListofCustomers = customerRepository.Get();
model.Cards = GetCards();
return View(model);
}
public ActionResult Transaction()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Card()
{
ViewBag.Message = "Your contact page.";
Cards model = new Cards();
model.ListofCards = cardRepository.Get();
return View(model);
}
/// <summary>
/// Add Cards
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public ActionResult CreateCards(FormCollection form)
{
Cards card = new Cards();
int number_of_Cards = Convert.ToInt32(form["txtNoofCards"]);
string Expiry_date = form["txtExpiryDate"].ToString();
card.Expiry = Convert.ToDateTime(Expiry_date);
card.Amount = form["txtAmount"].ToString();
cardRepository.Add(card, number_of_Cards);
return RedirectToAction("Card","Home");
}
/// <summary>
/// Add Customer
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public ActionResult AddCustomer(Customer customer)
{
if (ModelState.IsValid)
{
customerRepository.Add(customer);
return RedirectToAction("Customer", "Home");
}
return View();
}
/// <summary>
/// get Cards
/// </summary>
/// <returns></returns>
[NonAction]
private List<SelectListItem> GetCards()
{
List<Cards> cards = cardRepository.Get();
List<SelectListItem> drpDataCollectionList = new List<SelectListItem>();
foreach (Cards Card in cards)
{
drpDataCollectionList.Add(new SelectListItem { Value = Card.CardId.ToString(), Text = Card.CardNumber.ToString() });
}
return drpDataCollectionList;
}
}
}
|
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using System;
namespace NetFabric.Hyperlinq.Benchmarks
{
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class WhereSelectCountBenchmarks : RandomBenchmarksBase
{
[BenchmarkCategory("Array")]
[Benchmark(Baseline = true)]
public int Linq_Array()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(array, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("Enumerable_Value")]
[Benchmark(Baseline = true)]
public int Linq_Enumerable_Value()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(enumerableValue, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("Collection_Value")]
[Benchmark(Baseline = true)]
public int Linq_Collection_Value()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(collectionValue, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("List_Value")]
[Benchmark(Baseline = true)]
public int Linq_List_Value()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(listValue, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("Enumerable_Reference")]
[Benchmark(Baseline = true)]
public int Linq_Enumerable_Reference()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(enumerableReference, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("Collection_Reference")]
[Benchmark(Baseline = true)]
public int Linq_Collection_Reference()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(collectionReference, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("List_Reference")]
[Benchmark(Baseline = true)]
public int Linq_List_Reference()
=> System.Linq.Enumerable.Count(
System.Linq.Enumerable.Select(
System.Linq.Enumerable.Where(listReference, item => (item & 0x01) == 0), item => item));
[BenchmarkCategory("Array")]
[Benchmark]
public int Hyperlinq_Array()
=> array.AsValueEnumerable().Where(item => (item & 0x01) == 0).Select(item => item).Count();
[BenchmarkCategory("Array")]
[Benchmark]
public int Hyperlinq_Span()
=> array.AsSpan().Where(item => (item & 0x01) == 0).Select(item => item).Count();
[BenchmarkCategory("Array")]
[Benchmark]
public int Hyperlinq_Memory()
=> memory.AsValueEnumerable().Where(item => (item & 0x01) == 0).Select(item => item).Count();
[BenchmarkCategory("Enumerable_Value")]
[Benchmark]
public int Hyperlinq_Enumerable_Value()
=> EnumerableExtensions.AsValueEnumerable<TestEnumerable.Enumerable, TestEnumerable.Enumerable.Enumerator, int>(enumerableValue, enumerable => enumerable.GetEnumerator())
.Where(item => (item & 0x01) == 0)
.Select(item => item)
.Count();
[BenchmarkCategory("Collection_Value")]
[Benchmark]
public int Hyperlinq_Collection_Value()
=> ReadOnlyCollectionExtensions.AsValueEnumerable<TestCollection.Enumerable, TestCollection.Enumerable.Enumerator, int>(collectionValue, enumerable => enumerable.GetEnumerator())
.Where(item => (item & 0x01) == 0)
.Select(item => item)
.Count();
[BenchmarkCategory("List_Value")]
[Benchmark]
public int Hyperlinq_List_Value()
=> listValue
.AsValueEnumerable()
.Where(item => (item & 0x01) == 0)
.Select(item => item)
.Count();
[BenchmarkCategory("Enumerable_Reference")]
[Benchmark]
public int Hyperlinq_Enumerable_Reference()
=> enumerableReference
.AsValueEnumerable()
.Where(item => (item & 0x01) == 0)
.Select(item => item)
.Count();
[BenchmarkCategory("Collection_Reference")]
[Benchmark]
public int Hyperlinq_Collection_Reference()
=> collectionReference
.AsValueEnumerable()
.Where(item => (item & 0x01) == 0)
.Select(item => item)
.Count();
[BenchmarkCategory("List_Reference")]
[Benchmark]
public int Hyperlinq_List_Reference()
=> listReference
.AsValueEnumerable()
.Where(item => (item & 0x01) == 0)
.Select(item => item)
.Count();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApplication2
{
class SearchObject
{
public string Element { get; private set; }
public string ByWhat { get; private set; }
public SearchObject(string element, string byWhat)
{
this.Element = element;
this.ByWhat = byWhat;
}
public override string ToString()
{
return this.ByWhat + ":" + this.Element;
}
}
} |
using ShopApp.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ShopApp.WebUI.Models
{
public class BrandListViewModel
{
public string SelectedBrand { get; set; }
public List<Brand> Brands { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GetLabourManager.ViewModel
{
public class PermissionViewModel
{
public int PermissionId { get; set; }
public string PermissionDescription { get; set; }
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
namespace Microsoft.EntityFrameworkCore.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public sealed class ScopedDbContextLease<TContext> : IScopedDbContextLease<TContext>, IDisposable, IAsyncDisposable
where TContext : DbContext
{
private DbContextLease _lease;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public ScopedDbContextLease(IDbContextPool<TContext> contextPool)
=> _lease = new DbContextLease(contextPool, standalone: false);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public TContext Context
=> (TContext)_lease.Context;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void IDisposable.Dispose()
=> _lease.Release();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
ValueTask IAsyncDisposable.DisposeAsync()
=> _lease.ReleaseAsync();
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using DotNetNuke.Common;
using DotNetNuke.Entities.Content.Workflow.Repositories;
using DotNetNuke.Framework;
namespace DotNetNuke.Entities.Content.Workflow.Actions
{
public class WorkflowActionManager : ServiceLocator<IWorkflowActionManager, WorkflowActionManager> , IWorkflowActionManager
{
#region Members
private readonly IWorkflowActionRepository _workflowActionRepository;
#endregion
#region Constructor
public WorkflowActionManager()
{
_workflowActionRepository = WorkflowActionRepository.Instance;
}
#endregion
#region Public Methods
public IWorkflowAction GetWorkflowActionInstance(int contentTypeId, WorkflowActionTypes actionType)
{
var action = _workflowActionRepository.GetWorkflowAction(contentTypeId, actionType.ToString());
if (action == null)
{
return null;
}
return Reflection.CreateInstance(Reflection.CreateType(action.ActionSource)) as IWorkflowAction;
}
public void RegisterWorkflowAction(WorkflowAction workflowAction)
{
Requires.NotNull("workflowAction", workflowAction);
var action = Reflection.CreateInstance(Reflection.CreateType(workflowAction.ActionSource)) as IWorkflowAction;
if (action == null)
{
throw new ArgumentException("The specified ActionSource does not implement the IWorkflowAction interface");
}
_workflowActionRepository.AddWorkflowAction(workflowAction);
}
#endregion
#region Service Locator
protected override Func<IWorkflowActionManager> GetFactory()
{
return () => new WorkflowActionManager();
}
#endregion
}
}
|
using JoveZhao.Framework.DDD;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.DomesticTicket.Domain.Models.Refunds
{
public interface IPlatformRefundOrderRepository : IRepository<PlatformRefundOrder>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestCase.Basics;
using TestCase.Contracts;
namespace TestCase.Factory.Abstract
{
public abstract class WorkspaceFactory
{
public abstract IRouteProccesor CreateWorkspace(string args);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UFOAlienAI : WalkMonster
{
float attackDelay;
[SerializeField] int attackPerSecond;
float attackDuration;
int projectileCount;
float totalShotAngle;
[SerializeField] GameObject laser;
EnemyLaser laserComp;
bool isAlreadyDetectPlayer;
[SerializeField, Range(1f, 20f)] float height = 5;
[SerializeField] float visualRange;
bool isAttacking = false;
Coroutine attackCoroutine = null;
protected override void SettingVariables()
{
base.SettingVariables();
StopAllCoroutines();
attackDelay = StringToFloat(GetDataWithVariableName("AttackDelay"));
attackDuration = StringToFloat(GetDataWithVariableName("AttackDuration"));
projectileCount = (int)StringToFloat(GetDataWithVariableName("ProjectileCount"));
totalShotAngle = StringToFloat(GetDataWithVariableName("TotalShotAngle"));
visualRange = StringToFloat(GetDataWithVariableName("CognitiveRange"));
isAlreadyDetectPlayer = false;
isAttacking = false;
}
private void Awake()
{
SettingData();
GameObject laserObj = Instantiate(laser);
laserObj.transform.SetParent(transform);
laserObj.transform.position = transform.position;
laserComp = laserObj.GetComponent<EnemyLaser>();
laserComp.Initialize(projectileCount, totalShotAngle);
for (int i = 0; i < laserComp.laserCollider.Count; i++)
{
laserComp.laserCollider[i].rayDamage = StageManager.Instance.PlayerRoom <= 3 ? 1 : 2;
laserComp.laserCollider[i].attackDelay = 1f / attackPerSecond;
}
}
void Start()
{
OperateStart();
player = GameObject.FindWithTag("Player");
}
private void OnEnable()
{
OperateOnEnable();
}
private void OnDisable()
{
if (attackCoroutine != null)
{
StopCoroutine(attackCoroutine);
attackCoroutine = null;
}
for (int i = 0; i < laserComp.laserComps.Count; i++)
{
laserComp.laserComps[i].gameObject.SetActive(false);
}
laserComp.particleComp.gameObject.SetActive(false);
}
private void Update()
{
if (!isAlreadyDetectPlayer)
{
FindPlayer();
return;
}
else
{
if (attackCoroutine == null)
{
attackCoroutine = StartCoroutine(Attack());
}
}
CheckFrontWall();
}
IEnumerator Attack()
{
WaitForSeconds atkdel = new WaitForSeconds(attackDelay);
WaitForSeconds atkDur = new WaitForSeconds(attackDuration);
laserComp.particleComp.Play();
while (true)
{
laserComp.particleComp.gameObject.SetActive(true);
laserComp.particleComp.Play();
yield return atkdel; //공격 준비
laserComp.particleComp.gameObject.SetActive(false);
for (int i = 0; i < laserComp.laserComps.Count; i++)
{
laserComp.laserComps[i].gameObject.SetActive(true);
}
yield return atkDur; //공격 종료
for (int i = 0; i < laserComp.laserComps.Count; i++)
{
laserComp.laserComps[i].gameObject.SetActive(false);
}
}
}
void FindPlayer()
{
if (Vector2.Distance(player.transform.position, transform.position) <= visualRange)
{
isAlreadyDetectPlayer = true;
}
}
private void FixedUpdate()
{
if (isAlreadyDetectPlayer)
{
if (!isAttacking)
{
if (transform.position.y - player.transform.position.y >= height) //너무 높게 올라가면
{
rb2d.MovePosition(rb2d.position + Vector2.right * moveDir * movementSpeed * Time.deltaTime);
}
else
{
rb2d.MovePosition(new Vector2(rb2d.position.x + (moveDir * movementSpeed * Time.deltaTime), rb2d.position.y + 5 * Time.deltaTime));
}
}
}
}
private void OnCollisionEnter2D(Collision2D _collision)
{
OperateOnCollisionEnter2D(_collision);
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace JumpAndRun
{
public abstract class WorldComponent
{
public abstract void Update(JumpAndRunTime gameTime);
public abstract void Draw(JumpAndRunTime gameTime, Effect effect, Matrix view, Matrix proj);
public abstract void Initialize(Game game, Actor player);
public abstract string Name { get; }
}
}
|
using VoxConnections.JWT.Context;
using VoxConnections.JWT.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace VoxConnections.JWT.Repository
{
public class UsuarioRepository
{
private readonly VoxContext _context;
public UsuarioRepository(VoxContext context)
{
_context = context;
}
public async Task<Usuario> Find(LoginModel loginModel)
{
var result = await _context.Usuario
.Where(e => e.Senha.Equals(loginModel.Password) &&
e.Email.Equals(loginModel.Username) &&
e.Cadastrado == true)
.FirstOrDefaultAsync();
return result;
}
public async Task<int> FindCandidato(Guid idUsuario)
{
var result = await _context.Candidato
.Where(e => e.IdUsuario.Equals(idUsuario))
.Select(c => c.IdCandidato)
.FirstOrDefaultAsync();
return result;
}
public async Task<int> FindGestor(Guid idUsuario)
{
var result = await _context.Gestor
.Where(e => e.IdUsuario.Equals(idUsuario))
.Select(c => c.IdGestor)
.FirstOrDefaultAsync();
return result;
}
public async Task<int> FindHead(Guid idUsuario)
{
var result = await _context.Headhunter
.Where(e => e.IdUsuario.Equals(idUsuario))
.Select(c => c.IdHeadhunter)
.FirstOrDefaultAsync();
return result;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CustomCollection
{
/// <summary>
/// Represents a collection of composite keys (id, name) and values.
/// </summary>
/// <typeparam name="TId">The type of the key id in the collection.</typeparam>
/// <typeparam name="TName">The type of the key name in the collection.</typeparam>
/// <typeparam name="TValue">The type of the values in the collection.</typeparam>
public class CustomCollection<TId, TName, TValue> : IDoubleKeyDictionary<TId, TName, TValue>
{
#region [ Private Fields ]
private readonly IDictionary<TId, IDictionary<TName, TValue>> _dicById;
private readonly IDictionary<TName, IDictionary<TId, TValue>> _dicByName;
private readonly object _threadLock = new object();
#endregion // [ Private Fields ]
#region [ Public Properties ]
/// <summary>
/// Get a collection containing the Ids
/// </summary>
public IReadOnlyCollection<TId> Ids
{
get
{
lock (_threadLock)
{
return _dicById.Keys.ToList();
}
}
}
/// <summary>
/// Get a collection containing the names
/// </summary>
public IReadOnlyCollection<TName> Names
{
get
{
lock (_threadLock)
{
return _dicByName.Keys.ToList();
}
}
}
/// <summary>
/// Get a collection containing the values
/// </summary>
public IReadOnlyCollection<TValue> Values
{
get
{
lock (_threadLock)
{
return _dicById.SelectMany(item => item.Value.Values).ToList();
}
}
}
/// <summary>
/// Get the number of values contained in the collection
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Get or set element with composite Key (Id, Name)
/// </summary>
public TValue this[TId id, TName name]
{
get
{
TValue value;
if (TryGet(id, name, out value))
{
return value;
}
throw new ArgumentException("Element with given key (Id,Name) does not exists");
}
set { Set(id, name, value); }
}
/// <summary>
/// Get elements by Id
/// </summary>
public IReadOnlyCollection<NameValuePair<TName, TValue>> this[TId id]
{
get { return GetById(id); }
}
/// <summary>
/// Get elements Name
/// </summary>
public IReadOnlyCollection<IdValuePair<TId, TValue>> this[TName name]
{
get { return GetByName(name); }
}
#endregion // [Public Properties]
#region [ Constructors ]
/// <summary>
/// Initializes a new instance of the collection
/// </summary>
public CustomCollection()
{
_dicById = new Dictionary<TId, IDictionary<TName, TValue>>();
_dicByName = new Dictionary<TName, IDictionary<TId, TValue>>();
}
#endregion // [ Constructors ]
#region [ Public Methods ]
/// <summary>
/// Gets the value associated with the specified key (id, name)
/// </summary>
public bool TryGet(TId id, TName name, out TValue value)
{
if (id == null || name == null) throw new ArgumentNullException();
lock (_threadLock)
{
value = default(TValue);
IDictionary<TName, TValue> dicName;
return _dicById.TryGetValue(id, out dicName) && dicName.TryGetValue(name, out value);
}
}
/// <summary>
/// Get elements by Id
/// </summary>
public IReadOnlyCollection<NameValuePair<TName, TValue>> GetById(TId id)
{
lock (_threadLock)
{
IDictionary<TName, TValue> dicName;
return !_dicById.TryGetValue(id, out dicName)
? new List<NameValuePair<TName, TValue>>()
: dicName.Select(item => new NameValuePair<TName, TValue>(item.Key, item.Value)).ToList();
}
}
/// <summary>
/// Get elements by Name
/// </summary>
public IReadOnlyCollection<IdValuePair<TId, TValue>> GetByName(TName name)
{
lock (_threadLock)
{
IDictionary<TId, TValue> dicId;
return !_dicByName.TryGetValue(name, out dicId)
? new List<IdValuePair<TId, TValue>>()
: dicId.Select(item => new IdValuePair<TId, TValue>(item.Key, item.Value)).ToList();
}
}
/// <summary>
/// Save element with composite Key (Id, Name)
/// </summary>
public void Set(TId id, TName name, TValue value)
{
if (id == null || name == null) throw new ArgumentNullException();
lock (_threadLock)
{
IDictionary<TName, TValue> dicName;
TValue currentValue;
if (!_dicById.TryGetValue(id, out dicName) || !dicName.TryGetValue(name, out currentValue))
{
Add(id, name, value);
}
else
{
dicName[name] = value;
var dicId = _dicByName[name];
dicId[id] = value;
}
}
}
/// <summary>
/// Add new element with composite Key (Id, Name)
/// </summary>
public void Add(TId id, TName name, TValue value)
{
if (id == null || name == null) throw new ArgumentNullException();
lock (_threadLock)
{
IDictionary<TName, TValue> dicName;
if (!_dicById.TryGetValue(id, out dicName))
{
dicName = new Dictionary<TName, TValue>();
_dicById.Add(id, dicName);
}
if (dicName.ContainsKey(name))
{
throw new ArgumentOutOfRangeException("name", "Element with given key (Id,Name) already exists");
}
IDictionary<TId, TValue> dicId;
if (!_dicByName.TryGetValue(name, out dicId))
{
dicId = new Dictionary<TId, TValue>();
_dicByName.Add(name, dicId);
}
if (dicId.ContainsKey(id))
{
throw new ArgumentOutOfRangeException("id", "Element with given key (Id,Name) already exists");
}
dicId.Add(id, value);
dicName.Add(name, value);
Count++;
}
}
/// <summary>
/// Remove element by composite Key (Id, Name)
/// </summary>
public bool Remove(TId id, TName name)
{
if (id == null || name == null) throw new ArgumentNullException();
lock (_threadLock)
{
IDictionary<TName, TValue> dicName;
if (!_dicById.TryGetValue(id, out dicName)) return false;
IDictionary<TId, TValue> dicId;
if (!_dicByName.TryGetValue(name, out dicId)) return false;
dicId.Remove(id);
dicName.Remove(name);
Count--;
return true;
}
}
/// <summary>
/// Determines whether the collection contains an element with the specified key (id, name)
/// </summary>
public bool ContainsKey(TId id, TName name)
{
if (id == null || name == null) throw new ArgumentNullException();
lock (_threadLock)
{
if (!_dicById.ContainsKey(id)) return false;
var dicName = _dicById[id];
return dicName.ContainsKey(name);
}
}
/// <summary>
/// Removes all items from the collection
/// </summary>
public void Clear()
{
lock (_threadLock)
{
if (Count <= 0) return;
_dicById.Clear();
_dicByName.Clear();
Count = 0;
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection
/// </summary>
public IEnumerator<IdNameValueTriple<TId, TName, TValue>> GetEnumerator()
{
lock (_threadLock)
{
return _dicById.SelectMany(item => item.Value.Select(v => new IdNameValueTriple<TId, TName, TValue>(item.Key, v.Key, v.Value))).GetEnumerator();
}
}
void ICollection<IdNameValueTriple<TId, TName, TValue>>.Add(IdNameValueTriple<TId, TName, TValue> item)
{
Add(item.Id, item.Name, item.Value);
}
bool ICollection<IdNameValueTriple<TId, TName, TValue>>.Contains(IdNameValueTriple<TId, TName, TValue> item)
{
TValue value;
return TryGet(item.Id, item.Name, out value) && value.Equals(item.Value);
}
void ICollection<IdNameValueTriple<TId, TName, TValue>>.CopyTo(IdNameValueTriple<TId, TName, TValue>[] array, int arrayIndex)
{
((ICollection<IdNameValueTriple<TId, TName, TValue>>) this).CopyTo(array, arrayIndex);
}
bool ICollection<IdNameValueTriple<TId, TName, TValue>>.Remove(IdNameValueTriple<TId, TName, TValue> item)
{
TValue value;
if (TryGet(item.Id, item.Name, out value) && value.Equals(item.Value))
{
return Remove(item.Id, item.Name);
}
return false;
}
bool ICollection<IdNameValueTriple<TId, TName, TValue>>.IsReadOnly
{
get { return false; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion // [ Public Methods ]
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Windows.Documents;
namespace DiscuzCodeHighlighter
{
public class CodeBox : RichTextBox
{
bool _isToRender = false;
bool _isUbbView = false;
string _code = string.Empty;
/// <summary>
/// 当前是为UBB视图
/// </summary>
public bool IsUbbView
{
get
{
return _isUbbView;
}
set
{
if (_isUbbView != value)
{
if (this.ViewChanged != null)
this.ViewChanged(this, value);
_isUbbView = value;
}
}
}
/// <summary>
/// 存放的代码
/// </summary>
public string Code
{
get
{
return _code;
}
private set
{
_code = value;
if (this.CodeChanged != null)
this.CodeChanged(this, new EventArgs());
}
}
/// <summary>
/// 视图发生变化
/// </summary>
public event ViewChangedEventHandler ViewChanged;
/// <summary>
/// 代码发生改变
/// </summary>
public event EventHandler CodeChanged;
/// <summary>
/// 设置CodeBox显示内容
/// </summary>
/// <param name="paragraph">待显示的段落</param>
public void SetContent(Paragraph paragraph)
{
_isToRender = true;
this.Document.Blocks.Clear();
this.Document.Blocks.Add(paragraph);
_isToRender = false;
}
/// <summary>
/// 重写OnTextChanged方法,在某些情况中改变Code属性的值
/// </summary>
/// <param name="e"></param>
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
if (!_isUbbView && !_isToRender)
{
var textRange = new TextRange(
this.Document.ContentStart, this.Document.ContentEnd);
this.Code = textRange.Text;
}
}
/// <summary>
/// 重写OnPreviewKeyDown方法,重写定义Enter与CtrlV的行为
/// </summary>
/// <param name="e"></param>
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter && Keyboard.Modifiers != ModifierKeys.Shift)
{
this.CaretPosition.InsertLineBreak();
this.CaretPosition = this.CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);
e.Handled = true;
}
else if (e.Key == Key.V && Keyboard.Modifiers == ModifierKeys.Control)
{
var text = Clipboard.GetText();
text = text.Replace("\t", " ");
var paragraph = new Paragraph();
paragraph.Inlines.Add(text);
this.SetContent(paragraph);
this.Code = text;
e.Handled = true;
}
else
{
base.OnPreviewKeyDown(e);
}
}
/// <summary>
/// 重写OnPreviewMouseRightButtonUp,禁止右键菜单
/// </summary>
/// <param name="e"></param>
protected override void OnPreviewMouseRightButtonUp(MouseButtonEventArgs e)
{
e.Handled = true;
}
}
}
|
using System;
using Foundation;
using UIKit;
namespace JKMIOSApp
{
/// <summary>
/// Controller Name : MyTeamViewController
/// Author : Hiren Patel
/// Creation Date : 16 JAN 2018
/// Purpose : To display my team page screen as app shell screen
/// Revision :
/// </summary>
public partial class MyTeamViewController : UIViewController
{
public MyTeamViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
InitilizeIntarface();
}
/// <summary>
/// Method Name : InitilizeIntarface
/// Author : Hiren Patel
/// Creation Date : 29 Dec 2017
/// Purpose : To Initilizes the intarface.
/// Revision :
/// </summary>
public void InitilizeIntarface()
{
// InitilizeIntarface
btnAlert.TouchUpInside += BtnAlert_TouchUpInside;
btnContactUs.TouchUpInside += BtnContactUs_TouchUpInside;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
NavigationController.NavigationBarHidden = true;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
}
/// <summary>
/// Event Name : BtnContactUs_TouchUpInside
/// Author : Hiren Patel
/// Creation Date : 29 Dec 2017
/// Purpose : To redirect contactus page
/// Revision :
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event Argument</param>
private void BtnContactUs_TouchUpInside(object sender, EventArgs e)
{
PerformSegue("myteamToContactus", this);
}
/// <summary>
/// Event Name : BtnAlert_TouchUpInside
/// Author : Hiren Patel
/// Creation Date : 29 Dec 2017
/// Purpose : To redirect notification
/// Revision :
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event Argument</param>
private void BtnAlert_TouchUpInside(object sender, EventArgs e)
{
PerformSegue("notification", this);
}
}
}
|
using GameStore.Domain.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
namespace GameStore.WebUI.Models
{
public class ShoppingCart
{
private List<CartItem> items = new List<CartItem>();
public ShoppingCart()
{
}
public List<CartItem> GetItems()
{
return this.items;
}
public void AddItem(int id, Product product)
{
CartItem cartItem;
for (int i = 0; i < items.Count(); i++)
{
cartItem = items[i];
if (cartItem.GetItemId() == id)
{
cartItem.IncrementItemQuantity();
return;
}
}
CartItem newCartItem = new CartItem(product);
items.Add(newCartItem);
}
public void SetItemQuantity(int id, int quantity, Product product)
{
CartItem cartItem;
for (int i = 0; i < items.Count(); i++)
{
cartItem = items[i];
if (cartItem.GetItemId() == id)
{
if (quantity <= 0)
{
items.Remove(cartItem);
}
else
{
cartItem.Quantity = quantity;
}
return;
}
}
CartItem newCartItem = new CartItem(product);
items.Add(newCartItem);
}
public double GetTotalValue()
{
double sum = 0;
for (int i = 0; i < items.Count(); i++)
{
sum += items[i].GetDiscountedPrice();
}
return sum;
}
}
} |
using System;
using System.Collections.Generic;
class SortByLength
{
static void Main(string[] args)
{
string[] arr = { "asdc", "wdsc1", "as", "awe", "a" };
foreach (string element in arr)
{
Console.WriteLine(element);
}
Console.WriteLine();
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i].Length > arr[j].Length)
{
string temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Attributes.CustomAttributes
{
public class Info : Attribute
{
private string description;
public int Importance { get; set; }
public Info(string description)
{
this.description = description;
}
}
}
|
using Xamarin.Forms;
namespace App1.Renderers
{
public class ButtonTextAlignment : Button
{
}
}
|
using REQFINFO.Repository.DataEntity;
using REQFINFO.Repository.Infrastructure;
using REQFINFO.Repository.Infrastructure.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace REQFINFO.Repository
{
public class CustumLookupRepository : BaseRepository<CustomLookup>
{
GIGEntities entities;
public CustumLookupRepository(IUnitOfWork unit)
: base(unit)
{
entities = (GIGEntities)this.UnitOfWork.Db;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.