text stringlengths 13 6.01M |
|---|
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Newtonsoft.Json;
using ND.FluentTaskScheduling.CrawlKeGui.getModifyAndRefundStipulates;
/// <summary>
///_51bookHelper 接口访问帮助类
/// </summary>
public class _51bookHelper
{
public _51bookHelper(string _agencyCode,string _safetyCode)
{
agencyCode = _agencyCode;
safetyCode = _safetyCode;
}
//创建日记对象
//公司代码
private static string agencyCode = "";
//安全码
private static string safetyCode = ""; //正式账号
#region 全取退改签规定 getModifyAndRefundStipulates(GetModifyAndRefundStipulatesRequest model)
//根据航空公司、舱位获取退改签规定
public static object getModifyAndRefundStipulates(getModifyAndRefundStipulatesRequest model)
{
model.agencyCode = agencyCode;
model.sign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile((agencyCode + model.lastSeatId + model.rowPerPage + safetyCode), "MD5").ToLower();
try
{
getModifyAndRefundStipulatesReply result = new GetModifyAndRefundStipulatesServiceImpl_1_0Service().getModifyAndRefundStipulates(model);
return result;
}
catch (Exception e)
{
return e.Message+":"+JsonConvert.SerializeObject(e);
}
}
#endregion
}
|
using Project.DbConnect;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project.Model
{
class SettingsModel
{
Transactions trans = new Transactions();
public DataTable UpdateProfile(string userName, string password,string name, int userId)
{
string sql = " update user_info Set user_name = '"+userName+"', user_password = '"+password+"', " +
"name = '"+name+"' where user_id = "+userId+" RETURNING * ";
DataTable dt = new DataTable();
trans.OpenConnection();
trans.startTransaction();
try
{
dt = trans.Datasource(sql);
trans.commitQuery();
trans.closeTransaction();
}
catch (Exception e)
{
trans.closeTransaction();
MessageBox.Show(e.Message);
}
return dt;
}
}
}
|
namespace FamousQuoteQuiz.Data.ServiceModels
{
public class UserAnsweredQuizReview
{
public string Quiz { get; set; }
public string UserAnswer { get; set; }
public string CorrectAnswer { get; set; }
public string User { get; set; }
}
}
|
namespace RockPaperScissors.Basics
{
public enum Sign { Rock, Paper, Scissors }
public static class Signs
{
static readonly private bool?[,] _beats;
public static bool? Beats(Sign s1, Sign s2) => _beats[(int)s1, (int)s2];
public static int Count => (int)Sign.Scissors + 1;
static Signs()
{
// Rock, Paper, Scissors
_beats = new bool?[,] /*Rock*/ {{ null, false, true},
/*Paper*/ { true, null, false},
/*Scissors*/ { false, true, null}};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using alg;
/*
* tags: bs
* Time(n), Space(1)
* divide into two parts, left is a[0..i-1] and b[0..j-1], right is a[i..m-1] and b[j..n-1], where i=[0..m], j=[0..n]
* make sure max(left) <= min(right) and count(left)==count(right) [+ 1 if odd]
*/
namespace leetcode
{
public class Lc004_Median_of_Two_Sorted_Arrays
{
public double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
if (nums1.Length > nums2.Length)
{
var t = nums1;
nums1 = nums2;
nums2 = t;
}
int m = nums1.Length, n = nums2.Length;
int lo = 0, hi = m;
while (true)
{
int i = (lo + hi) / 2;
int j = (m + n + 1) / 2 - i;
int maxLeft1 = i > 0 ? nums1[i - 1] : int.MinValue;
int maxLeft2 = j > 0 ? nums2[j - 1] : int.MinValue;
int minRight1 = i < m ? nums1[i] : int.MaxValue;
int minRight2 = j < n ? nums2[j] : int.MaxValue;
if (maxLeft1 > minRight2) hi = i - 1;
else if (maxLeft2 > minRight1) lo = i + 1;
else if ((m + n) % 2 == 1) return Math.Max(maxLeft1, maxLeft2);
else return (Math.Max(maxLeft1, maxLeft2) + Math.Min(minRight1, minRight2)) / 2.0;
}
}
public void Test()
{
var nums1 = new int[] { 1, 2 };
var nums2 = new int[] { 2 };
Console.WriteLine(FindMedianSortedArrays(nums1, nums2) == 2);
nums1 = new int[] { 1, 2 };
nums2 = new int[] { 3, 4 };
Console.WriteLine(FindMedianSortedArrays(nums1, nums2) == 2.5);
nums1 = new int[] { 2 };
nums2 = new int[] { 1 };
Console.WriteLine(FindMedianSortedArrays(nums1, nums2) == 1.5);
nums1 = new int[] { };
nums2 = new int[] { 1 };
Console.WriteLine(FindMedianSortedArrays(nums1, nums2) == 1);
nums1 = new int[] { 3 };
nums2 = new int[] { 1, 2 };
Console.WriteLine(FindMedianSortedArrays(nums1, nums2) == 2);
}
}
}
|
using MediatR;
using MikeGrayCodes.BuildingBlocks.Application;
using System;
using System.Runtime.Serialization;
namespace MikeGrayCodes.Ordering.Application.Application.Commands
{
public class ShipOrderCommand : Command<Unit>
{
[DataMember]
public Guid OrderNumber { get; private set; }
public ShipOrderCommand(Guid orderNumber)
{
OrderNumber = orderNumber;
}
}
} |
using LocusNew.Persistence;
using LocusNew.Core.Models;
using System.Linq;
using LocusNew.Core.Repositories;
namespace LocusNew.Persistence.Repositories
{
public class GlobalSettingsRepository : IGlobalSettingsRepository
{
private readonly ApplicationDbContext _ctx;
public GlobalSettingsRepository(ApplicationDbContext ctx)
{
_ctx = ctx;
}
public GlobalSettings GetGlobalSettings()
{
return _ctx.GlobalSettings.FirstOrDefault();
}
}
} |
using System;
using System.Runtime.InteropServices;
namespace SenseHat {
/// <summary>
/// Misc. Raspberry Pi SenseHat Library Utils
/// </summary>
public static class SenseHat {
public static readonly Version LibraryVersion = new Version(1, 1, 0, 0); // Version of Library
// Probe to discover the dev name for the joystick
[DllImport("stick.so")]
private static extern string probe_sense_stick();
/// <summary>
/// Checks if SenseHat is attached
/// </summary>
/// <returns><c>true</c> if is attached; otherwise, <c>false</c>.</returns>
public static bool IsAttached () {
return !String.IsNullOrEmpty (probe_sense_stick ()); // Check if a valid device name is returned
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ellenseg : MonoBehaviour
{
protected Animator anim;
protected Rigidbody2D rb;
protected AudioSource death;
// Az alkalmazás vagy a fájl meghívásakor lefutó kód
protected virtual void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
death = GetComponent<AudioSource>();
}
// Az ellenségre ráugrottak (a játékos)
public void JumpedOn()
{
anim.SetTrigger("Death");
death.Play();
}
// Eltűnik az ellenség, "meghal"
private void Death()
{
Destroy(this.gameObject);
}
}
|
public class MinStack {
private Stack<int> st1;
private Stack<int> st2;
/** initialize your data structure here. */
public MinStack() {
st1 = new Stack<int>();
st2 = new Stack<int>();
}
public void Push(int x) {
st1.Push(x);
if(st2.Count == 0 || x <= st2.Peek()) st2.Push(x);
}
public void Pop() {
if (st1.Peek() == st2.Peek()) st2.Pop();
st1.Pop();
}
public int Top() {
return st1.Peek();
}
public int GetMin() {
return st2.Peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.Push(x);
* obj.Pop();
* int param_3 = obj.Top();
* int param_4 = obj.GetMin();
*/ |
using System.Net.Sockets;
namespace pjank.BossaAPI.Fixml
{
public class MarketDataFullRefreshMsg : FixmlMsg
{
public const string MsgName = "MktDataFull";
public int RequestId { get; private set; }
public MarketDataFullRefreshMsg(Socket socket) : base(socket) { }
protected override void ParseXmlMessage(string name)
{
base.ParseXmlMessage(MsgName);
// NOL3 w razie problemów czasem zwraca tutaj ujemną wartość -1
RequestId = FixmlUtil.ReadInt(xml, "ReqID");
}
public override string ToString()
{
return string.Format("[{0}:{1}]", Xml.Name, RequestId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace VesApp.Domain
{
public class Event
{
[Key]
public int IdEvent { get; set; }
public string Titulo { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "El campo {0} es obligatorio")]
public string Text { get; set; }
[DataType(DataType.Date)]
[Index("Publication_Fecha_Index")]
public DateTime FechaEvento { get; set; }
public string EnlaceOnline { get; set; }
public string EnlaceInscripcion { get; set; }
public string Lugar { get; set; }
public string Hora { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Ejercicio_19
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int fila;
int columna;
public MainWindow()
{
InitializeComponent();
Inicializar();
}
void Inicializar()
{
for (int i = 1; i < 21; i++)
{
cbxFilas.Items.Add(i);
cbxColumnas.Items.Add(i);
}
cbxFilas.SelectedItem = cbxFilas.Items[5];
cbxColumnas.SelectedIndex = 5;
}
private void BtnCrearMatriz_Click(object sender, RoutedEventArgs e)
{
stpMatriz.Children.Clear();
fila = int.Parse(cbxFilas.SelectedItem.ToString());
columna = int.Parse(cbxColumnas.SelectedItem.ToString());
CBotones btn;
<<<<<<< HEAD
=======
LineBreak saltoLinea = new LineBreak();
>>>>>>> casa/master
for (int i = 0; i < fila; i++)
{
for (int j = 0; j < columna; j++)
{
btn = new CBotones(i, j);
stpMatriz.Children.Add(btn.Btn);
<<<<<<< HEAD
}
=======
}
>>>>>>> casa/master
}
}
}
}
|
using InoDrive.Api.Providers;
using InoDrive.Domain;
using InoDrive.Domain.Models;
using InoDrive.Domain.Repositories.Abstract;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace InoDrive.Api.Controllers
{
[RoutePrefix("api/user")]
public class UserController : ApiController
{
private IUsersRepository _repo;
public UserController(IUsersRepository repo)
{
_repo = repo;
}
[HttpPost]
[Authorize]
[Route("getUserProfile")]
public IHttpActionResult GetUserProfile(ShortUserModel model)
{
var result = _repo.GetUserProfile(model);
return Ok(result);
}
[HttpPost]
[Route("getUserSummary")]
public IHttpActionResult GetUserSummary(ShortUserModel model)
{
var result = _repo.GetUserSummary(model);
return Ok(result);
}
[HttpPost]
[Authorize]
[Route("setUserProfile")]
public async Task<IHttpActionResult> SetUserProfile()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var provider = GetMultipartProvider("avatarsFolder");
var resultFile = await Request.Content.ReadAsMultipartAsync(provider);
var profile = (ProfileModel)GetFormData<ProfileModel>(resultFile);
var isFileAttached = resultFile.FileData.Count != 0;
if (isFileAttached)
{
profile.AvatarImage = (new FileInfo(resultFile.FileData.First().LocalFileName)).Name;
}
if (profile.AvatarImage != profile.OldAvatarImage)
{
string fullPathToFile =
HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["avatarsFolder"] + profile.OldAvatarImage);
if (File.Exists(fullPathToFile))
{
File.Delete(fullPathToFile);
}
}
try
{
_repo.SetUserProfile(profile);
}
catch
{
File.Delete(profile.AvatarImage);
return ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { status = Statuses.CommonFailure }));
}
return Ok(profile);
}
[HttpPost]
[Authorize]
[Route("setUserCar")]
public async Task<IHttpActionResult> SetUserCar()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var provider = GetMultipartProvider("carsFolder");
var resultFile = await Request.Content.ReadAsMultipartAsync(provider);
var car = (CarModel)GetFormData<CarModel>(resultFile);
var isFileAttached = resultFile.FileData.Count != 0;
if (isFileAttached)
{
car.CarImage = (new FileInfo(resultFile.FileData.First().LocalFileName)).Name;
}
if (car.CarImage != car.OldCarImage)
{
string fullPathToFile =
HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["carsFolder"] + car.OldCarImage);
if (File.Exists(fullPathToFile))
{
File.Delete(fullPathToFile);
}
}
try
{
_repo.SetUserCar(car);
}
catch
{
File.Delete(car.CarImage);
return ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { status = Statuses.CommonFailure }));
}
return Ok(car);
}
#region Private functions
private MultipartFormDataStreamProvider GetMultipartProvider(string folder)
{
var uploadFolder = ConfigurationManager.AppSettings[folder];
var root = HttpContext.Current.Server.MapPath(uploadFolder);
Directory.CreateDirectory(root);
return new CustomMultipartFormDataStreamProvider(root);
}
private object GetFormData<T>(MultipartFormDataStreamProvider result)
{
if (result.FormData.HasKeys())
{
var unescapedFormData = Uri.UnescapeDataString(result.FormData.GetValues(0).FirstOrDefault() ?? String.Empty);
if (!String.IsNullOrEmpty(unescapedFormData))
return JsonConvert.DeserializeObject<T>(unescapedFormData);
}
return null;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PlanMGMT.BLL;
using PlanMGMT.Utility;
using PlanMGMT.ViewModel;
namespace PlanMGMT.Module
{
/// <summary>
/// NoteListModule.xaml 的交互逻辑
/// </summary>
public partial class ReportModule : UserControl
{
public ReportModule()
{
InitializeComponent();
}
private void myCalender_SelectedDatesChanged_1(object sender, SelectionChangedEventArgs e)
{
DateTime dt = (DateTime)(e.AddedItems[0]);
if (dt != null)
{
((ViewModel.ReportViewModel)base.DataContext).LoadCommand.Execute(dt);
}
}
private void myCalender_DisplayDateChanged(object sender, CalendarDateChangedEventArgs e)
{
DateTime dt = (DateTime)(e.AddedDate);
if (dt != null)
{
((ViewModel.ReportViewModel)base.DataContext).LoadCommand.Execute(dt);
}
}
private void btnCommit_Click(object sender, RoutedEventArgs e)
{
((ViewModel.ReportViewModel)base.DataContext).CommitCommand.Execute(null);
}
}
}
|
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wpf.Dao;
using Wpf.Model;
namespace Wpf.ViewModel
{
class IndexViewModel : ViewModelBase
{
IndexDao indexDao = new IndexDao();//连接Dao层
Index index;//初始化视图模型对象
private ObservableCollection<Index> indexView = new ObservableCollection<Index>();
public IndexViewModel()
{
SelectIndexData();
indexView.Add(index);
}
private void SelectIndexData()
{
index = indexDao.Get(); //使用Dao层获取数据
}
public ObservableCollection<Index> IndexView
{
get { return indexView; }
set { indexView = value; RaisePropertyChanged(); }
}
public string test()
{
return index.IndexName;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stone : Block
{
public override string Name
{
get
{
return "Stone";
}
}
public override int BlockID
{
get
{
return 3;
}
}
public override bool IsStackable
{
get
{
return true;
}
}
public override Face FrontFaceUV
{
get
{
return Face.GetFromIndex(1, 0);
}
}
public override Face BackFaceUV
{
get
{
return Face.GetFromIndex(1, 0);
}
}
public override Face TopFaceUV
{
get
{
return Face.GetFromIndex(1, 0);
}
}
public override Face BottomFaceUV
{
get
{
return Face.GetFromIndex(1, 0);
}
}
public override Face LeftFaceUV
{
get
{
return Face.GetFromIndex(1, 0);
}
}
public override Face RightFaceUV
{
get
{
return Face.GetFromIndex(1, 0);
}
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MusicAPI.APIs
{
public class WikiPediaClient : IWikiPediaClient
{
private readonly IApiHelper _ApiHelper;
public WikiPediaClient(IApiHelper apiHelper)
{
_ApiHelper = apiHelper;
}
public async Task<string> GetArtistInfo(string searchTitle)
{
string url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro=true&redirects=true&titles=" + searchTitle;
using (HttpResponseMessage response = await _ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
var datastring = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(datastring);
var page = (JObject)json["query"]["pages"];
var pageId = page.Properties().First().Name;
var artistInfo = (JValue)page[pageId]["extract"];
return artistInfo.ToString();
}
else
{
throw new Exception(((int)response.StatusCode).ToString());
}
}
}
}
}
|
using Cafe.API.Models.Entities;
using Cafe.API.Models.Repository;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cafe.API.Controllers
{
[Route("api/clients")]
[ApiController]
public class ClientController : ControllerBase
{
private readonly IDataRepository<Client> _dataRepository;
private readonly ILogger<ClientController> _logger;
public ClientController(IDataRepository<Client> dataRepository,
ILogger<ClientController> logger)
{
_dataRepository = dataRepository;
_logger = logger;
}
// GET: api/clients
// ?sort=desc||asc
[HttpGet]
public IEnumerable<Client> Get(string sort)
{
try
{
IEnumerable<Client> clients;
switch (sort)
{
case "asc":
clients = _dataRepository.GetAll().OrderBy(x => x.SecondName);
break;
case "desc":
clients = _dataRepository.GetAll().OrderByDescending(x => x.SecondName);
break;
default:
clients = _dataRepository.GetAll();
break;
}
_logger.LogInformation($"Collection of clients was found");
return clients;
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return null;
}
}
// GET api/clients/5
[HttpGet("{id}", Name = "GetClient")]
public Client Get(int id)
{
try
{
return _dataRepository.Get(id);
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return null;
}
}
// POST api/clients
[HttpPost]
public void Post([FromBody] Client client)
{
_dataRepository.Add(client);
}
// PUT api/clients/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] Client client)
{
var entity = _dataRepository.Get(id);
_dataRepository.Update(entity, client);
}
// DELETE api/clients/5
[HttpDelete("{id}")]
public void Delete(int id)
{
var entity = _dataRepository.Get(id);
_dataRepository.Delete(entity);
}
[HttpGet("[action]")]
//PagingClients?pageNumber=1&&pageSize=5
public IEnumerable<Client> PagingClients(int? pageNumber, int? pageSize)
{
try
{
var clients = _dataRepository.GetAll();
var currentPageNumber = pageNumber ?? 1;
var currentPageSize = pageSize ?? 5;
_logger.LogInformation($"Amount of clients is {pageSize} on the page {pageNumber}");
return clients.Skip((currentPageNumber - 1)
* currentPageSize).Take(currentPageSize);
}
catch (Exception ex)
{
_logger.LogInformation($"{ex.Message}", ex);
return null;
}
}
[HttpGet]
[Route("[action]")]
//SearchClients?clientName=
public IEnumerable<Client> SearchClients(string clientName)
{
try
{
var clients = _dataRepository.GetAll()
.Where(c => c.SecondName.ToLower()
.StartsWith(clientName.ToLower()));
if (clients == null)
{
_logger.LogInformation($"Clients whose name begin with {clientName} not found");
return null;
}
_logger.LogInformation($"Clients whose name begin with {clientName} was found");
return clients;
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return null;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVP.Base.BaseRepository;
using MVP.Sample.Web.IRepositories;
namespace MVP.Sample.Web.Repositories
{
public class DependencyUC1Repository : BaseRepository<object>, IDependencyUC1Repository
{
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace SAAS.Mq.Socket.Channel
{
public class ClientMqConfig: MqConnectConfig
{
/// <summary>
/// 服务端 host地址
/// </summary>
public String host = "127.0.0.1";
/// <summary>
/// 服务端 监听端口号
/// </summary>
public int port = 10345;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Dapper;
namespace DemoF.Persistence.Repositories
{
using Core.Repositories;
using DemoF.Core.Contracts;
using System.Data;
using System.Data.SqlClient;
public abstract class GenericRepositoryDapper<TEntity> : IGenericRepositoryDapper<TEntity> where TEntity : class
{
protected DemofContext _context = new DemofContext(new DbContextOptions<DemofContext>());
protected readonly string _connectionString;
protected readonly string _tableName;
public GenericRepositoryDapper(string connectionString, string tableName)
{
_connectionString = connectionString;
_tableName = tableName;
}
public virtual IQueryable<TEntity> GetAll()
{
using (IDbConnection db = new SqlConnection(_connectionString))
{
return db.Query<TEntity>($"SELECT * FROM {_tableName}").AsQueryable();
}
}
public virtual async Task<IEnumerable<TEntity>> GetAllAsync()
{
using (IDbConnection db = new SqlConnection(_connectionString))
{
return await db.QueryAsync<TEntity>($"SELECT * FROM {_tableName}");
}
}
public virtual TEntity Get(int id)
{
using (IDbConnection db = new SqlConnection(_connectionString))
{
return db.Query<TEntity>($"SELECT * FROM {_tableName} WHERE Id = @id", new { id }).FirstOrDefault();
}
}
public virtual async Task<TEntity> GetAsync(int id)
{
using (IDbConnection db = new SqlConnection(_connectionString))
{
var query = $"SELECT * FROM {_tableName} WHERE Id = @id";
return (await db.QueryAsync<TEntity>(query, new { id })).FirstOrDefault();
}
}
public virtual TEntity Add(TEntity entity)
{
throw new NotImplementedException("Add");
}
public virtual async Task<TEntity> AddAsyn(TEntity t)
{
throw new NotImplementedException("AddAsyn");
}
public virtual async Task<int> DeleteAsyn(TEntity entity)
{
using (IDbConnection db = new SqlConnection(_connectionString))
{
var sqlQuery = $"DELETE FROM {_tableName} WHERE Id = @id";
return db.Execute(sqlQuery, entity);
}
}
public virtual async Task<TEntity> UpdateAsyn(IUpdatableModel model, object key)
{
if (model == null)
return null;
using (IDbConnection db = new SqlConnection(_connectionString))
{
db.Execute(model.GetUpdateQuery(), model);
}
return (TEntity)model;
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
this.disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
namespace AppendLists
{
using System;
using System.Collections.Generic;
using System.Linq;
public class StartUp
{
public static void Main()
{
List<List<string>> numbers = Console.ReadLine()
.Split('|')
.Reverse()
.Select(s => s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList())
.ToList();
foreach (var nums in numbers)
{
Console.Write(string.Join(" ", nums) + " ");
}
Console.WriteLine();
}
}
}
|
using Alabo.Data.People.UserTypes;
using Alabo.Validations;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Data.People.Circles.Domain.Entities
{
/// <summary>
/// 商圈
/// </summary>
[ClassProperty(Name = "商圈")]
[BsonIgnoreExtraElements]
[Table("People_Circle")]
[AutoDelete(IsAuto = true)]
public class Circle : UserTypeAggregateRoot<Circle>
{
/// <summary>
/// 商圈所属省份
/// </summary>
[Display(Name = "省份编码")]
[Required(AllowEmptyStrings = false, ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public long ProvinceId { get; set; }
/// <summary>
/// 商圈所属城市,可以等于null
/// </summary>
[Display(Name = "城市编码")]
[Required(AllowEmptyStrings = false, ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public long CityId { get; set; }
/// <summary>
/// 商圈所属区域
/// </summary>
[Display(Name = "区县编码")]
[Required(AllowEmptyStrings = false, ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public long CountyId { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StrongEffect : MonoBehaviour {
public Transform pos;
MuniaControllerScript muniaS;
Rigidbody2D rb;
bool faceRight = true;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
muniaS = GameObject.FindGameObjectWithTag("Player").GetComponent<MuniaControllerScript>();
}
void OnEnable()
{
transform.position = pos.transform.position;
if (this.gameObject.name == "BigSlash")
{
if (muniaS.facingRight == true)
{
if (faceRight == false) Flip();
rb.velocity = new Vector2(8f, 0);
}
else
{
if (faceRight == true) Flip();
rb.velocity = new Vector2(-8f, 0);
}
}
if (this.gameObject.name == "impacto")
{
StartCoroutine(Inactive(1));
}
if (this.gameObject.name == "BigSlash")
{
StartCoroutine(Inactive(1.2f));
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "enemy")
{
enemyScript es = collision.gameObject.GetComponent<enemyScript>();
if (es.canBeSmashed == true)
{
if (this.gameObject.name == "impacto")
{
es.TakeDamage(3, 7);
es.Smashing();
}
if (this.gameObject.name == "BigSlash")
{
es.TakeDamage(2, 10);
es.Smashing();
}
}
}
if (collision.gameObject.tag == "bullet")
{
collision.gameObject.GetComponent<BulletScript>().Disappear(0.01f);
}
if (collision.gameObject.tag == "beacon")
{
BeaconScript bs = collision.gameObject.GetComponent<BeaconScript>();
bs.TakeDamage(2);
}
}
void Flip() //direction facing
{
faceRight = !faceRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
IEnumerator Inactive(float timing)
{
yield return new WaitForSeconds(timing);
gameObject.SetActive(false);
}
}
|
using System;
using System.Activities.Presentation.Toolbox;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Phenix.Core;
using Phenix.Core.Reflection;
using Phenix.Core.Workflow;
using Phenix.Workflow.Windows.Desinger.PropertyEditing;
namespace Phenix.Workflow.Windows.Desinger.Helper
{
internal class ToolboxControlHelper
{
public static ToolboxControl BuildToolboxControl()
{
ToolboxControl result = new ToolboxControl();
AddToolboxItemWrapperFromBaseDirectory(result);
AddSystemActivities(result);
return result;
}
public static ToolboxItemWrapper AddToolboxItemWrapper(ToolboxControl toolboxControl, Type toolType)
{
PluginAssemblyNamePropertyValueEditor.AddAttributeTable(toolType);
WorkerRolePropertyValueEditor.AddAttributeTable(toolType);
AssemblyDescriptionAttribute assemblyDescriptionAttribute = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(toolType.Assembly, typeof(AssemblyDescriptionAttribute));
string categoryName = assemblyDescriptionAttribute != null
? !String.IsNullOrEmpty(assemblyDescriptionAttribute.Description)
? assemblyDescriptionAttribute.Description
: toolType.Namespace
: toolType.Namespace;
ToolboxCategory category = toolboxControl.Categories.FirstOrDefault(p => p.CategoryName == categoryName);
if (category == null)
{
category = new ToolboxCategory(categoryName);
toolboxControl.Categories.Add(category);
}
DescriptionAttribute descriptionAttribute = AppUtilities.GetFirstCustomAttribute<DescriptionAttribute>(toolType);
ToolboxItemWrapper result = new ToolboxItemWrapper(toolType, descriptionAttribute != null ? descriptionAttribute.Description : toolType.Name);
category.Add(result);
return result;
}
public static void AddToolboxItemWrapper(ToolboxControl toolboxControl, string fileName)
{
foreach (Type item in Utilities.LoadExportedSubclassTypes(fileName, false, typeof(IActivity)))
AddToolboxItemWrapper(toolboxControl, item);
}
public static void AddToolboxItemWrapperFromBaseDirectory(ToolboxControl toolboxControl)
{
foreach (Type item in Utilities.LoadExportedSubclassTypesFromBaseDirectory(false, typeof(IActivity)))
AddToolboxItemWrapper(toolboxControl, item);
}
private static void AddSystemActivities(ToolboxControl toolBox)
{
ToolboxCategory category = new ToolboxCategory("控制流");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Sequence), "Sequence"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.If), "If"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Switch<>), "Switch<>"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.DoWhile), "DoWhile"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.While), "While"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.ForEach<>), "ForEach<>"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Parallel), "Parallel"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.ParallelForEach<>), "ParallelForEach<>"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Pick), "Pick"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.PickBranch), "PickBranch"));
category = new ToolboxCategory("流程图");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Flowchart), "Flowchart"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.FlowDecision), "FlowDecision"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.FlowSwitch<>), "FlowSwitch<>"));
category = new ToolboxCategory("运行时");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Persist), "Persist"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.TerminateWorkflow), "TerminateWorkflow"));
category = new ToolboxCategory("基元");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Assign), "Assign"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Delay), "Delay"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.InvokeAction), "InvokeAction"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.WriteLine), "WriteLine"));
category = new ToolboxCategory("事务");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.CancellationScope), "CancellationScope"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.CompensableActivity), "CompensableActivity"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Compensate), "Compensate"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Confirm), "Confirm"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.TransactionScope), "TransactionScope"));
category = new ToolboxCategory("集合");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.AddToCollection<>), "AddToCollection<>"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.ClearCollection<>), "ClearCollection<>"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.ExistsInCollection<>), "ExistsInCollection<>"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.RemoveFromCollection<>), "RemoveFromCollection<>"));
category = new ToolboxCategory("错误处理");
toolBox.Categories.Add(category);
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Rethrow), "Rethrow"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.Throw), "Throw"));
category.Add(new ToolboxItemWrapper(typeof(System.Activities.Statements.TryCatch), "TryCatch"));
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace DataAccessLayer.Migrations
{
public partial class initiate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ContactNumbers");
migrationBuilder.AddColumn<string>(
name: "Phone1",
table: "Contacts",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Phone2",
table: "Contacts",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Phone3",
table: "Contacts",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Phone4",
table: "Contacts",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Phone1",
table: "Contacts");
migrationBuilder.DropColumn(
name: "Phone2",
table: "Contacts");
migrationBuilder.DropColumn(
name: "Phone3",
table: "Contacts");
migrationBuilder.DropColumn(
name: "Phone4",
table: "Contacts");
migrationBuilder.CreateTable(
name: "ContactNumbers",
columns: table => new
{
ID = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ContactID = table.Column<long>(type: "bigint", nullable: true),
PhoneNumber = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactNumbers", x => x.ID);
table.ForeignKey(
name: "FK_ContactNumbers_Contacts_ContactID",
column: x => x.ContactID,
principalTable: "Contacts",
principalColumn: "ContactID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_ContactNumbers_ContactID",
table: "ContactNumbers",
column: "ContactID");
}
}
}
|
using System;
using ApiTemplate.Common.Enums.Exceptions;
namespace ApiTemplate.Common.Exceptions
{
public class NullArgumentException:AppException
{
public NullArgumentException()
: base(CustomStatusCodes.ArgumentNull)
{
}
public NullArgumentException(string message)
: base(CustomStatusCodes.ArgumentNull, message)
{
}
public NullArgumentException(object additionalData)
: base(CustomStatusCodes.ArgumentNull, additionalData)
{
}
public NullArgumentException(string message, object additionalData)
: base(CustomStatusCodes.ArgumentNull, message, additionalData)
{
}
public NullArgumentException(string message, Exception exception)
: base(CustomStatusCodes.ArgumentNull, message, exception)
{
}
public NullArgumentException(string message, Exception exception, object additionalData)
: base(CustomStatusCodes.BadRequest, message, exception, additionalData)
{
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="TypeExtensions.cs" company="AnoriSoft">
// Copyright (c) AnoriSoft. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Anori.Extensions
{
using System;
using System.Reflection;
using JetBrains.Annotations;
/// <summary>
/// Type Extensions.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Determines whether this instance is nullable.
/// </summary>
/// <param name="genericTypeInfo">The generic type information.</param>
/// <returns>
/// <c>true</c> if the specified generic type information is nullable; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">genericTypeInfo is null.</exception>
public static bool IsNullable([NotNull] this TypeInfo genericTypeInfo)
{
if (genericTypeInfo == null)
{
throw new ArgumentNullException(nameof(genericTypeInfo));
}
return Nullable.GetUnderlyingType(genericTypeInfo) != null;
}
/// <summary>
/// Determines whether this instance is nullable.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the specified type is nullable; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">type is null.</exception>
public static bool IsNullable([NotNull] this Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return Nullable.GetUnderlyingType(type) != null;
}
/// <summary>
/// Determines whether this instance is nullable.
/// </summary>
/// <typeparam name="T">Type.</typeparam>
/// <returns>
/// <c>true</c> if this instance is nullable; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullable<T>() => typeof(T).IsNullable();
}
} |
using System;
namespace iSukces.Code.AutoCode
{
public interface IDirectCodeWriter
{
void ChangeIndent(int plus);
void OpenNamespace(string ns);
string TypeName(Type type);
void WriteLn(string txt);
}
} |
//
// Copyright (c) Autodesk, Inc. All rights reserved.
//
// This computer source code and related instructions and comments are the
// unpublished confidential and proprietary information of Autodesk, Inc.
// and are protected under Federal copyright and state trade secret law.
// They may not be disclosed to, copied or used by any third party without
// the prior written consent of Autodesk, Inc.
//
using UnityEngine;
using UnityEngine.Events;
namespace Autodesk.Forge.ARKit {
[System.Serializable]
public class QRDecodedEvent : UnityEvent<string, Vector3, Quaternion> {
}
public interface IQRCodeDecoderInterface {
#region Interface Properties
//bool _searchUntilFound
//[SerializeField]
//QRDecodedEvent _qrDecoded ;
#endregion
#region Unity APIs
//void OnEnable () ;
//void OnDisable () ;
//void Update () ;
#endregion
#region Interface Methods
//bool InitCamera () ;
//void StopCamera () ;
//void ProcessCameraFrame () ;
void ToggleScan () ;
#endregion
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using DG.Tweening;
using System.Text.RegularExpressions;
public class UIController : MonoBehaviour
{
public Canvas levelCanvas;
public Canvas hud;
public Text headerText;
public Text footerText;
public Text levelText;
public Text timerText;
public Text scoreText;
public Image redFlashImage;
public Image victoryImage;
public Image loseImage;
public RectTransform flashText;
public GameObject mainMenuButton;
public GameObject nextLevelButton;
public GameObject restartLevelButton;
public GameObject tapToResumeButton;
public GameLogic gamelogic;
public string[] completedLevels;
public Sequence scoreTextTween;
void Start()
{
completedLevels = Regex.Split(PlayerPrefs.GetString("Levels", ""), "-");
hud.enabled = false;
mainMenuButton.SetActive(false);
nextLevelButton.SetActive(false);
restartLevelButton.SetActive(false);
timerText.text = "Time: " + Mathf.Ceil(gamelogic.timer).ToString();
}
// Update is called once per frame
void Update()
{
}
public void FlashText(Text text, string textValue, float time, float alphaValue)
{
text.text = textValue;
text.DOFade(alphaValue, time);
}
public void SetButtons(bool main, bool next, bool restart)
{
if (main)
{
DOVirtual.DelayedCall(1.8f, () => mainMenuButton.SetActive(main));
DOVirtual.DelayedCall(1.8f, () => mainMenuButton.GetComponent<Animator>().Play("MainMenuButton"));
}
else
{
mainMenuButton.SetActive(main);
}
if (next)
{
DOVirtual.DelayedCall(1.5f, () => nextLevelButton.SetActive(next));
DOVirtual.DelayedCall(1.5f, () => nextLevelButton.GetComponent<Animator>().Play("NextLevelButton"));
}
else
{
nextLevelButton.SetActive(next);
}
if (restart)
{
DOVirtual.DelayedCall(1.5f, () => restartLevelButton.SetActive(restart));
DOVirtual.DelayedCall(1.5f, () => restartLevelButton.GetComponent<Animator>().Play("RestartLevelButton"));
}
else
{
restartLevelButton.SetActive(restart);
}
}
public void TapToResume()
{
tapToResumeButton.SetActive(false);
if (footerText.text == gamelogic.tutorialText)
{
footerText.DOFade(0f, 1f);
headerText.DOFade(0f, 1f);
DOVirtual.DelayedCall(1f, () => gamelogic.gamestate = GameLogic.GameState.Ongoing);
}
else
{
FlashText(levelText, "Level " + gamelogic.levelID.ToString(), 1f, 0f);
FlashText(headerText, gamelogic.objectiveHeader, 1f, 0f);
FlashText(footerText, gamelogic.objectiveInfo, 1f, 0f);
if (gamelogic.tutorialText == "")
{
DOVirtual.DelayedCall(1f, () => gamelogic.gamestate = GameLogic.GameState.Ongoing);
}
else
{
Sequence mySeq = DOTween.Sequence();
mySeq.Append(footerText.DOFade(0f, 1f));
mySeq.Join(headerText.DOFade(0f, 1f));
mySeq.Append(footerText.GetComponent<Text>().DOText(gamelogic.tutorialText, 0f));
mySeq.Join(headerText.GetComponent<Text>().DOText(gamelogic.tutorialTitle, 0f));
mySeq.Append(footerText.DOFade(1f, 1f));
mySeq.Join(headerText.DOFade(1f, 1f));
mySeq.AppendCallback(() => tapToResumeButton.SetActive(true));
}
}
}
public void ShowVictoryImage()
{
DOVirtual.DelayedCall(0.75f, () => victoryImage.enabled = true);
DOVirtual.DelayedCall(0.75f, () => victoryImage.gameObject.GetComponent<Animator>().Play("Victory"));
}
public void ShowLoseImage()
{
DOVirtual.DelayedCall(0.75f, () => loseImage.enabled = true);
DOVirtual.DelayedCall(0.75f, () => loseImage.DOColor(new Color(1f,1f,1f,1f) , 1f));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BuyNSell.Models
{
public class CustomValidationDataAnnotation
{
}
public class EmailIdExistOrNot : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
BuyNSell_DbEntities objDB = new BuyNSell_DbEntities();
if (value != null)
{
String EmailId = value.ToString();
UserMaster CheckEmailId = objDB.UserMasters.Where(e => e.EmailId.Equals(EmailId)).FirstOrDefault();
if (CheckEmailId != null)
{
return new ValidationResult("EmailId Already Exist");
}
else
{
return ValidationResult.Success;
}
}
return null;
}
}
} |
using Entities.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace Entities.Configuration
{
class PhoneNumberConfiguration : IEntityTypeConfiguration<PhoneNumber>
{
public void Configure(EntityTypeBuilder<PhoneNumber> builder)
{
builder.HasData(
new PhoneNumber
{
Id = 1,
Type = "მობილური",
Number = "555940789",
PersonId = 1,
});
builder.HasData(
new PhoneNumber
{
Id = 2,
Type = "სახლის",
Number = "58890309",
PersonId = 2
});
builder.HasData(
new PhoneNumber
{
Id = 3,
Type = "სახლის",
Number = "58890309",
PersonId = 4
});
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace BanSupport
{
public class ScrollGalleryAutoArrangeWindow : EditorWindow
{
private ScrollGallery scrollGallery;
private float spacing = 10;
private Vector2 scaleDelta = new Vector2(-0.1f, -0.1f);
private Vector2 widthAndHeightDelta = new Vector2(-10, -10);
private RectTransform maskTransform = null;
public static void ShowWindow(ScrollGallery scrollGallery)
{
var window = GetWindow<ScrollGalleryAutoArrangeWindow>("ScrollGalleryAutoArrangeWindow");
window.scrollGallery = scrollGallery;
var r = window.position;
r.width = 500;
r.x = Screen.currentResolution.width / 2 - r.width / 2;
r.y = Screen.currentResolution.height / 2 - r.height / 2;
window.position = r;
}
private void OnGUI()
{
this.scrollGallery = EditorGUILayout.ObjectField("当前ScrollSystem:", this.scrollGallery, typeof(ScrollGallery), true) as ScrollGallery;
if (this.scrollGallery == null) { return; }
GUILayout.Label("当前滚动方向:" + ((this.scrollGallery.Direction == ScrollGallery.ScrollDirection.Vertical) ? "垂直" : "水平"));
GUILayout.BeginHorizontal();
this.spacing = Mathf.Max(0, EditorGUILayout.FloatField("间隔:", this.spacing));
if (GUILayout.Button("自动排列"))
{
AutoArrangeBySpacing();
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("对齐:");
if (this.scrollGallery.Direction == ScrollGallery.ScrollDirection.Vertical)
{
if (GUILayout.Button("左对齐"))
{
AutoArrangeByFitLeft();
}
if (GUILayout.Button("中对齐"))
{
AutoArrangeByFitCenter();
}
if (GUILayout.Button("右对齐"))
{
AutoArrangeByFitRight();
}
}
else
{
if (GUILayout.Button("上对齐"))
{
AutoArrangeByFitUp();
}
if (GUILayout.Button("中对齐"))
{
AutoArrangeByFitCenter();
}
if (GUILayout.Button("下对齐"))
{
AutoArrangeByFitDown();
}
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Scale Delta:");
this.scaleDelta = EditorGUILayout.Vector2Field("", this.scaleDelta);
if (GUILayout.Button("等差调整"))
{
DoScale();
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Width&Height Delta:");
this.widthAndHeightDelta = EditorGUILayout.Vector2Field("", this.widthAndHeightDelta);
if (GUILayout.Button("等差调整"))
{
DoWidthAndHeight();
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
this.maskTransform = EditorGUILayout.ObjectField("Mask:", this.maskTransform, typeof(RectTransform), true) as RectTransform;
if (this.maskTransform != null && GUILayout.Button("匹配大小和位置"))
{
FitMask();
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
if (GUILayout.Button("创建父物体RectMask,进行裁切"))
{
var origin = scrollGallery.transform as RectTransform;
var temp = new GameObject("RectMask", typeof(RectTransform)).transform as RectTransform;
temp.gameObject.AddComponent<UnityEngine.UI.RectMask2D>();
temp.transform.SetParent(scrollGallery.transform.parent);
temp.anchorMin = origin.anchorMin;
temp.anchorMax = origin.anchorMax;
temp.anchoredPosition = origin.anchoredPosition;
temp.sizeDelta = origin.sizeDelta;
temp.transform.localScale = origin.transform.localScale;
origin.transform.SetParent(temp);
}
}
private void AutoArrangeBySpacing()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
if (scrollGallery.Direction == ScrollGallery.ScrollDirection.Vertical)
{
var lastTransfrom = mainTransform;
for (int i = scrollGallery.MainIndex; i >= 0; i--)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "根据spacing自动排列位置");
curTransform.anchoredPosition = lastTransfrom.anchoredPosition + Vector2.up * (spacing + lastTransfrom.sizeDelta.y / 2 * lastTransfrom.localScale.y + curTransform.sizeDelta.y / 2 * curTransform.localScale.y);
lastTransfrom = curTransform;
}
lastTransfrom = mainTransform;
for (int i = scrollGallery.MainIndex + 2; i < scrollGallery.Splits.Length; i++)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "根据spacing自动排列位置");
curTransform.anchoredPosition = lastTransfrom.anchoredPosition + Vector2.down * (spacing + lastTransfrom.sizeDelta.y / 2 * lastTransfrom.localScale.y + curTransform.sizeDelta.y / 2 * curTransform.localScale.y);
lastTransfrom = curTransform;
}
}
else
{
var lastTransfrom = mainTransform;
for (int i = scrollGallery.MainIndex; i >= 0; i--)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "根据spacing自动排列位置");
curTransform.anchoredPosition = lastTransfrom.anchoredPosition + Vector2.left * (spacing + lastTransfrom.sizeDelta.x / 2 * lastTransfrom.localScale.x + curTransform.sizeDelta.x / 2 * curTransform.localScale.x);
lastTransfrom = curTransform;
}
lastTransfrom = mainTransform;
for (int i = scrollGallery.MainIndex + 2; i < scrollGallery.Splits.Length; i++)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "根据spacing自动排列位置");
curTransform.anchoredPosition = lastTransfrom.anchoredPosition + Vector2.right * (spacing + lastTransfrom.sizeDelta.x / 2 * lastTransfrom.localScale.x + curTransform.sizeDelta.x / 2 * curTransform.localScale.x);
lastTransfrom = curTransform;
}
}
}
private void AutoArrangeByFitLeft()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
float leftEdge = mainTransform.anchoredPosition.x - mainTransform.sizeDelta.x / 2 * mainTransform.localScale.x;
for (int i = 0; i < this.scrollGallery.Splits.Length; i++)
{
var curTransform = this.scrollGallery.Splits[i];
if (curTransform == mainTransform) { continue; }
Undo.RecordObject(curTransform, "AutoArrangeByFitLeft");
var newAnchoredPosition = curTransform.anchoredPosition;
newAnchoredPosition.x = leftEdge + curTransform.sizeDelta.x / 2 * curTransform.localScale.x;
curTransform.anchoredPosition = newAnchoredPosition;
}
}
private void AutoArrangeByFitRight()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
float rightEdge = mainTransform.anchoredPosition.x + mainTransform.sizeDelta.x / 2 * mainTransform.localScale.x;
for (int i = 0; i < this.scrollGallery.Splits.Length; i++)
{
var curTransform = this.scrollGallery.Splits[i];
if (curTransform == mainTransform) { continue; }
Undo.RecordObject(curTransform, "AutoArrangeByFitRight");
var newAnchoredPosition = curTransform.anchoredPosition;
newAnchoredPosition.x = rightEdge - curTransform.sizeDelta.x / 2 * curTransform.localScale.x;
curTransform.anchoredPosition = newAnchoredPosition;
}
}
private void AutoArrangeByFitUp()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
float upEdge = mainTransform.anchoredPosition.y + mainTransform.sizeDelta.y / 2 * mainTransform.localScale.y;
for (int i = 0; i < this.scrollGallery.Splits.Length; i++)
{
var curTransform = this.scrollGallery.Splits[i];
if (curTransform == mainTransform) { continue; }
Undo.RecordObject(curTransform, "AutoArrangeByFitUp");
var newAnchoredPosition = curTransform.anchoredPosition;
newAnchoredPosition.y = upEdge - curTransform.sizeDelta.y / 2 * curTransform.localScale.y;
curTransform.anchoredPosition = newAnchoredPosition;
}
}
private void AutoArrangeByFitDown()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
float downEdge = mainTransform.anchoredPosition.y - mainTransform.sizeDelta.y / 2 * mainTransform.localScale.y;
for (int i = 0; i < this.scrollGallery.Splits.Length; i++)
{
var curTransform = this.scrollGallery.Splits[i];
if (curTransform == mainTransform) { continue; }
Undo.RecordObject(curTransform, "AutoArrangeByFitDown");
var newAnchoredPosition = curTransform.anchoredPosition;
newAnchoredPosition.y = downEdge + curTransform.sizeDelta.y / 2 * curTransform.localScale.y;
curTransform.anchoredPosition = newAnchoredPosition;
}
}
private void AutoArrangeByFitCenter()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
if (scrollGallery.Direction == ScrollGallery.ScrollDirection.Vertical)
{
float center = mainTransform.anchoredPosition.x;
for (int i = 0; i < this.scrollGallery.Splits.Length; i++)
{
var curTransform = this.scrollGallery.Splits[i];
if (curTransform == mainTransform) { continue; }
Undo.RecordObject(curTransform, "AutoArrangeByFitCenter");
var newAnchoredPosition = curTransform.anchoredPosition;
newAnchoredPosition.x = center;
curTransform.anchoredPosition = newAnchoredPosition;
}
}
else
{
float center = mainTransform.anchoredPosition.y;
for (int i = 0; i < this.scrollGallery.Splits.Length; i++)
{
var curTransform = this.scrollGallery.Splits[i];
if (curTransform == mainTransform) { continue; }
Undo.RecordObject(curTransform, "AutoArrangeByFitCenter");
var newAnchoredPosition = curTransform.anchoredPosition;
newAnchoredPosition.y = center;
curTransform.anchoredPosition = newAnchoredPosition;
}
}
}
private void DoScale()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
var curScale = mainTransform.localScale;
for (int i = scrollGallery.MainIndex; i >= 0; i--)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "DoScale");
curScale += new Vector3(scaleDelta.x, scaleDelta.y, 0);
curTransform.localScale = curScale;
}
curScale = mainTransform.localScale;
for (int i = scrollGallery.MainIndex + 2; i < scrollGallery.Splits.Length; i++)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "DoScale");
curScale += new Vector3(scaleDelta.x, scaleDelta.y, 0);
curTransform.localScale = curScale;
}
}
private void DoWidthAndHeight()
{
var mainTransform = scrollGallery.Splits[scrollGallery.MainIndex + 1];
var curWidthAndHeight = mainTransform.sizeDelta;
for (int i = scrollGallery.MainIndex; i >= 0; i--)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "DoHeightAndWidth");
curWidthAndHeight += widthAndHeightDelta;
curTransform.sizeDelta = curWidthAndHeight;
}
curWidthAndHeight = mainTransform.sizeDelta;
for (int i = scrollGallery.MainIndex + 2; i < scrollGallery.Splits.Length; i++)
{
var curTransform = scrollGallery.Splits[i];
Undo.RecordObject(curTransform, "DoHeightAndWidth");
curWidthAndHeight += widthAndHeightDelta;
curTransform.sizeDelta = curWidthAndHeight;
}
}
private void FitMask()
{
RectBounds rectBounds = new RectBounds(scrollGallery.Splits[1]);
for (int i = 2; i < scrollGallery.Splits.Length - 1; i++)
{
var curSplit = scrollGallery.Splits[i];
rectBounds.Encapsulate(curSplit);
}
var listChildren = ListPool<Transform>.Get();
foreach (Transform aTrans in this.maskTransform)
{
listChildren.Add(aTrans);
}
listChildren.ForEach(temp => temp.SetParent(this.maskTransform.parent));
Undo.RecordObject(this.maskTransform, "FitMask Main");
this.maskTransform.position = rectBounds.center;
var lossyScale = this.maskTransform.lossyScale;
this.maskTransform.sizeDelta = new Vector2(rectBounds.width / lossyScale.x, rectBounds.height / lossyScale.y);
listChildren.ForEach(temp => temp.SetParent(this.maskTransform));
ListPool<Transform>.Release(listChildren);
Debug.Log("FitMask");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoConsumerDesktopApp.Models
{
public class SensorDaten
{
public ObservableCollection<BarometerSensor> SensorData
{
get;
set;
} = new ObservableCollection<BarometerSensor>();
}
}
|
namespace MTD.SDVTwitch.Models
{
public class Config
{
public string TwitchName { get; set; }
public string ClientId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using Aloha.ItemSystem;
using UniRx;
using UnityEngine;
public class CollectionPreviewer : MonoBehaviour
{
public event Action<string, IItem> OnPreviewingItemChanged;
private Dictionary<string, IItem> _previewingItems = new Dictionary<string, IItem>();
[SerializeField] GameObject GunPreview;
[SerializeField] BulletPreviewAnimation Trailpreview;
private void Start()
{
GunPreview.SetActive(true);
}
public void RegisterPreviewSelectionHandler(string slot, CollectionItemSelectionHandler itemSelectionHandler)
{
itemSelectionHandler.PreviewingItem
.Subscribe(item =>
{
SetPreviewingItem(slot, item);
if (slot == "Trail")
{
Trailpreview.EndAni();
Trailpreview.StartAni();
}
});
itemSelectionHandler.PreviewAction += ChangePreview;
}
private void SetPreviewingItem(string slot, IItem item)
{
_previewingItems[slot] = item;
OnPreviewingItemChanged?.Invoke(slot, item);
}
private void ChangePreview(int Id)
{
if (Id > 100 && Id < 110)
{
Trailpreview.gameObject.SetActive(false);
GunPreview.SetActive(true);
}
else if (Id > 200 && Id < 210)
{
Trailpreview.gameObject.SetActive(true);
GunPreview.SetActive(false);
}
}
}
|
namespace Athenaeum.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class FkUpdate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Comments",
c => new
{
CommentId = c.Int(nullable: false, identity: true),
AuthorId = c.String(),
Body = c.String(),
PostedDate = c.DateTime(nullable: false),
EntityId = c.Int(nullable: false),
CommentTypeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.CommentId)
.ForeignKey("dbo.CommentTypes", t => t.CommentTypeId, cascadeDelete: true)
.Index(t => t.CommentTypeId);
CreateTable(
"dbo.CommentTypes",
c => new
{
CommentTypeId = c.Int(nullable: false, identity: true),
Description = c.String(),
})
.PrimaryKey(t => t.CommentTypeId);
CreateTable(
"dbo.NewsArticles",
c => new
{
NewsArticleId = c.Int(nullable: false, identity: true),
Title = c.String(),
AuthorId = c.String(maxLength: 128),
PostedDate = c.DateTime(nullable: false),
Body = c.String(),
NewsCategoryId = c.Int(nullable: false),
ImageUrl = c.String(),
NumberOfComments = c.Int(nullable: false),
})
.PrimaryKey(t => t.NewsArticleId)
.ForeignKey("dbo.AspNetUsers", t => t.AuthorId)
.ForeignKey("dbo.NewsCategories", t => t.NewsCategoryId, cascadeDelete: true)
.Index(t => t.AuthorId)
.Index(t => t.NewsCategoryId);
CreateTable(
"dbo.NewsCategories",
c => new
{
NewsCategoryId = c.Int(nullable: false, identity: true),
Description = c.String(),
})
.PrimaryKey(t => t.NewsCategoryId);
AddColumn("dbo.AspNetUsers", "BattleTag", c => c.String());
AddColumn("dbo.AspNetUsers", "Introduction", c => c.String());
AddColumn("dbo.AspNetUsers", "ImageUrl", c => c.String());
}
public override void Down()
{
DropForeignKey("dbo.NewsArticles", "NewsCategoryId", "dbo.NewsCategories");
DropForeignKey("dbo.NewsArticles", "AuthorId", "dbo.AspNetUsers");
DropForeignKey("dbo.Comments", "CommentTypeId", "dbo.CommentTypes");
DropIndex("dbo.NewsArticles", new[] { "NewsCategoryId" });
DropIndex("dbo.NewsArticles", new[] { "AuthorId" });
DropIndex("dbo.Comments", new[] { "CommentTypeId" });
DropColumn("dbo.AspNetUsers", "ImageUrl");
DropColumn("dbo.AspNetUsers", "Introduction");
DropColumn("dbo.AspNetUsers", "BattleTag");
DropTable("dbo.NewsCategories");
DropTable("dbo.NewsArticles");
DropTable("dbo.CommentTypes");
DropTable("dbo.Comments");
}
}
}
|
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
using Ofl.Net.Http.ApiClient.Json;
using Ofl.Threading.Tasks;
namespace Ofl.Atlassian.Jira.V3
{
public class JiraClient : JsonApiClient, IJiraClient
{
#region Constructor
public JiraClient(
HttpClient httpClient,
IOptions<JiraClientConfiguration> jiraClientConfigurationOptions
) : base(httpClient)
{
// Validate parameters.
_jiraClientConfigurationOptions = jiraClientConfigurationOptions
?? throw new ArgumentNullException(nameof(jiraClientConfigurationOptions));
}
#endregion
#region Instance, read-only state.
private readonly IOptions<JiraClientConfiguration> _jiraClientConfigurationOptions;
#endregion
#region Implementation of IJiraClient
public Task<GetWatchersResponse> GetWatchersAsync(
GetWatchersRequest request,
CancellationToken cancellationToken
)
{
// Validate parameters.
if (request == null) throw new ArgumentNullException(nameof(request));
// The url.
string url = $"/issue/{ request.IssueIdOrKey }/watchers";
// Get JSON.
return GetAsync<GetWatchersResponse>(url, cancellationToken);
}
public Task RemoveWatcherAsync(
RemoveWatcherRequest request,
CancellationToken cancellationToken
)
{
// Validate parameters.
if (request == null) throw new ArgumentNullException(nameof(request));
// The url.
string url = $"/issue/{ request.IssueIdOrKey }/watchers";
// Add the username.
url = QueryHelpers.AddQueryString(url, "accountId", request.AccountId);
// Delete.
return DeleteAsync(url, cancellationToken);
}
public Task<CreateOrUpdateRemoteIssueLinkResponse> CreateOrUpdateRemoteIssueLinkAsync(
CreateOrUpdateRemoteIssueLinkRequest request,
CancellationToken cancellationToken
)
{
// Validate parameters.
if (request == null) throw new ArgumentNullException(nameof(request));
// The url.
string url = $"/issue/{ request.IssueIdOrKey }/remotelink";
// Post.
return PostAsync<RemoteIssueLink, CreateOrUpdateRemoteIssueLinkResponse>(
url, request.RemoteIssueLink, cancellationToken);
}
public Task<GetIssueLinkTypesResponse> GetIssueLinkTypesAsync(
CancellationToken cancellationToken
)
{
// Validate parameters.
// The URL.
const string url = "/issueLinkType";
// Get.
return GetAsync<GetIssueLinkTypesResponse>(url, cancellationToken);
}
public Task LinkIssuesAsync(
LinkIssuesRequest request,
CancellationToken cancellationToken
)
{
// Validate parameters.
if (request == null) throw new ArgumentNullException(nameof(request));
// The url.
const string url = "/issueLink";
// Post.
return PostAsync(url, request, cancellationToken);
}
#endregion
#region Overrides of JsonApiClient
protected override ValueTask<string> FormatUrlAsync(
string url,
CancellationToken cancellationToken
)
{
// validate parameters.
if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url));
// Create the API url.
return ValueTaskExtensions.FromResult(_jiraClientConfigurationOptions.Value.CreateApiUri(url));
}
protected override async Task<HttpResponseMessage> ProcessHttpResponseMessageAsync(
HttpResponseMessage httpResponseMessage,
CancellationToken cancellationToken
)
{
// Validate parameters.
if (httpResponseMessage == null) throw new ArgumentNullException(nameof(httpResponseMessage));
// If the response code is valid, just return the response message.
if (httpResponseMessage.IsSuccessStatusCode) return httpResponseMessage;
// Deserailize the response into errors.
ErrorCollection errorCollection = await httpResponseMessage
.ToObjectAsync<ErrorCollection>(cancellationToken)
.ConfigureAwait(false);
// Throw an exception.
throw new JiraException(errorCollection);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using KartObjects.Entities;
namespace KartSystem
{
public class POSGroupSettings:Entity
{
public override string FriendlyName
{
get { return "Свойства группы устройств"; }
}
public List<PayType> PayTypes;
public List<POSParameter> POSParameters;
public List<POSButtonAction> POSButtonActions;
public List<PosDiscount> POSDiscounts;
public List<HeaderString> HeaderStrings;
}
}
|
using DChild.Gameplay.Combat.StatusEffects.Configurations;
using DChild.Gameplay.Objects.Characters;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Combat.StatusEffects
{
public class CorrosionInflicter : StatusInflicter<CorrosionStatus, CorrosionConfig> { }
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Experimental.UIElements.GraphView;
using UnityEngine;
using UnityEngine.Experimental.PlayerLoop;
using UnityEngine.Experimental.UIElements;
using Random = UnityEngine.Random;
public class Agent : MonoBehaviour
{
public Agent curTarget;
[SerializeField]
public List<Creature> predators {
get { return AgentManager.predatorLookup[(int) creatureType]; }
}
[SerializeField]
public List<Creature> prey;
[SerializeField]
public Creature creatureType;
public Agent captor;
public Agent pursuer;
public List<Agent> heldPrey;
public List<Agent> capturedPrey;
public bool isTargeted;
public bool isAlive;
public bool hasEaten;
public enum State{normal, pursue, scared, tired, sleep, dead}
public enum Creature{lichen, drone, lowlife, crawler, hunter}
public enum Job {gather, defend}
public Job job = Job.gather;
[SerializeField]
public State state;
public float health = 1;
public float hunger = 1;
public float energy = 10;
public float speed = 1;
public float nutrition = 1;
public float xOffset;
public float yOffset;
public float capacity = 1;
public float weight = 1;
public float carriedWeight;
public float turnRadius = 2;
public bool scavenger;
private Vector3 velocity;
public Transform homeParent;
private Vector3 homePos;
public Vector3 home
{
get
{
if (homeParent != null)
{
return homeParent.position;
}
else
{
return homePos;
}
}
}
public Vector3 distanceToTarget
{
get { return curTarget.transform.position - transform.position; }
}
public Vector3 distanceToHome
{
get { return home - transform.position; }
}
public Vector3 distanceToPursuer
{
get { return pursuer.transform.position - transform.position; }
}
public void Awake()
{
Init();
}
protected void Init()
{
homePos = transform.position;
xOffset = Random.Range(-9999f, 9999f);
yOffset = Random.Range(-9999f, 9999f);
AgentManager.entities[(int)creatureType].Add(this);
isAlive = true;
hunger = Random.Range(5f, 10f);
energy = Random.Range(-1f, 1f);
}
protected bool FindClosestTarget()
{
float distance = Mathf.Infinity;
int index = 0;
int i = 0;
bool foundTarget = false;
if (prey.Count <= 0) return false;
Agent newTarget = null;
foreach (Creature p in prey)
{
foreach (Agent a in AgentManager.entities[(int) p])
{
float curDistance = Vector3.Distance(transform.position, a.transform.position);
if (a != this && a.job != Job.defend && curDistance < distance && (a.isAlive || (!a.isAlive && scavenger)) &&
!a.isTargeted)
{
if (a.captor != null && (a.captor == this || a.captor.creatureType == creatureType))
{
}
else
{
distance = curDistance;
newTarget = a;
foundTarget = true;
}
}
i++;
}
}
if (foundTarget)
{
if (curTarget != null)
{
StopChasing();
}
curTarget = newTarget;
curTarget.pursuer = this;
curTarget.isTargeted = true;
return true;
}
return false;
}
protected bool FindClosestPredator()
{
float distance = Mathf.Infinity;
int index = 0;
int i = 0;
bool foundTarget = false;
if (predators.Count <= 0) return false;
Agent newTarget = null;
foreach (Creature p in predators)
{
foreach (Agent a in AgentManager.entities[(int) p])
{
float curDistance = Vector3.Distance(transform.position, a.transform.position);
if (a != this && curDistance < distance && a.isAlive && !a.isTargeted)
{
if (a.captor != null && (a.captor == this || a.captor.creatureType == creatureType))
{
}
else
{
distance = curDistance;
newTarget = a;
foundTarget = true;
}
}
i++;
}
}
if (foundTarget && distance < 1)
{
if (curTarget != null)
{
StopChasing();
}
curTarget = newTarget;
curTarget.pursuer = this;
curTarget.isTargeted = true;
return true;
}
return false;
}
void StopChasing()
{
curTarget.isTargeted = false;
curTarget.pursuer = null;
if (curTarget.state == State.scared)
{
curTarget.ChangeState(State.normal);
}
curTarget = null;
}
protected void CatchTarget()
{
hunger = curTarget.nutrition;
energy = curTarget.nutrition;
curTarget.Caught();
curTarget.transform.parent = transform;
curTarget.transform.position = transform.position;
carriedWeight += curTarget.weight;
heldPrey.Add(curTarget);
if (curTarget.captor != null)
{
if (curTarget.captor.heldPrey.Contains(curTarget))
{
curTarget.captor.heldPrey.Remove(curTarget);
}else if (curTarget.captor.capturedPrey.Contains(curTarget))
{
curTarget.captor.capturedPrey.Remove(curTarget);
}
}
curTarget.captor = this;
if (carriedWeight >= capacity)
{
ChangeState(State.tired);
}
else
{
ChangeState(State.normal);
}
hasEaten = true;
curTarget = null;
}
public void Caught()
{
ChangeState(State.dead);
}
protected void Pursue()
{
if (curTarget != null)
{
Vector3 targetDir = (curTarget.transform.position - transform.position);
if (targetDir.magnitude > 1)
{
targetDir.Normalize();
FindClosestTarget();
}else if (targetDir.magnitude > 1)
{
if (curTarget.state != State.scared)
{
curTarget.ChangeState(State.scared);
}
}
else if (targetDir.magnitude < 0.2f)
{
targetDir.Normalize();
}
velocity = Vector3.Lerp(velocity, targetDir * speed, Time.deltaTime * turnRadius);
// if (!curTarget.isAlive)
// {
// if (!FindClosestTarget())
// {
// ChangeState(State.tired);
// }
// }
}
if (distanceToTarget.magnitude < 0.1f)
{
CatchTarget();
}
if (energy < 0 && !hasEaten)
{
ChangeState(State.tired);
}
}
protected void Sleep()
{
velocity = Vector3.Lerp(velocity, Vector3.zero, Time.deltaTime * 5);
energy += Time.deltaTime * 2;
if (energy > 10)
{
ChangeState(State.normal);
}
hasEaten = false;
}
protected void ReturnHome()
{
Vector3 targetDir = (home - transform.position);
if (targetDir.magnitude > 1)
{
targetDir.Normalize();
}
velocity = Vector3.Lerp(velocity, targetDir * speed, Time.deltaTime * turnRadius);
if (Vector3.Distance(home, transform.position) < 0.1f)
{
if (heldPrey.Count > 0)
{
DropTarget();
}
if (energy > 0)
{
ChangeState(State.normal);
}
else
{
ChangeState(State.sleep);
}
}
}
protected void Flee()
{
Vector3 targetDir;
if (distanceToPursuer.magnitude < 1)
{
targetDir = transform.position - pursuer.transform.position;
}
else
{
targetDir = home - transform.position;
}
velocity = Vector3.Lerp(velocity, targetDir.normalized * speed, Time.deltaTime * turnRadius);
if (distanceToPursuer.magnitude > 1)
{
ChangeState(State.normal);
}
}
protected void Search()
{
float xDir = Mathf.PerlinNoise(Time.time * -xOffset, Time.time + -yOffset) - 0.5f;
float yDir = Mathf.PerlinNoise(Time.time * xOffset, Time.time + yOffset) - 0.5f;
Vector3 moveDir = new Vector3(xDir, 0,yDir) * 2;
velocity = Vector3.Lerp(velocity, moveDir * speed, Time.deltaTime);
}
protected void Patrol()
{
transform.RotateAround(home, Vector3.up, Time.deltaTime * 10);
float xDir = Mathf.PerlinNoise(Time.time * -xOffset, Time.time + -yOffset) - 0.5f;
float yDir = Mathf.PerlinNoise(Time.time * xOffset, Time.time + yOffset) - 0.5f;
Vector3 moveDir = new Vector3(xDir, 0, yDir) * 2;
velocity = Vector3.Lerp(velocity, moveDir * speed, Time.deltaTime);
}
protected void Defend()
{
if (curTarget != null)
{
Vector3 targetDir = (curTarget.transform.position - transform.position);
if (targetDir.magnitude > 1)
{
targetDir.Normalize();
}else if (targetDir.magnitude < 1)
{
if (curTarget.state != State.scared)
{
curTarget.ChangeState(State.scared);
}
}
else if (targetDir.magnitude < 0.2f)
{
targetDir.Normalize();
}
velocity = Vector3.Lerp(velocity, targetDir * speed, Time.deltaTime * turnRadius);
}
if (distanceToHome.magnitude > 1)
{
ChangeState(State.tired);
}
}
protected void Attack()
{
//attacking is pursuing except the target is not caught, just killed
}
protected void DropTarget()
{
foreach (Agent a in heldPrey)
{
a.transform.parent = homeParent;
a.isTargeted = false;
a.DropTarget();
capturedPrey.Add(a);
a.transform.position = home + Vector3.up * 0.05f * capturedPrey.Count;
}
heldPrey.Clear();
carriedWeight = 0;
}
protected void DropPrey()
{
// ???
}
protected void LeaveState(State s)
{
switch (s)
{
case State.scared :
break;
case State.tired :
break;
case State.pursue:
if (curTarget != null)
{
StopChasing();
}
break;
}
}
protected void ChangeState(State s)
{
LeaveState(state);
switch (s)
{
case State.dead:
velocity = Vector3.zero;
isAlive = false;
break;
case State.scared :
break;
case State.tired :
break;
case State.pursue:
break;
}
state = s;
}
private void OnDestroy()
{
if (captor != null)
{
if (captor.heldPrey.Contains(this))
{
captor.heldPrey.Remove(this);
}else if (captor.capturedPrey.Contains(this))
{
captor.capturedPrey.Remove(this);
}
}
if (curTarget != null)
{
StopChasing();
}
}
void Update()
{
hunger -= Time.deltaTime;
if (hunger < -10)
{
// ChangeState(State.dead);
}
if (state != State.sleep && state != State.normal)
{
//energy -= Time.deltaTime;
}
if (isAlive)
{
transform.position += velocity * Time.deltaTime;
}
switch (state)
{
case State.normal:
if (job == Job.defend)
{
Patrol();
if (FindClosestPredator())
{
ChangeState(State.pursue);
}
}else if (job == Job.gather)
{
Search();
if (FindClosestTarget())
{
ChangeState(State.pursue);
}
}
if (energy < 0)
{
ChangeState(State.tired);
}
break;
case State.pursue :
if (job == Job.gather)
{
Pursue();
}else if (job == Job.defend)
{
Defend();
}
break;
case State.scared :
Flee();
break;
case State.tired :
ReturnHome();
break;
case State.sleep:
Sleep();
break;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AGCompressedAir.Windows.Common;
using AGCompressedAir.Windows.Models;
using AGCompressedAir.Windows.Services.DialogService;
using AGCompressedAir.Windows.Services.PartService;
using AGCompressedAir.Windows.ViewModels.Base;
using Prism.Events;
namespace AGCompressedAir.Windows.ViewModels
{
public class PartListViewModel : ListViewModelBase<Part>
{
public PartListViewModel(IEventAggregator eventAggregator, IDialogService dialogService,
IPartService partService) : base(eventAggregator)
{
DialogService = dialogService;
PartService = partService;
}
private IDialogService DialogService { get; }
private IPartService PartService { get; }
protected override async Task<List<Part>> OnLoadItemsAsync()
{
return await PartService.ListAsync(SearchTerm);
}
private async Task DeleteServiceAsync()
{
await PartService.DeleteAsync(SelectedItem);
}
protected override async Task OnAddAsync()
{
await DialogService.ShowContentDialogAsync(ViewNames.PartManageView);
}
protected override async Task OnEditAsync(Part selectedItem)
{
await DialogService.ShowContentDialogAsync(ViewNames.PartManageView, selectedItem);
}
protected override async Task OnDeleteAsync(Part selectedItem)
{
var delete = false;
await DialogService.ShowMessageDialogAsync("Are you sure you want to delete the selected Part?",
"Delete Part",
"Delete", () => { delete = true; }, "Cancel");
if (delete)
{
await DeleteServiceAsync();
}
}
}
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Org.Common;
using Org.Common.DataProvider;
using Org.Common.Domain;
using Org.Common.Exception;
using Org.Common.Manager;
using Org.Common.Model;
using Org.Common.Options;
namespace Org.Services
{
internal class UserManager : IUserManager
{
private readonly UserManager<EmployeePortalUser> _userManager;
private readonly IDatabaseMigrationProvider _migrationProvider;
private readonly SignInManager<EmployeePortalUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly AuthorizationOptions _authorizationOptions;
public UserManager(UserManager<EmployeePortalUser> userManager, IDatabaseMigrationProvider migrationProvider, SignInManager<EmployeePortalUser> signInManager,
RoleManager<IdentityRole> roleManager, IOptions<AuthorizationOptions> options)
{
_userManager = userManager;
_migrationProvider = migrationProvider;
_signInManager = signInManager;
_roleManager = roleManager;
_authorizationOptions = options.Value;
}
public async Task<User> Register(RegistrationModel model)
{
await _migrationProvider.MigrateDb();
EmployeePortalUser user = null;
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
var result = await _userManager.CreateAsync(new EmployeePortalUser
{
Email = model.Email,
UserName = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
DOB=model.DOB,
}, model.Password);
if (!result.Succeeded)
{
throw new BadRegistrationRequestException(result.Errors);
}
user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == model.Email);
if (model.AdminKey == _authorizationOptions.AdminCreationKey)
{
if (!await _roleManager.Roles.AnyAsync(r => r.Name == Constants.Roles.ADMINISTRATOR))
{
await _roleManager.CreateAsync(new IdentityRole(Constants.Roles.ADMINISTRATOR));
}
//This is adding user to role, i e making him an admin
await _userManager.AddToRoleAsync(user, Constants.Roles.ADMINISTRATOR);
}
scope.Complete();
}
var roles = await _userManager.GetRolesAsync(user);
return new User
{
Roles = roles.ToList(),
Email = user.Email,
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
DOB=user.DOB,
};
}
public async Task<User> Login(string login, string password)
{
var user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == login);
if (user == null)
{
throw new NotAuthorizedException("There is no user with provided login and password");
}
var result = await _signInManager.CheckPasswordSignInAsync(user, password, true);
if (!result.Succeeded)
{
throw new NotAuthorizedException("There is no user with provided login and password");
}
var roles = await _userManager.GetRolesAsync(user);
return new User
{
Email = user.Email,
Id = user.Id,
Roles = roles.ToList(),
FirstName = user.FirstName,
LastName = user.LastName
};
}
}
} |
using Alabo.Datas.Ef.SqlServer;
using Microsoft.EntityFrameworkCore;
namespace Alabo.Datas.UnitOfWorks.SqlServer {
/// <summary>
/// 工作单元
/// </summary>
public class SqlServerUnitOfWork : MsSqlUnitOfWork, IUnitOfWork {
/// <summary>
/// 初始化工作单元
/// </summary>
/// <param name="options">配置项</param>
/// <param name="unitOfWorkManager">工作单元服务</param>
public SqlServerUnitOfWork(DbContextOptions options, IUnitOfWorkManager unitOfWorkManager) : base(options,
unitOfWorkManager) {
}
}
} |
using System;
using System.Numerics;
using System.Text;
namespace Tools
{
public class DynamicMatrix
{
private dynamic matrix;
public DynamicMatrix(dynamic Array2D)
{
matrix = Array2D;
}
public static DynamicMatrix operator +(DynamicMatrix a, DynamicMatrix b)
{
Type t = GetLargestType(a, b);
if (a.matrix.GetLength(0) == b.matrix.GetLength(0) &&
a.matrix.GetLength(1) == b.matrix.GetLength(1))
{
dynamic resMatrix = Array.CreateInstance(t, a.matrix.GetLength(0), a.matrix.GetLength(1));
for (int i = 0; i < a.matrix.GetLength(0); i++)
{
for (int j = 0; j < a.matrix.GetLength(1); j++)
{
resMatrix[i, j] = a[i, j] + b[i, j];
}
}
return new DynamicMatrix(resMatrix);
}
else
{
throw new ArgumentException();
}
}
public static DynamicMatrix operator -(DynamicMatrix a, DynamicMatrix b)
{
Type t = GetLargestType(a, b);
if (a.matrix.GetLength(0) == b.matrix.GetLength(0) &&
a.matrix.GetLength(1) == b.matrix.GetLength(1))
{
dynamic resMatrix = Array.CreateInstance(t, a.matrix.GetLength(0), a.matrix.GetLength(1));
for (int i = 0; i < a.matrix.GetLength(0); i++)
{
for (int j = 0; j < a.matrix.GetLength(1); j++)
{
resMatrix[i, j] = a[i, j] - b[i, j];
}
}
return new DynamicMatrix(resMatrix);
}
else
{
throw new ArgumentException();
}
}
public static DynamicMatrix operator *(DynamicMatrix a, int k)
{
Type t = a.matrix[0, 0].GetType();
dynamic resMatrix = Array.CreateInstance(t, a.matrix.GetLength(0), a.matrix.GetLength(1));
for (int i = 0; i < a.matrix.GetLength(0); i++)
{
for (int j = 0; j < a.matrix.GetLength(1); j++)
{
resMatrix[i, j] = a[i, j] * k;
}
}
return new DynamicMatrix(resMatrix);
}
public static DynamicMatrix operator *(DynamicMatrix a, DynamicMatrix b)
{
Type t = GetLargestType(a, b);
if (a.matrix.GetLength(1) == b.matrix.GetLength(0))
{
dynamic cMatrix = Array.CreateInstance(t, a.matrix.GetLength(0), b.matrix.GetLength(1));
for (int i = 0; i < cMatrix.GetLength(0); i++)
{
for (int j = 0; j < cMatrix.GetLength(1); j++)
{
for (int r = 0; r < a.matrix.GetLength(1); r++)
{
cMatrix[i, j] += a[i, r] * b[r, j];
}
}
}
return new DynamicMatrix(cMatrix);
}
else
{
throw new ArgumentException();
}
}
public static DynamicMatrix IdentityMatrix(int size, Type type)
{
dynamic matrix = Array.CreateInstance(type, size, size);
for (int i = 0; i < size; i++)
{
matrix[i, i] = 1;
}
return new DynamicMatrix(matrix);
}
public int GetLength(int dimension)
{
return matrix.GetLength(dimension);
}
public Type GetInnerType()
{
return matrix[0, 0].GetType();
}
public dynamic this[int x, int y]
{
get { return this.matrix[x, y]; }
}
public override string ToString()
{
StringBuilder res = new StringBuilder();
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
res.AppendFormat("{0} ", this[i, j]);
}
res.Append('\n');
}
return res.ToString().TrimEnd('\n');
}
private static readonly Type tInt = typeof(int),
tUInt = typeof(uint),
tLong = typeof(long),
tULong = typeof(ulong),
tFloat = typeof(float),
tDouble = typeof(double),
tDecimal = typeof(decimal),
tBigInteger = typeof(BigInteger);
private static Type GetLargestType(DynamicMatrix a, DynamicMatrix b)
{
Type t1 = a.matrix[0, 0].GetType();
Type t2 = b.matrix[0, 0].GetType();
if (t1 == tDecimal || t2 == tDecimal)
{
return tDecimal;
}
if (t1 == tDouble || t2 == tDouble)
{
return tDouble;
}
if (t1 == tFloat || t2 == tFloat)
{
return tFloat;
}
if (t1 == tBigInteger || t2 == tBigInteger)
{
return tBigInteger;
}
if (t1 == tULong || t2 == tULong)
{
return tULong;
}
if (t1 == tLong || t2 == tLong)
{
return tLong;
}
if (t1 == tUInt || t2 == tUInt)
{
return tUInt;
}
return tInt;
}
}
}
|
using System.Collections.Generic;
using Flux.src.Platform.OpenGL;
namespace Flux.src.Flux.Renderer
{
public abstract class VertexArray
{
public abstract void Bind();
public abstract void Unbind();
public abstract void AddVertexBuffer(VertexBuffer vertexBuffer);
public abstract void SetIndexBuffer(IndexBuffer indexBuffer);
public abstract List<VertexBuffer> GetVertexBuffers();
public abstract IndexBuffer GetIndexBuffer();
public static VertexArray Create()
{
return new OpenGLVertexArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Uintra.Core.Controls.FileUpload;
using Uintra.Infrastructure.Caching;
using Umbraco.Web.WebApi;
namespace Uintra.Controllers
{
public class FileController : UmbracoApiController
{
private const int MaxUploadCount = 10;
private readonly ICacheService cacheService;
public FileController(ICacheService cacheService)
{
this.cacheService = cacheService;
}
[HttpPost]
public async Task<HttpResponseMessage> UploadSingle()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var file = provider.Contents.Single();
var fileName = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
var result = new TempFile
{
Id = Guid.NewGuid(),
FileName = fileName,
FileBytes = buffer
};
cacheService.GetOrSet(result.Id.ToString(), () => result, DateTimeOffset.Now.AddDays(1));
return Request.CreateResponse(HttpStatusCode.OK, result.Id);
}
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var idList = new List<Guid>(MaxUploadCount);
foreach (var file in provider.Contents.Take(MaxUploadCount))
{
var fileName = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
var tempFile = new TempFile
{
Id = Guid.NewGuid(),
FileName = fileName,
FileBytes = buffer
};
cacheService.GetOrSet(tempFile.Id.ToString(), () => tempFile, DateTimeOffset.Now.AddDays(1));
idList.Add(tempFile.Id);
}
var result = string.Join(",", idList);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}
} |
namespace Communicator.Core.Domain
{
public enum UserStatusType
{
Iam=0,
Imnot=1,
DontDistrub=2,
Another=3
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using ODL.DomainModel;
using ODL.DomainModel.Organisation;
namespace ODL.DataAccess.Mappningar
{
public class OrganisationAvtalMappning : EntityTypeConfiguration<OrganisationAvtal>
{
public OrganisationAvtalMappning()
{
ToTable("Avtal.OrganisationAvtal");
HasKey(k => new {k.OrganisationId, k.AvtalId});
Property(e => e.OrganisationId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).HasColumnName("OrganisationFKId");
Property(e => e.AvtalId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).HasColumnName("AvtalFKId");
Property(e => e.ProcentuellFordelning).HasPrecision(5, 2);
}
}
} |
using GHCIQuizSolution.DBContext;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace GHCIQuizSolution.Controllers.UserControllers
{
public class UserQuizController : BaseQuizController
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public Object Get(String id)
{
logger.Info("The Id is:" + id);
var quizs = QuizDB.Quizs
.Select(quiz => new
{
quiz.description,
quiz.id,
quiz.level,
quiz.passpoint,
quiz.imageUrl,
quiz.successMessage,
quiz.failedMessage,
quiz.instruction,
UserQuizs =
quiz.UserQuizs
.Where(userQuiz => userQuiz.userId == id)
//.OrderBy(u => u.attempt)
.Select(userQuiz => new
{
userQuiz.id,
userQuiz.quizId,
userQuiz.status,
userQuiz.timeTakenInterval,
userQuiz.attempt
//,
//QuizUser = new
//{
// userQuiz.QuizUser.currentUserQuizId,
// userQuiz.QuizUser.email,
// userQuiz.QuizUser.id,
// userQuiz.QuizUser.name
//}
})
//.OrderBy(u => u.attempt)
.DefaultIfEmpty()
})
.OrderBy(quiz => quiz.level);
return quizs;
}
public Object Post([FromBody]QuizUser quizUser)
{
var dbQuizUser = QuizDB.QuizUsers.First(u => u.id == quizUser.id);
// if there is no quiz assigned or the current quiz is completed then get the next quiz.
if (dbQuizUser.CurrentUserQuiz == null || dbQuizUser.CurrentUserQuiz.status == QUIZ_STATUS.COMPLETED_FAIL || dbQuizUser.CurrentUserQuiz.status == QUIZ_STATUS.COMPLETED_SUCCESS) {
this.SetNextQuiz(dbQuizUser);
this.SetNextQuestion(dbQuizUser);
}
// ensure that the request quizId is indeed the users next or inprogress quiz.
if (dbQuizUser.CurrentUserQuiz != null && dbQuizUser.CurrentUserQuiz.status == QUIZ_STATUS.IN_PROGRESS
&& dbQuizUser.CurrentUserQuiz.Quiz !=null && dbQuizUser.CurrentUserQuiz.Quiz.id == quizUser.CurrentUserQuiz.quizId)
{
this.SaveQuizDBChanges();
// return current user
return Ok(quizUser);
}
else {
//return NotFound();
throw new NotImplementedException();
}
}
}
}
|
//------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.BodyBasics
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
/// <summary>
/// Interaction logic for MainWindow
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
/// <summary>
/// Radius of drawn hand circles
/// </summary>
private const double HandSize = 30;
/// <summary>
/// Thickness of drawn joint lines
/// </summary>
private const double JointThickness = 3;
/// <summary>
/// Thickness of clip edge rectangles
/// </summary>
private const double ClipBoundsThickness = 10;
/// <summary>
/// Constant for clamping Z values of camera space points from being negative
/// </summary>
private const float InferredZPositionClamp = 0.1f;
/// <summary>
/// Brush used for drawing hands that are currently tracked as closed
/// </summary>
private readonly Brush handClosedBrush = new SolidColorBrush(Color.FromArgb(128, 255, 0, 0));
/// <summary>
/// Brush used for drawing hands that are currently tracked as opened
/// </summary>
private readonly Brush handOpenBrush = new SolidColorBrush(Color.FromArgb(128, 0, 255, 0));
/// <summary>
/// Brush used for drawing hands that are currently tracked as in lasso (pointer) position
/// </summary>
private readonly Brush handLassoBrush = new SolidColorBrush(Color.FromArgb(128, 0, 0, 255));
/// <summary>
/// Brush used for drawing joints that are currently tracked
/// </summary>
private readonly Brush trackedJointBrush = new SolidColorBrush(Color.FromArgb(255, 68, 192, 68));
/// <summary>
/// Brush used for drawing joints that are currently inferred
/// </summary>
private readonly Brush inferredJointBrush = Brushes.Yellow;
/// <summary>
/// Pen used for drawing bones that are currently inferred
/// </summary>
private readonly Pen inferredBonePen = new Pen(Brushes.Gray, 1);
/// <summary>
/// Drawing group for body rendering output
/// </summary>
private DrawingGroup drawingGroup;
/// <summary>
/// Drawing image that we will display
/// </summary>
private DrawingImage imageSource;
/// <summary>
/// Active Kinect sensor
/// </summary>
private KinectSensor kinectSensor = null;
/// <summary>
/// Coordinate mapper to map one type of point to another
/// </summary>
private CoordinateMapper coordinateMapper = null;
/// <summary>
/// Reader for body frames
/// </summary>
private BodyFrameReader bodyFrameReader = null;
/// <summary>
/// Array for the bodies
/// </summary>
private Body[] bodies = null;
/// <summary>
/// definition of bones
/// </summary>
private List<Tuple<JointType, JointType>> bones;
/// <summary>
/// Width of display (depth space)
/// </summary>
private int displayWidth;
/// <summary>
/// Height of display (depth space)
/// </summary>
private int displayHeight;
/// <summary>
/// List of colors for each body tracked
/// </summary>
private List<Pen> bodyColors;
/// <summary>
/// Current status text to display
/// </summary>
private string statusText = null;
/// <summary>
/// Initializes a new instance of the MainWindow class.
/// </summary>
public MainWindow()
{
// one sensor is currently supported
this.kinectSensor = KinectSensor.GetDefault();
// get the coordinate mapper
this.coordinateMapper = this.kinectSensor.CoordinateMapper;
// get the depth (display) extents
FrameDescription frameDescription = this.kinectSensor.DepthFrameSource.FrameDescription;
// get size of joint space
this.displayWidth = frameDescription.Width;
this.displayHeight = frameDescription.Height;
// open the reader for the body frames
this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();
// a bone defined as a line between two joints
this.bones = new List<Tuple<JointType, JointType>>();
// Torso
this.bones.Add(new Tuple<JointType, JointType>(JointType.Head, JointType.Neck));
this.bones.Add(new Tuple<JointType, JointType>(JointType.Neck, JointType.SpineShoulder));
this.bones.Add(new Tuple<JointType, JointType>(JointType.SpineShoulder, JointType.SpineMid));
this.bones.Add(new Tuple<JointType, JointType>(JointType.SpineMid, JointType.SpineBase));
this.bones.Add(new Tuple<JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.SpineShoulder, JointType.ShoulderLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.SpineBase, JointType.HipRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.SpineBase, JointType.HipLeft));
// Right Arm
this.bones.Add(new Tuple<JointType, JointType>(JointType.ShoulderRight, JointType.ElbowRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.ElbowRight, JointType.WristRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.WristRight, JointType.HandRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.HandRight, JointType.HandTipRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.WristRight, JointType.ThumbRight));
// Left Arm
this.bones.Add(new Tuple<JointType, JointType>(JointType.ShoulderLeft, JointType.ElbowLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.ElbowLeft, JointType.WristLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.WristLeft, JointType.HandLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.HandLeft, JointType.HandTipLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.WristLeft, JointType.ThumbLeft));
// Right Leg
this.bones.Add(new Tuple<JointType, JointType>(JointType.HipRight, JointType.KneeRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.KneeRight, JointType.AnkleRight));
this.bones.Add(new Tuple<JointType, JointType>(JointType.AnkleRight, JointType.FootRight));
// Left Leg
this.bones.Add(new Tuple<JointType, JointType>(JointType.HipLeft, JointType.KneeLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.KneeLeft, JointType.AnkleLeft));
this.bones.Add(new Tuple<JointType, JointType>(JointType.AnkleLeft, JointType.FootLeft));
// populate body colors, one for each BodyIndex
this.bodyColors = new List<Pen>();
this.bodyColors.Add(new Pen(Brushes.Red, 6));
this.bodyColors.Add(new Pen(Brushes.Orange, 6));
this.bodyColors.Add(new Pen(Brushes.Green, 6));
this.bodyColors.Add(new Pen(Brushes.Blue, 6));
this.bodyColors.Add(new Pen(Brushes.Indigo, 6));
this.bodyColors.Add(new Pen(Brushes.Violet, 6));
// set IsAvailableChanged event notifier
this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged;
// open the sensor
this.kinectSensor.Open();
// set the status text
this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
: Properties.Resources.NoSensorStatusText;
// Create the drawing group we'll use for drawing
this.drawingGroup = new DrawingGroup();
// Create an image source that we can use in our image control
this.imageSource = new DrawingImage(this.drawingGroup);
// use the window object as the view model in this simple example
this.DataContext = this;
// initialize the components (controls) of the window
this.InitializeComponent();
}
/// <summary>
/// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the bitmap to display
/// </summary>
public ImageSource ImageSource
{
get
{
return this.imageSource;
}
}
/// <summary>
/// Gets or sets the current status text to display
/// </summary>
public string StatusText
{
get
{
return this.statusText;
}
set
{
if (this.statusText != value)
{
this.statusText = value;
// notify any bound elements that the text has changed
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText"));
}
}
}
}
/// <summary>
/// Execute start up tasks
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
if (this.bodyFrameReader != null)
{
this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived;
}
}
/// <summary>
/// Execute shutdown tasks
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
if (this.bodyFrameReader != null)
{
// BodyFrameReader is IDisposable
this.bodyFrameReader.Dispose();
this.bodyFrameReader = null;
}
if (this.kinectSensor != null)
{
this.kinectSensor.Close();
this.kinectSensor = null;
}
}
/// <summary>
/// Handles the body frame data arriving from the sensor
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (this.bodies == null)
{
this.bodies = new Body[bodyFrame.BodyCount];
}
// The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
// As long as those body objects are not disposed and not set to null in the array,
// those body objects will be re-used.
bodyFrame.GetAndRefreshBodyData(this.bodies);
dataReceived = true;
}
}
if (dataReceived)
{
using (DrawingContext dc = this.drawingGroup.Open())
{
// Draw a transparent background to set the render size
dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
int penIndex = 0;
foreach (Body body in this.bodies)
{
Pen drawPen = this.bodyColors[penIndex++];
if (body.IsTracked)
{
this.DrawClippedEdges(body, dc);
IReadOnlyDictionary<JointType, Joint> joints = body.Joints;
// convert the joint points to depth (display) space
Dictionary<JointType, Point> jointPoints = new Dictionary<JointType, Point>();
foreach (JointType jointType in joints.Keys)
{
// sometimes the depth(Z) of an inferred joint may show as negative
// clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity)
CameraSpacePoint position = joints[jointType].Position;
if (position.Z < 0)
{
position.Z = InferredZPositionClamp;
}
DepthSpacePoint depthSpacePoint = this.coordinateMapper.MapCameraPointToDepthSpace(position);
jointPoints[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y);
}
this.DrawBody(joints, jointPoints, dc, drawPen);
this.DrawHand(body.HandLeftState, jointPoints[JointType.HandLeft], dc);
this.DrawHand(body.HandRightState, jointPoints[JointType.HandRight], dc);
}
}
// prevent drawing outside of our render area
this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
}
}
}
/// <summary>
/// Draws a body
/// </summary>
/// <param name="joints">joints to draw</param>
/// <param name="jointPoints">translated positions of joints to draw</param>
/// <param name="drawingContext">drawing context to draw to</param>
/// <param name="drawingPen">specifies color to draw a specific body</param>
private void DrawBody(IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, DrawingContext drawingContext, Pen drawingPen)
{
// Draw the bones
foreach (var bone in this.bones)
{
this.DrawBone(joints, jointPoints, bone.Item1, bone.Item2, drawingContext, drawingPen);
}
// Draw the joints
foreach (JointType jointType in joints.Keys)
{
Brush drawBrush = null;
TrackingState trackingState = joints[jointType].TrackingState;
if (trackingState == TrackingState.Tracked)
{
drawBrush = this.trackedJointBrush;
}
else if (trackingState == TrackingState.Inferred)
{
drawBrush = this.inferredJointBrush;
}
if (drawBrush != null)
{
drawingContext.DrawEllipse(drawBrush, null, jointPoints[jointType], JointThickness, JointThickness);
}
}
}
/// <summary>
/// Draws one bone of a body (joint to joint)
/// </summary>
/// <param name="joints">joints to draw</param>
/// <param name="jointPoints">translated positions of joints to draw</param>
/// <param name="jointType0">first joint of bone to draw</param>
/// <param name="jointType1">second joint of bone to draw</param>
/// <param name="drawingContext">drawing context to draw to</param>
/// /// <param name="drawingPen">specifies color to draw a specific bone</param>
private void DrawBone(IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, JointType jointType0, JointType jointType1, DrawingContext drawingContext, Pen drawingPen)
{
Joint joint0 = joints[jointType0];
Joint joint1 = joints[jointType1];
// If we can't find either of these joints, exit
if (joint0.TrackingState == TrackingState.NotTracked ||
joint1.TrackingState == TrackingState.NotTracked)
{
return;
}
// We assume all drawn bones are inferred unless BOTH joints are tracked
Pen drawPen = this.inferredBonePen;
if ((joint0.TrackingState == TrackingState.Tracked) && (joint1.TrackingState == TrackingState.Tracked))
{
drawPen = drawingPen;
}
drawingContext.DrawLine(drawPen, jointPoints[jointType0], jointPoints[jointType1]);
}
/// <summary>
/// Draws a hand symbol if the hand is tracked: red circle = closed, green circle = opened; blue circle = lasso
/// </summary>
/// <param name="handState">state of the hand</param>
/// <param name="handPosition">position of the hand</param>
/// <param name="drawingContext">drawing context to draw to</param>
private void DrawHand(HandState handState, Point handPosition, DrawingContext drawingContext)
{
switch (handState)
{
case HandState.Closed:
drawingContext.DrawEllipse(this.handClosedBrush, null, handPosition, HandSize, HandSize);
break;
case HandState.Open:
drawingContext.DrawEllipse(this.handOpenBrush, null, handPosition, HandSize, HandSize);
break;
case HandState.Lasso:
drawingContext.DrawEllipse(this.handLassoBrush, null, handPosition, HandSize, HandSize);
break;
}
}
/// <summary>
/// Draws indicators to show which edges are clipping body data
/// </summary>
/// <param name="body">body to draw clipping information for</param>
/// <param name="drawingContext">drawing context to draw to</param>
private void DrawClippedEdges(Body body, DrawingContext drawingContext)
{
FrameEdges clippedEdges = body.ClippedEdges;
if (clippedEdges.HasFlag(FrameEdges.Bottom))
{
drawingContext.DrawRectangle(
Brushes.Red,
null,
new Rect(0, this.displayHeight - ClipBoundsThickness, this.displayWidth, ClipBoundsThickness));
}
if (clippedEdges.HasFlag(FrameEdges.Top))
{
drawingContext.DrawRectangle(
Brushes.Red,
null,
new Rect(0, 0, this.displayWidth, ClipBoundsThickness));
}
if (clippedEdges.HasFlag(FrameEdges.Left))
{
drawingContext.DrawRectangle(
Brushes.Red,
null,
new Rect(0, 0, ClipBoundsThickness, this.displayHeight));
}
if (clippedEdges.HasFlag(FrameEdges.Right))
{
drawingContext.DrawRectangle(
Brushes.Red,
null,
new Rect(this.displayWidth - ClipBoundsThickness, 0, ClipBoundsThickness, this.displayHeight));
}
}
/// <summary>
/// Handles the event which the sensor becomes unavailable (E.g. paused, closed, unplugged).
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void Sensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e)
{
// on failure, set the status text
this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
: Properties.Resources.SensorNotAvailableStatusText;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CEMAPI.Models
{
public class InvoiceBrkupDtlDTO
{
public InvoiceBrkupDtlDTO()
{
this.CompanyName = "";
this.CompanyAddress = "";
this.CompanyCIN = "";
this.ProjectLogo = "";
this.ServiceTagReg = "";
this.VatReg = "";
this.InvoiceId = "";
//this.InvoiceDate = DateTime.Now;
this.ProjectCode = "";
this.ProjectName = "";
this.ProjectColor = "";
this.UnitNumber = "";
this.CustomerName = "";
this.MilestoneName = "";
//this.MilestoneCompletionDate = DateTime.Now;
this.TowardsLand = 0;
this.LandVatableComponent = 0;
this.LandNonVatableComponent = 0;
this.LandServiceTax = 0;
this.LandSBC = 0;
this.LandKKC = 0;
this.LandVAT = 0;
this.LandTotalTax = 0;
this.LandTotalAmount = 0;
this.TowardsConstn = 0;
this.ConstnVatableComponent = 0;
this.ConstnNonVatableComponent = 0;
this.ConstnServiceTax = 0;
this.ConstnSBC = 0;
this.ConstnKKC = 0;
this.ConstnVAT = 0;
this.ConstnTotalTax = 0;
this.ConstnTotalAmount = 0;
this.ConstnTotalNonVatableTax = 0;
this.ConstnTotalVatableTax = 0;
this.TowardsMaintn = 0;
this.MaintnServiceTax = 0;
this.MaintnSBC = 0;
this.MaintnKKC = 0;
this.MaintnVAT = 0;
this.MaintnTotalTax = 0;
this.MaintnTotalAmount = 0;
this.OtherCharges = 0;
this.OtherChargServiceTax = 0;
this.OtherChargSBC = 0;
this.OtherChargKKC = 0;
this.OtherChargVAT = 0;
this.OtherChargTotalTax = 0;
this.OtherChargTotalAmount = 0;
this.CustomisationCharges = 0;
this.CustmServiceTax = 0;
this.CustmSBC = 0;
this.CustmKKC = 0;
this.CustmVAT = 0;
this.CustmTotalTax = 0;
this.CustmTotalAmount = 0;
this.InterestCharges = 0;
this.IntrstServiceTax = 0;
this.IntrstSBC = 0;
this.IntrstKKC = 0;
this.IntrstVAT = 0;
this.IntrstTotalTax = 0;
this.IntrstTotalAmount = 0;
this.Reimbursements = 0;
this.ReimbServiceTax = 0;
this.ReimbSBC = 0;
this.ReimbKKC = 0;
this.ReimbVAT = 0;
this.ReimbTotalTax = 0;
this.ReimbTotalAmount = 0;
this.TotalAmount = 0;
this.TotalTax = 0;
this.BasicConsideration = 0;
this.TotalServiceTax = 0;
this.TotalSBC = 0;
this.TotalKKC = 0;
this.TotalVAT = 0;
this.TotalPayable = 0;
this.TDS = 0;
this.NetPayable = 0;
}
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyLogo { get; set; }
public string CompanyCIN { get; set; }
public string ProjectLogo { get; set; }
public string ServiceTagReg { get; set; }
public string VatReg { get; set; }
public string InvoiceId { get; set; }
public DateTime? InvoiceDate { get; set; }
public string ProjectCode { get; set; }
public string ProjectName { get; set; }
public string ProjectColor { get; set; }
public string UnitNumber { get; set; }
public string CustomerName { get; set; }
public string MilestoneName { get; set; }
public DateTime? MilestoneCompletionDate { get; set; }
#region LandCostBrkup
public decimal? TowardsLand { get; set; }
public decimal? LandVatableComponent { get; set; }
public decimal? LandNonVatableComponent { get; set; }
public decimal? LandServiceTax { get; set; }
public decimal? LandSBC { get; set; }
public decimal? LandKKC { get; set; }
public decimal? LandVAT { get; set; }
public decimal? LandTotalTax { get; set; }
public decimal? LandTotalAmount { get; set; }
#endregion LandCostBrkup
#region ConstnCostBrkup
public decimal? TowardsConstn { get; set; }
public decimal? ConstnVatableComponent { get; set; }
public decimal? ConstnNonVatableComponent { get; set; }
public decimal? ConstnServiceTax { get; set; }
public decimal? ConstnSBC { get; set; }
public decimal? ConstnKKC { get; set; }
public decimal? ConstnVAT { get; set; }
public decimal? ConstnTotalTax { get; set; }
public decimal? ConstnTotalAmount { get; set; }
public decimal? ConstnTotalVatableTax { get; set; }
public decimal? ConstnTotalNonVatableTax { get; set; }
#endregion ConstnCostBrkup
#region MaintnCostBrkup
public decimal? TowardsMaintn { get; set; }
public decimal? MaintnServiceTax { get; set; }
public decimal? MaintnSBC { get; set; }
public decimal? MaintnKKC { get; set; }
public decimal? MaintnVAT { get; set; }
public decimal? MaintnTotalTax { get; set; }
public decimal? MaintnTotalAmount { get; set; }
#endregion MaintnCostBrkup
#region OtherChrgsBrkup
public decimal? OtherCharges { get; set; }
public decimal? OtherChargServiceTax { get; set; }
public decimal? OtherChargSBC { get; set; }
public decimal? OtherChargKKC { get; set; }
public decimal? OtherChargVAT { get; set; }
public decimal? OtherChargTotalTax { get; set; }
public decimal? OtherChargTotalAmount { get; set; }
#endregion OtherChrgsBrkup
#region ReimbCostBrkup
public decimal? Reimbursements { get; set; }
public decimal? ReimbServiceTax { get; set; }
public decimal? ReimbSBC { get; set; }
public decimal? ReimbKKC { get; set; }
public decimal? ReimbVAT { get; set; }
public decimal? ReimbTotalTax { get; set; }
public decimal? ReimbTotalAmount { get; set; }
#endregion ReimbCostBrkup
#region InterestChargesBrkup
public decimal? InterestCharges { get; set; }
public decimal? IntrstServiceTax { get; set; }
public decimal? IntrstSBC { get; set; }
public decimal? IntrstKKC { get; set; }
public decimal? IntrstVAT { get; set; }
public decimal? IntrstTotalTax { get; set; }
public decimal? IntrstTotalAmount { get; set; }
#endregion InterestChargesBrkup
#region CustomisationChargesBrkup
public decimal? CustomisationCharges { get; set; }
public decimal? CustmServiceTax { get; set; }
public decimal? CustmSBC { get; set; }
public decimal? CustmKKC { get; set; }
public decimal? CustmVAT { get; set; }
public decimal? CustmTotalTax { get; set; }
public decimal? CustmTotalAmount { get; set; }
#endregion CustomizationChargesBrkup
public decimal? TotalAmount { get; set; }
public decimal? TotalTax { get; set; }
public decimal? TotalConsideration { get; set; }
public decimal? BasicConsideration { get; set; }
public decimal? TotalServiceTax { get; set; }
public decimal? TotalSBC { get; set; }
public decimal? TotalKKC { get; set; }
public decimal? TotalVAT { get; set; }
public decimal? TotalPayable { get; set; }
public decimal? TDS { get; set; }
public decimal? NetPayable { get; set; }
public decimal? TDSPercentage { get; set; }
public decimal? TDSAmnt { get; set; }
public int InvoicePaymentDueDays { get; set; }
public string CompanyPAN { get; set; }
public string CEMManagerName { get; set; }
public string CEMManagerEmail { get; set; }
public string PaymentDelayPeriod { get; set; }
public List<InvoiceBankDtls> invBankDtl = new List<InvoiceBankDtls>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.Globalize;
using Newtonsoft.Json;
namespace Client.Internal
{
public class Settings : ISettings
{
private readonly Internal.ILogger _logger;
public Settings()
{
_logger = (Internal.ILogger)Bootstrap.Instance.Services.GetService(typeof(Internal.ILogger));
Culture = Localize.Language.English;
DBPath = System.IO.Path.Combine(StaticFolders.GetUserFolder(), GlobalValues.DBFileName);
}
public Localize.Language Culture { get; set; }
public string DBPath { get; set; }
public void Save()
{
try
{
var value = JsonConvert.SerializeObject(this);
var path = System.IO.Path.Combine(StaticFolders.GetUserFolder(), GlobalValues.SettingsFileName);
System.IO.File.WriteAllText(path, value);
} catch (Exception ex)
{
_logger.Error(ex);
}
}
public void Load()
{
try
{
var path = System.IO.Path.Combine(StaticFolders.GetUserFolder(), GlobalValues.SettingsFileName);
if (System.IO.File.Exists(path))
{
var settings = JsonConvert.DeserializeObject<Settings>(System.IO.File.ReadAllText(path));
Culture = settings.Culture;
DBPath = settings.DBPath;
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CIS016_2.Week1
{
public partial class CountriesForm : Form
{
public CountriesForm()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
var countryName = tbCountry.Text;
if (string.IsNullOrEmpty(countryName))
{
MessageBox.Show("Please input country name!", "No value", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
lbCountries.Items.Add(countryName);
tbCountry.Text = string.Empty;
}
private void btnDelete_Click(object sender, EventArgs e)
{
var selectedItem = lbCountries.SelectedItem;
lbCountries.Items.Remove(selectedItem);
}
private void btnClear_Click(object sender, EventArgs e)
{
lbCountries.Items.Clear();
}
private void btnCancel_Click(object sender, EventArgs e)
{
tbCountry.Text = string.Empty;
}
}
}
|
/*
Extension de la classe d'entité Etat
!!Attention!!
Ce code source est généré automatiquement, toutes modifications seront perdues
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Controls;
using System.Globalization;
using System.Reflection;
using ArduinoAdmin.Lib;
using ArduinoAdmin.Formats;
namespace ArduinoAdmin.Model
{
/// <summary>
/// Implémente la validation des propriétés
/// </summary>
public class Etat : IDataErrorInfo
{
// Validation globale de l'entité
public string Error
{
get
{
string all_mess = "";
string msg;
all_mess += ((msg = this["Etat_Id"]) != String.Empty) ? (GetPropertyDesc("Etat_Id") + " :\n\t" + App.TranslateAppErrorCode(msg) + "\n") : String.Empty;
all_mess += ((msg = this["Nom"]) != String.Empty) ? (GetPropertyDesc("Nom") + " :\n\t" + App.TranslateAppErrorCode(msg) + "\n") : String.Empty;
all_mess += ((msg = this["Valeur"]) != String.Empty) ? (GetPropertyDesc("Valeur") + " :\n\t" + App.TranslateAppErrorCode(msg) + "\n") : String.Empty;
return all_mess;
}
}
// Validation par propriété
public string this[string propertyName]
{
get
{
string msg = String.Empty;
switch (propertyName)
{
case "Etat_Id":
if(this.Etat_Id == null){
msg = "NOT_NULL_RESTRICTION";
break;
}
// Pas de test
break;
case "Nom":
if(this.Nom == null){
msg = "NOT_NULL_RESTRICTION";
break;
}
// Pas de test
break;
case "Valeur":
if(this.Valeur == null)
break;
// Pas de test
break;
}
if (msg != String.Empty)
return GetPropertyDesc(propertyName) + ":\n" + App.TranslateAppErrorCode(msg);
return String.Empty;
}
}
public static string GetClassDesc()
{
return "Propriété d'un équipement";
}
public static string GetPropertyDesc(string propertyName)
{
switch (propertyName)
{
case "Etat_Id":
return "";
case "Nom":
return "Nom";
case "Valeur":
return "Valeur";
}
return "";
}
}
} |
using Xamarin.Forms;
namespace AsNum.XFControls {
/// <summary>
/// 边框
/// </summary>
public class Border : ContentView {
/// <summary>
/// 圆角大小
/// </summary>
public static readonly BindableProperty CornerRadiusProperty =
BindableProperty.Create("CornerRadius",
typeof(CornerRadius),
typeof(Border),
default(CornerRadius)
);
/// <summary>
/// 边框颜色
/// </summary>
public static readonly BindableProperty StrokeProperty =
BindableProperty.Create("Stroke",
typeof(Color),
typeof(Border),
Color.Default);
/// <summary>
/// 边框厚度
/// </summary>
public static readonly BindableProperty StrokeThicknessProperty =
BindableProperty.Create("StrokeThickness",
typeof(Thickness),
typeof(Border),
default(Thickness)
);
/// <summary>
/// 是否裁剪超出部分
/// </summary>
public static readonly BindableProperty IsClippedToBorderProperty =
BindableProperty.Create("IsClippedToBorder",
typeof(bool),
typeof(bool),
true);
/// <summary>
/// 圆角大小
/// </summary>
public CornerRadius CornerRadius {
get {
return (CornerRadius)base.GetValue(CornerRadiusProperty);
}
set {
base.SetValue(CornerRadiusProperty, value);
}
}
/// <summary>
/// 边框颜色
/// </summary>
public Color Stroke {
get {
return (Color)GetValue(StrokeProperty);
}
set {
SetValue(StrokeProperty, value);
}
}
/// <summary>
/// 边框宽度
/// </summary>
public Thickness StrokeThickness {
get {
return (Thickness)GetValue(StrokeThicknessProperty);
}
set {
SetValue(StrokeThicknessProperty, value);
}
}
/// <summary>
/// 是否裁剪超出部分
/// </summary>
public bool IsClippedToBorder {
get {
return (bool)GetValue(IsClippedToBorderProperty);
}
set {
SetValue(IsClippedToBorderProperty, value);
}
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class Global : MonoBehaviour {
private static readonly string UIModulePath = "Prefabs/UI/UIModule";
private static Global instance;
private bool destructing;
public InputManager Input { get; private set; }
public MapManager Maps { get; private set; }
public MemoryManager Memory { get; private set; }
public AudioManager Audio { get; private set; }
public SettingsCollection Settings { get; private set; }
public UIEngine UIEngine { get; private set; }
public PartyManager Party { get; private set; }
private IndexDatabase database;
public IndexDatabase Database {
get {
if (database == null && !destructing) {
database = IndexDatabase.Instance();
}
return database;
}
}
public static Global Instance() {
if (instance == null) {
GameObject globalObject = new GameObject();
// debug-ish and we don't serialize scenes
// globalObject.hideFlags = HideFlags.HideAndDontSave;
instance = globalObject.AddComponent<Global>();
instance.InstantiateManagers();
}
return instance;
}
public void Update() {
SetFullscreenMode();
}
public void Awake() {
DontDestroyOnLoad(gameObject);
MoonSharp.Interpreter.UserData.RegisterAssembly();
}
public void OnDestroy() {
destructing = true;
}
private void InstantiateManagers() {
Settings = gameObject.AddComponent<SettingsCollection>();
Input = gameObject.AddComponent<InputManager>();
Maps = gameObject.AddComponent<MapManager>();
Memory = gameObject.AddComponent<MemoryManager>();
Audio = gameObject.AddComponent<AudioManager>();
Party = gameObject.AddComponent<PartyManager>();
GameObject module = Instantiate(Resources.Load<GameObject>(UIModulePath));
module.transform.parent = transform;
UIEngine = module.GetComponentInChildren<UIEngine>();
}
private void SetFullscreenMode() {
// not sure if this "check" is necessary
// actually performing this here is kind of a hack
if (Settings != null && Screen.fullScreen != Settings.GetBoolSetting(SettingsConstants.Fullscreen).Value) {
Screen.fullScreen = Settings.GetBoolSetting(SettingsConstants.Fullscreen).Value;
}
}
}
|
using LoanAPound.Db.Model;
using System;
namespace LoanAPound.LoanEngine
{
/// <summary>
/// Represents the call to the third party credit score provider
/// </summary>
public class CreditScoreProviderClient : ICreditScoreProviderClient
{
private static readonly Random random = new Random();
public double GetScore(CreditScoreProvider creditScoreProvider, Applicant applicant)
{
// Use details from creditScoreProvider to setup and make the call to the 3rd party
// possibly call a strategy pattern if support different types of calls e.g. REST, SOAP..
// This where we would call the creditScoreProvider and get the credit score
// passing details from applicant object
return 1 + (random.NextDouble() * (100 - 1));
}
}
}
|
using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using SlackBot;
namespace Bot.Extensions
{
public static class Collector
{
private static readonly CloudBlobClient BlobClient;
static Collector()
{
BlobClient = CloudStorageAccount
.Parse(ConfigurationManager.AppSettings["Storage.ConnectionString"])
.CreateCloudBlobClient();
}
public static async Task Collect(SlackCommand cmd)
{
var blob = BlobClient
.GetContainerReference("bot")
.GetBlockBlobReference(DateTime.UtcNow.Ticks.ToString());
await blob.UploadTextAsync(JsonConvert.SerializeObject(cmd));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimonSaysProject_OfekRon_ItayShachar
{
public partial class Form_SimonSays : Form
{
public Form_SimonSays()
{
InitializeComponent();
SetImagesArray();
}
private const int arrayLength = 4;
private PictureBox[] array_Colors = new PictureBox[arrayLength];
Random rnd = new Random();
private int[] blinkOrder = new int[10];
private int k;
private int countFlash = 0;
private int level = 1;
private int countCompBlink = -1;
private int countClicks = 0;
string strStage;
private Win_SimonSays WinnerMessage = new Win_SimonSays();
private Lose_SimonSays LoseMessage = new Lose_SimonSays();
private void SetImagesArray()
{
array_Colors[0] = pictureBox0;
array_Colors[1] = pictureBox1;
array_Colors[2] = pictureBox2;
array_Colors[3] = pictureBox3;
for (int i = 0; i < blinkOrder.Length; i++)
{
blinkOrder[i] = rnd.Next(0, 4);
}
}
private void startButton_Click(object sender, EventArgs e)
{
array_Colors[0].Visible = true;
array_Colors[1].Visible = true;
array_Colors[2].Visible = true;
array_Colors[3].Visible = true;
startButton.Visible = false;
SetImagesArray();
countClicks = 0;
countCompBlink = -1;
level = 1;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
countCompBlink++;
countFlash = 0;
timer2.Start();
}
private void timer2_Tick(object sender, EventArgs e)
{
if (countFlash == 0)
array_Colors[blinkOrder[countCompBlink]].Visible = false;
else if (countFlash == 1)
array_Colors[blinkOrder[countCompBlink]].Visible = true;
else
{
if ((countCompBlink + 1) >= level)
timer1.Stop();
timer2.Stop();
}
countFlash++;
}
public void pictureBox_Click(object sender, EventArgs e)
{
PictureBox pictureBox = sender as PictureBox;
countClicks++;
string imageName = pictureBox.Name;
k = int.Parse(imageName.Substring(imageName.Length - 1));
countFlash = 0;
timer3.Start();
if (k != blinkOrder[countClicks - 1])
{
LoseMessage.Show();
array_Colors[0].Visible = false;
array_Colors[1].Visible = false;
array_Colors[2].Visible = false;
array_Colors[3].Visible = false;
startButton.Visible = true;
}
if (countClicks == level)
{
strStage = "Stage " + level;
stage.Text = strStage;
stage.Visible = true;
countClicks = 0;
countCompBlink = -1;
if (level == blinkOrder.Length)
{
//המחשב מציג הודעה, מעלים את התמונות ומחזיר את כפתור ההתחלה
WinnerMessage.Show();
array_Colors[0].Visible = false;
array_Colors[1].Visible = false;
array_Colors[2].Visible = false;
array_Colors[3].Visible = false;
startButton.Visible = true;
}
else
{
// המחשב ממשיך לשלב הבא
timer1.Start();
level++;
}
}
}
private void timer3_Tick(object sender, EventArgs e)
{
if (countFlash == 0)
array_Colors[k].Visible = false;
else if (countFlash == 1)
array_Colors[k].Visible = true;
else
timer3.Stop();
countFlash++;
}
}
}
|
using OnlineTitleSearch.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace OnlineTitleSearch.Context
{
public class SearchDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Search> Searches { get; set; }
public DbSet<Domain> Domains { get; set; }
public DbSet<Result> Results { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OrgMan.DataContracts.Repository.RepositoryBase;
using OrgMan.DataModel;
namespace OrgMan.DataContracts.Repository
{
public interface IIndividualPersonRepository : IGenericRepository<IndividualPerson>
{
IEnumerable<IndividualPerson> Get(List<Guid> mandatorUids, string fullTextSeachString);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts.HUD
{
public class StatusBars
{
private float currHealth;
private float currEnergy;
private float maxHealth;
private float maxEnergy;
private const int ySize = 10;
private const int maxBarLenght = 150;
private GetStatusComponents _getComponents;
public StatusBars(string name, Canvas canvas)
{
_getComponents = new GetStatusComponents(canvas);
Messenger<float>.AddListener(name + "Health", SetHealth);
Messenger<float>.AddListener(name + "Energy", SetEnergy);
Messenger<float>.AddListener(name + "MaxHealth", SetMaxHealth);
Messenger<float>.AddListener(name + "MaxEnergy", SetMaxEnergy);
}
private void SetHealth(float constant)
{
currHealth = constant;
}
private void SetEnergy(float constant)
{
currEnergy = constant;
}
private void SetMaxHealth(float constant)
{
maxHealth = constant;
}
private void SetMaxEnergy(float constant)
{
maxEnergy = constant;
}
private float CurrentBarLenght(float currSize, float maxSize, float maxLenght)
{
return (int)((currSize / maxSize) * maxLenght);
}
public void SettingSizes()
{
_getComponents.GetHealhBar().rectTransform.sizeDelta = new Vector2(CurrentBarLenght(currHealth, maxHealth, maxBarLenght), ySize);
_getComponents.GetEnergyBar().rectTransform.sizeDelta = new Vector2(CurrentBarLenght(currEnergy, maxEnergy, maxBarLenght), ySize);
}
public void SettingText()
{
_getComponents.GetHealthText().text = (int)currHealth + "/" + (int)maxHealth + " Health";
_getComponents.GetEnergyText().text = (int)currEnergy + "/" + (int)maxEnergy + " Energy";
}
}
}
|
using System.Windows;
namespace CODE.Framework.Wpf.Mvvm
{
/// <summary>This interface defines standard features defined in a theme</summary>
/// <remarks>
/// When a theme implements this interface, it not only must implement the interface, but the resulting
/// class name must be configured in the resources as a string resource called ThemeStandardFeaturesType
/// </remarks>
public interface IThemeStandardFeatures
{
/// <summary>Reference to the standard view factory (if supported)</summary>
IStandardViewFactory StandardViewFactory { get; }
}
/// <summary>This interface can be implemented to create a standard theme factory (and object that can create instances of standard themes</summary>
public interface IStandardViewFactory
{
/// <summary>Returns a standard view based on the view name as a string</summary>
/// <param name="viewName">Standard view name</param>
/// <returns>Standard view or null</returns>
FrameworkElement GetStandardView(string viewName);
/// <summary>Returns a standard view based on the standard view enumeration</summary>
/// <param name="standardView">Standard view identifier</param>
/// <returns>Standard view or null</returns>
FrameworkElement GetStandardView(StandardViews standardView);
}
}
|
using System;
namespace VehicleInventory.Services.DTOs
{
public class VehicleInStockDTO
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public decimal PriceBought { get; set; }
public decimal PriceSold { get; set; }
public DateTime? DateSold { get; set; }
public DateTime DateBought { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using ApartmentApps.Api.BindingModels;
using ApartmentApps.Portal.Controllers;
namespace ApartmentApps.Api.ViewModels
{
public class IncidentReportViewModel : BaseViewModel
{
public string Title { get; set; }
public DateTime RequestDate { get; set; }
public string Comments { get; set; }
public UserBindingModel SubmissionBy { get; set; }
public string StatusId { get; set; }
public string UnitName { get; set; }
public string BuildingName { get; set; }
public IncidentCheckinBindingModel LatestCheckin { get; set; }
public IEnumerable<IncidentCheckinBindingModel> Checkins { get; set; }
}
} |
namespace Sila.Models.Database
{
using System;
/// <summary>
/// Describes a database model for a part.
/// </summary>
public class Part : AssemblyOrPart
{
/// <summary>
/// The color of the part.
/// </summary>
public String? Color { get; set; }
/// <summary>
/// The material of the part.
/// </summary>
public String? Material { get; set; }
/// <summary>
/// Create a new part.
/// </summary>
/// <param name="id">The database identifier.</param>
/// <param name="name">The name of the part or assembly.</param>
public Part(String id, String name) : base(id, name)
{
}
}
} |
using UnityEngine;
[RequireComponent(typeof(VirusPopper))]
public class VirusPopper : MonoBehaviour
{
public bool Able = false;
private Animator animator;
private float TimeAt = 0f;
private float TimeTo = 10f;
void Awake()
{
animator = GetComponent<Animator>();
}
public void Pop(RegionBehaviour region)
{
gameObject.transform.SetParent(region.transform, false);
gameObject.transform.localPosition = Vector3.zero;
gameObject.transform.localScale = Vector3.one;
Able = false;
//animator.Play("PlagueCase");
animator.SetBool("Checked", false);
animator.SetTrigger("Case");
TimeAt = 0f;
//Debug.Log("Popped on x: " + region.Region.X + " y: " + region.Region.Y);
}
private void Update()
{
if (animator.GetCurrentAnimatorStateInfo(0).IsTag("idle"))
{
Able = true;
gameObject.transform.parent = null;
gameObject.transform.localPosition = Vector3.zero;
gameObject.transform.localScale = Vector3.one;
} else
{
Able = false;
}
if (!Able)
{
TimeAt += Time.deltaTime;
if(TimeAt >= TimeTo)
{
TimeAt = 0f;
animator.SetBool("Checked", true);
}
}
}
private void OnMouseEnter()
{
animator.SetBool("Checked", true);
}
}
|
using ADOExam.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ADOExam.Pages
{
public partial class Search : Page
{
public static ComboBox scat;
public Search()
{
InitializeComponent();
SearchCategory.ItemsSource = MainWindow.db.CategoriesSet.Select(s => s.CategoryName).ToList();
scat = SearchCategory;
}
private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(SearchCategory.Text) || !String.IsNullOrEmpty(SearchDate.Text) || !String.IsNullOrEmpty(SearchEMail.Text) || !String.IsNullOrWhiteSpace(SearchPhrase.Text))
{
Categories cats = MainWindow.db.CategoriesSet.FirstOrDefault(fod => fod.CategoryName == SearchCategory.Text);
List<Vacancies> lv = new List<Vacancies>();
if (!String.IsNullOrEmpty(SearchCategory.Text))
lv = MainWindow.db.VacanciesSet.Where(w => w.CategoryID == cats.CategoryID).ToList();
if (!String.IsNullOrEmpty(SearchDate.Text))
lv = MainWindow.db.VacanciesSet.ToList().Where(w => w.VacancyPublishingDate.Date >= SearchDate.SelectedDate.Value).ToList();
if (!String.IsNullOrEmpty(SearchEMail.Text))
lv = MainWindow.db.VacanciesSet.Where(w => w.VacancyAuthorEMail == SearchEMail.Text).ToList();
if (!String.IsNullOrWhiteSpace(SearchPhrase.Text))
lv = MainWindow.db.VacanciesSet.Where(w => w.VacancyDescription.Contains(SearchPhrase.Text)).ToList();
if (lv.Count == 0)
{
MessageBox.Show("There are no info by thees parameters", "Nothing founded", MessageBoxButton.OK);
}
else
DBLV.ItemsSource = lv;
}
else
{
MessageBox.Show("No data inserted, try again", "No data", MessageBoxButton.OK);
}
}
}
}
|
using Newtonsoft.Json;
namespace ConsoleApp.Model
{
public class Currency
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("decimal_places")]
public int DecimalPlaces { get; set; }
[JsonProperty("todolar")]
public double? ToDolar { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MapPoint
{
public class MapPointConstants
{
public const int PORT = 8888;
public const string REQUEST_END = "$";
public const char DELIM = ';';
public const string COMMAND_END = "~";
public const string HOST = "127.0.0.1";
public const int BUFFER_SIZE = 10025;
public const string COMMAND_GetCalculatedRoute = "GetCalculatedRoute";
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace CollaborativeFiltering
{
public class DataReader
{
public IEnumerable<Movie> ReadMovies(string path)
{
var movies = new List<Movie>();
using (var stream = File.OpenText(path))
{
if (stream.EndOfStream)
return movies;
var line = stream.ReadLine();
while (!stream.EndOfStream && !string.IsNullOrEmpty(line))
{
var tab = line.Split(',');
var id = int.Parse(tab[0]);
var year = 0;
if (!int.TryParse(tab[1], out year))
year = 2000;
var title = tab[2];
var movie = new Movie(id, title, year);
movies.Add(movie);
line = stream.ReadLine();
}
}
return movies;
}
public void ReadDataFromFiles(string moviesPath, string ratingsPath, out IEnumerable<Movie> movies, out IEnumerable<User> users, out IEnumerable<Rating> ratings)
{
movies = ReadMovies(moviesPath);
var ratingsBag = new ConcurrentBag<Rating>();
var text = null as string;
var moviesDict = movies.ToDictionary(p => p.Id);
var usersDict = new ConcurrentDictionary<int, User>();
using (var stream = File.OpenText(ratingsPath))
text = stream.ReadToEnd();
var lines = text.Split('\n');
var options = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(lines, options, line =>
{
var tab = line.Split(',');
if (tab.Length != 3)
return;
var movieId = int.Parse(tab[0]);
var userId = int.Parse(tab[1]);
var value = double.Parse(tab[2], CultureInfo.InvariantCulture);
var user = null as User;
if (!usersDict.TryGetValue(userId, out user))
{
user = new User(userId);
usersDict[userId] = user;
}
var movie = moviesDict[movieId];
var rating = Rating.CreateRating(user, movie, value);
ratingsBag.Add(rating);
});
ratings = ratingsBag.ToList();
movies = ratings.GroupBy(p => p.Movie.Id).OrderByDescending(p => p.Count()).Select(p => p.First().Movie).ToList();
users = usersDict.Select(p => p.Value);
}
public void ReadDataFromFiles(string moviesFile, string trainingRatingsFile, string testRatingsFile, double percentToRead, out IEnumerable<Movie> movies, out IEnumerable<User> users, out IEnumerable<Rating> trainingRatings, out IEnumerable<Rating> testRatings)
{
movies = ReadMovies(moviesFile);
var moviesById = movies.ToDictionary(m => m.Id);
var usersById = new ConcurrentDictionary<int, User>();
IEnumerable<Rating> allTrainingRatings;
IEnumerable<Rating> allTestRatings;
ReadRatings(trainingRatingsFile, percentToRead, moviesById, usersById, out allTrainingRatings);
ReadRatings(testRatingsFile, percentToRead, moviesById, usersById, out allTestRatings);
var allUsers = usersById.Select(u => u.Value);
movies = allTestRatings.GroupBy(p => p.Movie.Id).OrderByDescending(p => p.Count()).Select(p => p.First().Movie).ToList();
var usersToReturn = allUsers.OrderByDescending(u => u.Ratings.Count()).Take((int)((double)allUsers.Count() * percentToRead)).ToList();
testRatings = allTestRatings;
trainingRatings = allTrainingRatings;
users = usersToReturn;
}
private void ReadRatings(string ratingsFile, double percentToRead, Dictionary<long,Movie> movies, ConcurrentDictionary<int, User> usersById, out IEnumerable<Rating> ratings)
{
String file;
using (var stream = File.OpenText(ratingsFile))
file = stream.ReadToEnd();
var lines = file.Split('\n');
var linesToRead = (int)((double)lines.Count() * percentToRead);
var readedLines = lines.Take(linesToRead);
var ratingsBag = new ConcurrentBag<Rating>();
Parallel.ForEach(readedLines, line =>
{
var tab = line.Split(',');
if (tab.Length != 3)
return;
var movieId = int.Parse(tab[0]);
var userId = int.Parse(tab[1]);
var value = double.Parse(tab[2], CultureInfo.InvariantCulture);
User user;
if (!usersById.TryGetValue(userId, out user))
{
user = new User(userId);
usersById[userId] = user;
}
var movie = movies[movieId];
var rating = Rating.CreateRating(user, movie, value);
ratingsBag.Add(rating);
});
ratings = ratingsBag.ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BimPlusDemo.Commands;
namespace BimPlusDemo.UserControls
{
/// <summary>
/// Interaction logic for ProgressWindow.xaml
/// </summary>
public partial class ProgressWindow : INotifyPropertyChanging, INotifyPropertyChanged
{
#region Fields
// Property variables
private int _pProgress;
private string _pProgressMessage;
private int _pProgressMax;
//Member variables
private string _mProgressMessageTemplate;
private readonly string _mCancellationMessage;
#endregion
public ProgressWindow(Window parent)
{
InitializeComponent();
DataContext = this;
_mProgressMessageTemplate = "Upload Ifc-File {0}% complete";
_mCancellationMessage = "Ifc Upload cancelled";
Cancel = new CancelCommand(this);
ClearViewModel();
WorkStarted += (sender, args) =>
{
this.Owner = parent;
this.Show();
};
WorkEnded += (sender, args) => { this.Close(); };
}
#region Admin Properties
/// <summary>
/// A cancellation token source for the background operations.
/// </summary>
internal CancellationTokenSource TokenSource { get; set; }
/// <summary>
/// Whether the operation in progress has been cancelled.
/// </summary>
/// <remarks>
/// The Cancel command is invoked by the Cancel button, and on the window
/// close (in case the user clicks the close box to cancel. The Cancel
/// command sets this property and checks it to make sure that the command
/// isn't run twice when the user clicks the Cancel button (once for the
/// button-click, and once for the window-close.
/// </remarks>
public bool IsCancelled { get; set; }
public virtual bool IgnorePropertyChangeEvents { get; set; }
#endregion
#region Command Properties
/// <summary>
/// The Cancel command.
/// </summary>
public ICommand Cancel { get; set; }
#endregion
#region Data Properties
/// <summary>
/// The progress of an image processing job.
/// </summary>
/// <remarks>
/// The setter for this property also sets the ProgressMessage property.
/// </remarks>
public int Progress
{
get => _pProgress;
set
{
RaisePropertyChangingEvent("Progress");
_pProgress = value;
RaisePropertyChangedEvent("Progress");
}
}
/// <summary>
/// The maximum progress value.
/// </summary>
/// <remarks>
/// The
/// </remarks>
public int ProgressMax
{
get => _pProgressMax;
set
{
RaisePropertyChangingEvent("ProgressMax");
_pProgressMax = value;
RaisePropertyChangedEvent("ProgressMax");
}
}
/// <summary>
/// The status message to be displayed in the View.
/// </summary>
public string ProgressMessage
{
get => _pProgressMessage;
set
{
RaisePropertyChangingEvent("ProgressMessage");
_pProgressMessage = value;
RaisePropertyChangedEvent("ProgressMessage");
}
}
#endregion
#region Internal Methods
/// <summary>
/// Clears the view model.
/// </summary>
internal void ClearViewModel()
{
_pProgress = 0;
_pProgressMax = 0;
_pProgressMessage = "Preparing to perform simulated work.";
this.IsCancelled = false;
}
/// <summary>
/// Advances the progress counter for the Progress dialog.
/// </summary>
/// <param name="incrementClicks">The number of 'clicks' to advance the counter.</param>
internal void IncrementProgressCounter(int incrementClicks)
{
if (Progress + incrementClicks > _pProgressMax)
return;
// Increment counter
this.Progress += incrementClicks;
// Update progress message
var progress = Convert.ToSingle(_pProgress);
var progressMax = Convert.ToSingle(_pProgressMax);
var f = (progress / progressMax) * 100;
var percentComplete = Single.IsNaN(f) ? 0 : Convert.ToInt32(f);
ProgressMessage = string.Format(_mProgressMessageTemplate, percentComplete);
}
internal void AssignProgressCounter(int value)
{
_mProgressMessageTemplate = "processing Ifc-Import {0}% complete";
Progress = value;
ProgressMessage = string.Format(_mProgressMessageTemplate, value);
}
internal void AssignMessage(string message)
{
ProgressMessage = message;
}
/// <summary>
/// Sets the progress message to show that processing was cancelled.
/// </summary>
internal void ShowCancellationMessage()
{
ProgressMessage = _mCancellationMessage;
}
#endregion
#region Private Methods
#endregion
#region Public Methods
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">The name of the changed property.</param>
public virtual void RaisePropertyChangedEvent(string propertyName)
{
// Exit if changes ignored
if (IgnorePropertyChangeEvents) return;
// Exit if no subscribers
if (PropertyChanged == null) return;
// Raise event
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
/// <summary>
/// Raises the PropertyChanging event.
/// </summary>
/// <param name="propertyName">The name of the changing property.</param>
public virtual void RaisePropertyChangingEvent(string propertyName)
{
// Exit if changes ignored
if (IgnorePropertyChangeEvents) return;
// Exit if no subscribers
if (PropertyChanging == null) return;
// Raise event
var e = new PropertyChangingEventArgs(propertyName);
PropertyChanging(this, e);
}
/// <summary>
/// Raises the WorkStarting event.
/// </summary>
internal void RaiseWorkStartedEvent()
{
// Raise event
WorkStarted?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Raises the WorkEnding event.
/// </summary>
internal void RaiseWorkEndedEvent()
{
// Raise event
WorkEnded?.Invoke(this, EventArgs.Empty);
}
#endregion
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler WorkStarted;
public event EventHandler WorkEnded;
private void OnWindowClosing(object sender, CancelEventArgs e)
{
Cancel.Execute(null);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC : MonoBehaviour
{
Rigidbody thisRigidbody;
Objective currentObjective;
public void Awake()
{
thisRigidbody = GetComponent<Rigidbody>();
}
public void CompleteObjective(Objective what)
{
if (what == currentObjective)
{
what.PostCompletion();
Debug.LogFormat("NPC ({0}): completed {1}", name, what);
StartCoroutine(YayCoroutine());
currentObjective = null;
}
else
{
Debug.LogWarningFormat("NPC ({0}): can't complete objective {1} because it isn't the current objective {2}", name, what, currentObjective);
}
}
public Objective StartObjective(Objective what)
{
if (currentObjective == null)
{
currentObjective = what;
what.SetOwner(this);
what.Activate();
Debug.LogFormat("NPC ({0}): started {1}", name, what);
}
return currentObjective;
}
IEnumerator YayCoroutine()
{
Quaternion startRotation = thisRigidbody.rotation;
float t = 0;
while (t < 1.0f)
{
t += Time.deltaTime;
Quaternion newRotation = startRotation * Quaternion.AngleAxis(t * 360, transform.up);
thisRigidbody.MoveRotation(newRotation);
yield return 0;
}
}
}
|
using System;
using UnityEngine;
using UnityEditor;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace IzBone.Common {
/**
* EditorGUIに対する便利処理
*/
internal static partial class EditorGUIUtility8
{
// ------------------------------------- public メンバ --------------------------------------------
/**
* 指定の範囲にカーブ(x:0~1,y:0~1)のプレビューを表示する。
* 内部でRepaint時にのみ処理するので、OnGUIで呼べばOK
*/
public static void drawGraphPreview(
Rect rect,
Func<float, float> getValue
) {
if (Event.current.type != EventType.Repaint) return;
checkInitialized();
GUI.BeginClip(rect);
GL.PushMatrix();
GL.Clear(true, false, Color.black);
s_guiMtl.SetPass(0);
// 背景を表示
GL.Begin(GL.TRIANGLES); {
var x0 = 0;
var x1 = rect.width;
var y0 = 0;
var y1 = rect.height;
GL.Color( new Color(0.15f,0.15f,0.15f) );
GL.Vertex3(x0,y0,0); GL.Vertex3(x1,y0,0); GL.Vertex3(x0,y1,0);
GL.Vertex3(x1,y0,0); GL.Vertex3(x1,y1,0); GL.Vertex3(x0,y1,0);
} GL.End();
// グラフを表示
GL.Begin(GL.LINE_STRIP); {
GL.Color( new Color(0,1,0) );
for (int x=0; x<=rect.width-4; ++x) {
var xRate = x / (rect.width-4);
var yRate = 1 - getValue(xRate);
GL.Vertex3(2+x, 3 + (rect.height-6)*yRate, 0);
}
GL.Vertex3(rect.width-2, 3 + (rect.height-6)*(1-getValue(1)), 0);
} GL.End();
// 枠を表示
GL.Begin(GL.LINE_STRIP); {
float2 size = float2( (int)rect.width, (int)rect.height ) - 0.5f;
GL.Color( Color.black );
GL.Vertex3( 0.5f, 0.5f, 0 );
GL.Vertex3( size.x, 0.5f, 0 );
GL.Vertex3( size.x, size.y, 0 );
GL.Vertex3( 0.5f, size.y, 0 );
GL.Vertex3( 0.5f, 0.5f, 0 );
} GL.End();
GL.PopMatrix();
GUI.EndClip();
}
// ------------------------------------- private メンバ --------------------------------------------
static Material s_guiMtl = null;
static void checkInitialized() {
// マテリアルを生成
if (s_guiMtl == null) {
var shader = Shader.Find("Hidden/Internal-Colored");
s_guiMtl = new Material(shader);
}
}
// --------------------------------------------------------------------------------------------------
}
}
|
using System;
namespace consoleproject
{
public class Fight
{
public Fight()
{
}
Random random = new Random();
// Take in a player and an enemey
public Boolean fightEnemy(Player player, Enemy enemy)
{
int num = random.Next(10);
if (num > 5)
{
return true;
}
else
{
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TaskNF
{
[Table("Books")]
public class Book
{
[Key]
public int IdBook { get; set; }
public string Title { get; set; }
public string Language { get; set; }
public virtual ICollection<Autor> Autors {get; set;}
public virtual ICollection<Genre> Genres { get; set; }
public virtual Publisher PublisherName { get; set; }
public int PublisherID { get; set; }
public virtual DateTimeOffset PublisherDate { get; set; }
}
} |
namespace Kremen.Models
{
class OldCouple : Couple
{
private const int NumberOfRooms = 3;
private const decimal RoomElectricity = 15;
private decimal stoveCost;
public OldCouple(decimal pensionOne, decimal pensioTwo, decimal tvCost, decimal fridgeCost, decimal stoveCost)
: base(NumberOfRooms, RoomElectricity, pensionOne + pensioTwo, tvCost, fridgeCost)
{
this.stoveCost = stoveCost;
}
public override decimal Consumation
{
get
{
return this.stoveCost + base.Consumation;
}
}
}
}
|
using System;
class Fibonacci
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int Fibonacci(int a, int b, int count, int number)
{
if (count < number)
{
return Fibonacci(b, a + b, count + 1, number);
}
else
{
Console.WriteLine(a + b);
return 0;
}
}
Fibonacci(0, 1, 1, n);
}
}
|
using System;
using Xunit;
namespace DotNetCross.Memory.Tests
{
public class Unsafe_RefAtByteOffset_Test
{
public class ObjectValue
{
public int Value = 42;
}
[Fact]
public static unsafe void RefAtByteOffset_Object()
{
var obj = new ObjectValue();
ref var valueRef = ref obj.Value;
var valueByteOffset = Unsafe.ByteOffset(obj, ref valueRef);
ref var byteOffsetValueRef = ref Unsafe.RefAtByteOffset<int>(obj, valueByteOffset);
byteOffsetValueRef = 17;
Assert.True(Unsafe.AreSame(ref valueRef, ref byteOffsetValueRef));
Assert.Equal(17, obj.Value);
}
[Fact]
public static unsafe void RefAtByteOffset_Array()
{
var array = new byte[] { 0, 1, 2};
ref var valueRef = ref array[1];
var valueByteOffset = Unsafe.ByteOffset(array, ref valueRef);
ref var byteOffsetValueRef = ref Unsafe.RefAtByteOffset<byte>(array, valueByteOffset);
byteOffsetValueRef = 17;
ref var nextValueRef = ref Unsafe.Add(ref byteOffsetValueRef, 1);
nextValueRef = 42;
Assert.True(Unsafe.AreSame(ref valueRef, ref byteOffsetValueRef));
Assert.Equal(17, array[1]);
Assert.Equal(42, array[2]);
}
}
}
|
using System.Data.Entity;
using SimpleMVC.App.Models;
using SimpleMVC.App.MVC.Interfaces;
namespace SimpleMVC.App.Data
{
public class NotesAppContext : DbContext, IDbIdentityContext
{
public NotesAppContext() : base("NotesAppContext")
{
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Note> Notes { get; set; }
public DbSet<Login> Logins { get; set; }
void IDbIdentityContext.SaveChanges()
{
this.SaveChanges();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Breeze.AssetTypes.DataBoundTypes;
using Microsoft.Xna.Framework;
namespace Breeze.Helpers
{
public static class VectorHelpers
{
public static FloatRectangle AdjustForMargin(this FloatRectangle inputRectangle, Thickness margin) => new FloatRectangle(inputRectangle.X + margin.Left, inputRectangle.Y + margin.Top, inputRectangle.Width - margin.HorizontalMargin, inputRectangle.Height - margin.VerticalMargin);
public static FloatRectangle AdjustForMargin(this FloatRectangle inputRectangle,
DataboundAsset.DataboundValue<Thickness> margin)
{
if (inputRectangle.Height == 0 || !margin.HasValue())
{
return inputRectangle;
}
else
{
return new FloatRectangle(inputRectangle.X + margin.Value.Left, inputRectangle.Y + margin.Value.Top,
inputRectangle.Width - margin.Value.HorizontalMargin,
inputRectangle.Height - margin.Value.VerticalMargin);
}
}
public static FloatRectangle PadForMargin(this FloatRectangle inputRectangle, Thickness margin) => new FloatRectangle(inputRectangle.X + margin.Left, inputRectangle.Y + margin.Top, inputRectangle.Width + margin.HorizontalMargin, inputRectangle.Height + margin.VerticalMargin);
public static Vector2 PadForMargin(this Vector2 inputVector2, Thickness margin) => new Vector2(inputVector2.X + margin.HorizontalMargin, inputVector2.Y + margin.VerticalMargin);
public static Vector2 PadForMargin(this Vector2 inputVector2, DataboundAsset.DataboundValue<Thickness> margin) => inputVector2.Y == 0 || !margin.HasValue() ? inputVector2 : new Vector2(inputVector2.X + margin.Value.HorizontalMargin, inputVector2.Y + margin.Value.VerticalMargin);
public static Vector2 ToVector2(this DataboundAsset.DataboundValue<FloatRectangle> rect)
{
return rect.Value.ToVector2;
}
public static FloatRectangle ConstrainTo(this FloatRectangle input, FloatRectangle constrain)
{
return new FloatRectangle(
constrain.X + (input.X),
constrain.Y + (input.Y),
input.Width,
input.Height
);
return new FloatRectangle(
constrain.X + (constrain.Width * input.X),
constrain.Y + (constrain.Width * input.Y),
constrain.Width * input.Width,
constrain.Height * input.Height
);
}
public static Color ToColor(this uint argb)
{
return new Color(
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff),
(byte)((argb & -16777216) >> 0x18));
}
public static Color ToColor(this string argb)
{
argb = argb.Replace("#", "");
byte a = System.Convert.ToByte("ff", 16);
byte pos = 0;
if (argb.Length == 8)
{
a = System.Convert.ToByte(argb.Substring(pos, 2), 16);
pos = 2;
}
byte r = System.Convert.ToByte(argb.Substring(pos, 2), 16);
pos += 2;
byte g = System.Convert.ToByte(argb.Substring(pos, 2), 16);
pos += 2;
byte b = System.Convert.ToByte(argb.Substring(pos, 2), 16);
return new Color(r, g, b, a);
}
public static Vector2 ToVector(this float angle)
{
return new Vector2((float)Math.Sin(angle), -(float)Math.Cos(angle));
}
public static float ToAngle(this Vector2 vector)
{
return (float)Math.Atan2(vector.X, -vector.Y);
}
public static float DifferenceBetweenAnglesInDegrees(this float angle1, float angle2)
{
float a1 = MathHelper.ToDegrees(angle1);
float a2 = MathHelper.ToDegrees(angle2);
float dif = (float)Math.Abs(a1 - a2) % 360;
if (dif > 180)
dif = 360 - dif;
return dif;
}
public static Vector2 Clip(this Vector2 input, FloatRectangle? clip)
{
Vector2 result = new Vector2(input.X, input.Y);
if (clip == null) return result;
if (result.X < clip.Value.X) result.X = clip.Value.X;
if (result.Y < clip.Value.Y) result.Y = clip.Value.Y;
if (result.X > clip.Value.BottomRight.X) result.X = clip.Value.BottomRight.X;
if (result.Y > clip.Value.BottomRight.Y) result.X = clip.Value.BottomRight.Y;
return result;
}
public static float FontScale
{
get
{
float returnValue = 1920f / Solids.Instance.SpriteBatch.GraphicsDevice.Viewport.Bounds.Width;
float alt = 1080f / Solids.Instance.SpriteBatch.GraphicsDevice.Viewport.Bounds.Height;
if (alt > returnValue) returnValue = alt;
return returnValue;
}
}
public static void DoBorderAction(Action<int, int> action)
{
for (int y = -1; y <= 1; y++)
{
for (int x = -1; x <= 1; x++)
{
action(x, y);
}
}
}
public static Rectangle Add(this Rectangle rect, Vector2 input)
{
return new Rectangle(rect.X + (int)input.X, rect.Y + (int)input.Y, rect.Width, rect.Height);
}
public static Rectangle Clip(this Rectangle rect, FloatRectangle? clip)
{
if (clip == null) return rect;
int x = rect.X;
int y = rect.Y;
int x2 = rect.Right;
int y2 = rect.Bottom;
if (x < clip.Value.X) x = (int)clip.Value.X;
if (y < clip.Value.Y) y = (int)clip.Value.Y;
if (x > clip.Value.X + clip.Value.Width) x = (int)(clip.Value.X + clip.Value.Width);
if (y > clip.Value.Y + clip.Value.Height) y = (int)(clip.Value.Y + clip.Value.Height);
if (x2 < clip.Value.X) x2 = (int)clip.Value.X;
if (y2 < clip.Value.Y) y2 = (int)clip.Value.Y;
if (x2 > clip.Value.X + clip.Value.Width) x2 = (int)(clip.Value.X + clip.Value.Width);
if (y2 > clip.Value.Y + clip.Value.Height) y2 = (int)(clip.Value.Y + clip.Value.Height);
return new Rectangle(x, y, x2 - x, y2 - y);
}
public static FloatRectangle Clip(this FloatRectangle rect, FloatRectangle? clip)
{
if (clip == null) return rect;
float x = rect.X;
float y = rect.Y;
float x2 = rect.Right;
float y2 = rect.Bottom;
if (x < clip.Value.X) x = (int)clip.Value.X;
if (y < clip.Value.Y) y = (int)clip.Value.Y;
if (x > clip.Value.X + clip.Value.Width) x = (int)(clip.Value.X + clip.Value.Width);
if (y > clip.Value.Y + clip.Value.Height) y = (int)(clip.Value.Y + clip.Value.Height);
if (x2 < clip.Value.X) x2 = (int)clip.Value.X;
if (y2 < clip.Value.Y) y2 = (int)clip.Value.Y;
if (x2 > clip.Value.X + clip.Value.Width) x2 = (int)(clip.Value.X + clip.Value.Width);
if (y2 > clip.Value.Y + clip.Value.Height) y2 = (int)(clip.Value.Y + clip.Value.Height);
return new FloatRectangle(x, y, x2 - x, y2 - y);
}
public static FloatRectangle Clamp(this FloatRectangle rect, Rectangle? clamp, bool leftClampOnly = false)
{
if (!clamp.HasValue) return rect;
return Clamp(rect, new FloatRectangle(clamp.Value), leftClampOnly);
}
public static FloatRectangle Clamp(this FloatRectangle? rect, Rectangle? clamp, bool leftClampOnly = false)
{
if (!clamp.HasValue)
{
if (rect.HasValue)
{
return rect.Value;
}
else
{
return new FloatRectangle(Solids.Instance.Bounds);
}
}
return Clamp(rect.Value, new FloatRectangle(clamp.Value), leftClampOnly);
}
public static FloatRectangle Clamp(this FloatRectangle rect, Rectangle clamp, bool leftClampOnly = false)
{
return Clamp(rect, new FloatRectangle(clamp), leftClampOnly);
}
public static FloatRectangle Clamp(this FloatRectangle? rect, Rectangle clamp, bool leftClampOnly = false)
{
if (rect == null)
{
return Clamp(new FloatRectangle(Solids.Instance.Bounds), new FloatRectangle(clamp), leftClampOnly);
}
return Clamp(rect.Value, new FloatRectangle(clamp), leftClampOnly);
}
public static FloatRectangle? Move(this FloatRectangle? fr, Vector2? vector2d)
{
if (fr.HasValue)
{
if (vector2d.HasValue)
{
Vector2 vector2 = vector2d.Value;
return new FloatRectangle(fr.Value.X + vector2.X, fr.Value.Y + vector2.Y, fr.Value.Width, fr.Value.Height);
}
else
{
return fr.Value;
}
}
else
{
return null;
}
}
public static Vector2 Move(this Vector2 input, Vector2? translationVector)
{
if (!translationVector.HasValue) return input;
return input + translationVector.Value;
}
public static FloatRectangle Clamp(this FloatRectangle rect, FloatRectangle? clamp, bool leftClampOnly = false)
{
// using (new BenchMark())
{
if (clamp.HasValue == false) return rect;
float tx = rect.X;
float ty = rect.Y;
float bx = rect.BottomRight.X;
float by = rect.BottomRight.Y;
if (tx < clamp.Value.X) tx = clamp.Value.X;
if (ty < clamp.Value.Y) ty = clamp.Value.Y;
if (!leftClampOnly)
{
if (bx > clamp.Value.BottomRight.X) bx = clamp.Value.BottomRight.X;
if (by > clamp.Value.BottomRight.Y) by = clamp.Value.BottomRight.Y;
}
float width = bx - tx;
float height = by - ty;
if (width < 0 | height < 0)
{
return new FloatRectangle(0, 0, 0, 0);
}
return new FloatRectangle(tx, ty, width, height);
}
}
public static Vector2 Clamp(this Vector2 rect, FloatRectangle clamp, bool leftClampOnly = false)
{
float tx = rect.X;
float ty = rect.Y;
if (tx < clamp.X) tx = clamp.X;
if (ty < clamp.Y) ty = clamp.Y;
if (!leftClampOnly)
{
if (tx > clamp.BottomRight.X) tx = clamp.BottomRight.X;
if (ty > clamp.BottomRight.Y) ty = clamp.BottomRight.Y;
}
return new Vector2(tx, ty);
}
public static bool Intersects(this Rectangle rect, Vector2 pos)
{
return pos.X > rect.X && pos.X < rect.Right && pos.Y > rect.Y && pos.Y < rect.Bottom;
}
public static bool Intersects(this FloatRectangle rect, Vector2 pos)
{
return pos.X > rect.X && pos.X < rect.Right && pos.Y > rect.Y && pos.Y < rect.Bottom;
}
public static bool Intersects(this Vector2 pos, Rectangle rect)
{
return pos.X > rect.X && pos.X < rect.Right && pos.Y > rect.Y && pos.Y < rect.Bottom;
}
public static bool Intersects(this Vector2 pos, FloatRectangle rect)
{
return pos.X > rect.X && pos.X < rect.Right && pos.Y > rect.Y && pos.Y < rect.Bottom;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Domain.ValueObject
{
/// <summary>
/// 单据类型
/// </summary>
public enum BillIdentity
{
[Description("销售订单")]
/// <summary>
/// 销售订单
/// </summary>
SaleOrder = 1,
[Description("销售退单")]
/// <summary>
/// 销售退订单
/// </summary>
SaleRefund = 2,
[Description("采购合同")]
/// <summary>
/// 采购合同
/// </summary>
PurchaseContract = 10 ,
[Description("采购订单")]
/// <summary>
/// 采购订单
/// </summary>
PurchaseOrder = 11,
[Description("采购退单")]
/// <summary>
/// 采购退单订单
/// </summary>
PurchaseBackOrder = 12,
[Description("合同调价单")]
/// <summary>
/// 合同调价单
/// </summary>
AdjustContractPrice = 15,
[Description("商品调价单")]
/// <summary>
/// 商品调价单
/// </summary>
AdjustSalePrice = 16,
[Description("门店调价单")]
/// <summary>
/// 调整门店售价单
/// </summary>
AdjustStorePrice = 17,
// 通用单据 10~49 , 门店单据50~-99
[Description("采购订单")]
/// <summary>
/// 门店采购订单
/// </summary>
StorePurchaseOrder = 51,
[Description("采购退单")]
/// <summary>
/// 门店采购退单订单
/// </summary>
StorePurchaseRefundOrder = 52,
[Description("门店盘点")]
StoreStocktakingPlan = 53,
[Description("盘点单")]
StoreStocktaking = 54,
[Description("盘点修正单")]
StoreStocktakingEdit = 55,
[Description("调拨单")]
TransferOrder = 60,
[Description("其他入库单")]
OtherInOrder = 61,
[Description("其他出库单")]
OtherOutOrder = 62
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TransformMisc
{
public static void ResetPRS(this Transform root)
{
root.localPosition = Vector3.zero;
root.localRotation = Quaternion.identity;
root.localScale = Vector3.one;
}
public static Transform Search(this Transform root, string name)
{
if (root.name == name)
return root;
int count = root.childCount;
for (int i = 0; i < count; i++)
{
Transform child = root.GetChild(i);
Transform found = Search(child, name);
if (found != null)
return found;
}
return null;
}
public static string GetChildPath(this Transform root, Transform node)
{
List<string> nameList = new List<string>();
GetChildPath(nameList, root, node);
nameList.Reverse();
return string.Join("/", nameList.ToArray());
}
private static void GetChildPath(List<string> nameList, Transform root, Transform node)
{
if (node.parent == null || node == root)
return;
nameList.Add(node.name);
GetChildPath(nameList, root, node.parent);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ViewModelLib;
using ViewModelLib.PropertyViewModels;
namespace ViewLib
{
/// <summary>
/// Logique d'interaction pour CollectionView.xaml
/// </summary>
public partial class CollectionView : UserControl
{
public static readonly DependencyProperty ShowRemoveDialogProperty = DependencyProperty.Register("ShowRemoveDialog", typeof(bool), typeof(CollectionView),new PropertyMetadata(true));
public bool ShowRemoveDialog
{
get { return (bool)GetValue(ShowRemoveDialogProperty); }
set { SetValue(ShowRemoveDialogProperty, value); }
}
public static readonly DependencyProperty ViewModelCollectionProperty = DependencyProperty.Register("ViewModelCollection", typeof(IViewModelCollection), typeof(CollectionView));
public IViewModelCollection ViewModelCollection
{
get { return (IViewModelCollection)GetValue(ViewModelCollectionProperty); }
set { SetValue(ViewModelCollectionProperty, value); }
}
public CollectionView()
{
InitializeComponent();
}
private bool OnEditViewModel(IPropertyViewModelCollection Properties)
{
EditWindow editWindow;
editWindow = new EditWindow() { Owner = Application.Current.MainWindow, PropertyViewModelCollection = Properties };
return editWindow.ShowDialog() ?? false;
}
private bool OnRemoveViewModel(IPropertyViewModelCollection Properties)
{
if (!ShowRemoveDialog) return true;
return MessageBox.Show(Application.Current.MainWindow, "Do you want to delete this item(s)", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question)==MessageBoxResult.Yes;
}
private void AddCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.Handled = true; e.CanExecute = ViewModelCollection?.CanAdd() ?? false;
}
private async void AddCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
try
{
await ViewModelCollection.AddAsync(OnEditViewModel);
}
catch
{
ViewModelCollection.ErrorMessage = "Failed to add item";
}
}
private void RemoveCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.Handled = true; e.CanExecute = ViewModelCollection?.CanRemove() ?? false;
}
private async void RemoveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
try
{
await ViewModelCollection.RemoveAsync(OnRemoveViewModel);
}
catch
{
ViewModelCollection.ErrorMessage = "Failed to remove item";
}
}
private void EditCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.Handled = true; e.CanExecute = ViewModelCollection?.CanEdit() ?? false;
}
private async void EditCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
try
{
await ViewModelCollection.EditAsync(OnEditViewModel);
}
catch
{
ViewModelCollection.ErrorMessage = "Failed to edit item";
}
}
private async void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
if (ViewModelCollection?.CanEdit() ?? false) await ViewModelCollection.EditAsync(OnEditViewModel);
}
catch
{
ViewModelCollection.ErrorMessage = "Failed to edit item";
}
}
}
}
|
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebPageTest.Controllers
{
public class HomeController : Controller
{
private readonly HttpClient _client = new HttpClient();
public ActionResult Index()
{
return View();
}
private async Task<object> GetDataFromWebPageTest(string url)
{
using (var httpClient = new HttpClient())
{
var result = await httpClient.GetAsync(url).ConfigureAwait(false);
var responseBody = await result.Content.ReadAsStringAsync();
return responseBody;
}
}
[HttpGet]
public object GetData(string url)
{
return GetDataFromWebPageTest(url).GetAwaiter().GetResult();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} |
using System.Reflection;
using CYJ.Utils.Extension.ReflectionExtension;
// ReSharper disable once CheckNamespace
namespace Aquarium.Util.Extension.ReflectionExtension
{
public static class PropertyExtension
{
/// <summary>An object extension method that gets the properties.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>An array of property information.</returns>
public static PropertyInfo[] GetProperties(this object @this)
{
return @this.GetType().GetProperties();
}
/// <summary>An object extension method that gets the properties.</summary>
/// <param name="this">The @this to act on.</param>
/// <param name="bindingAttr">The binding attribute.</param>
/// <returns>An array of property information.</returns>
public static PropertyInfo[] GetProperties(this object @this, BindingFlags bindingAttr)
{
return @this.GetType().GetProperties(bindingAttr);
}
/// <summary>
/// A T extension method that gets a property.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="name">The name.</param>
/// <returns>The property.</returns>
public static PropertyInfo GetProperty<T>(this T @this, string name)
{
return @this.GetType().GetProperty(name);
}
/// <summary>
/// A T extension method that gets a property.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="name">The name.</param>
/// <param name="bindingAttr">The binding attribute.</param>
/// <returns>The property.</returns>
public static PropertyInfo GetProperty<T>(this T @this, string name, BindingFlags bindingAttr)
{
return @this.GetType().GetProperty(name, bindingAttr);
}
/// <summary>A T extension method that gets property or field.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="name">The name.</param>
/// <returns>The property or field.</returns>
public static MemberInfo GetPropertyOrField<T>(this T @this, string name)
{
var property = @this.GetProperty(name);
if (property != null) return property;
var field = @this.GetField(name);
if (field != null) return field;
return null;
}
/// <summary>
/// A T extension method that sets property value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="propertyName">Name of the property.</param>
/// <param name="value">The value.</param>
public static void SetPropertyValue<T>(this T @this, string propertyName, object value)
{
var type = @this.GetType();
var property = type.GetProperty(propertyName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
property.SetValue(@this, value, null);
}
/// <summary>
/// A T extension method that gets property value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="propertyName">Name of the property.</param>
/// <returns>The property value.</returns>
public static object GetPropertyValue<T>(this T @this, string propertyName)
{
var type = @this.GetType();
var property = type.GetProperty(propertyName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
return property.GetValue(@this, null);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Web.Models.MRP
{
public class FlowClassify
{
[Display(Name = "FlowClassify_Flow", ResourceType = typeof(Resources.MRP.FlowClassify))]
public string Flow { get; set; }
[Display(Name = "FlowClassify_Classify01", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify01 { get; set; }
[Display(Name = "FlowClassify_Classify02", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify02 { get; set; }
[Display(Name = "FlowClassify_Classify03", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify03 { get; set; }
[Display(Name = "FlowClassify_Classify04", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify04 { get; set; }
[Display(Name = "FlowClassify_Classify05", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify05 { get; set; }
[Display(Name = "FlowClassify_Classify06", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify06 { get; set; }
[Display(Name = "FlowClassify_Classify07", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify07 { get; set; }
[Display(Name = "FlowClassify_Classify08", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify08 { get; set; }
[Display(Name = "FlowClassify_Classify09", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify09 { get; set; }
[Display(Name = "FlowClassify_Classify10", ResourceType = typeof(Resources.MRP.FlowClassify))]
public bool Classify10 { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Query.SyncObject
{
public class ChangeDataSync
{
public int Id { get; set; }
public string DomainName { get; set; }
public int DataId { get; set; }
public DateTime CreatedOn { get; set; }
}
}
|
using AbiokaScrum.Api.Entities;
namespace AbiokaScrum.Api.Data
{
public interface ILabelOperation : IOperation<Label>
{
}
} |
namespace CurriculumManagement.Migrations
{
using CurriculumManagement.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<CurriculumManagement.Models.EAFormDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CurriculumManagement.Models.EAFormDBContext context)
{
context.EAFormStatuses.AddOrUpdate(i => i.Name,
new EAFormStatus
{
Name = "Imported",
Description = "Copies created from the one45 extract. Ready for distribution."
},
new EAFormStatus
{
Name = "Distributed",
Description = "EA Forms that are sent to teaching staff for review and changes."
},
new EAFormStatus
{
Name = "Draft",
Description = "EA Forms saved as draft by teaching staff who are not yet ready to submit."
},
new EAFormStatus
{
Name = "Submitted",
Description = "EA Forms submitted by teaching staff after completing review and changes."
},
new EAFormStatus
{
Name = "PA Checked",
Description = "EA Forms checked by a Program Assistant."
},
new EAFormStatus
{
Name = "Completed",
Description = "CMU has gathered changes from instructor(s) and is done using the form."
},
new EAFormStatus
{
Name = "one45 Extract",
Description = "EA Forms that match the one45 extract imported."
}
);
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
//Create 3 roles
//
//Admin
string roleName = "Admin";
if (!RoleManager.RoleExists(roleName))
{
var roleresult = RoleManager.Create(new IdentityRole(roleName));
}
//PA
roleName = "Program Assistant";
if (!RoleManager.RoleExists(roleName))
{
var roleresult = RoleManager.Create(new IdentityRole(roleName));
}
//CMC
roleName = "Curriculum Materials Coordinator";
if (!RoleManager.RoleExists(roleName))
{
var roleresult = RoleManager.Create(new IdentityRole(roleName));
}
//Create test users
var user = new ApplicationUser();
user.UserName = "chengken";
var result = UserManager.Create(user);
if (result.Succeeded)
{
result = UserManager.AddToRole(user.Id, "Admin");
}
user = new ApplicationUser();
user.UserName = "pdkeats";
result = UserManager.Create(user);
if (result.Succeeded)
{
result = UserManager.AddToRole(user.Id, "Admin");
}
user = new ApplicationUser();
user.UserName = "staff01";
result = UserManager.Create(user);
if (result.Succeeded)
{
result = UserManager.AddToRole(user.Id, "Program Assistant");
}
user = new ApplicationUser();
user.UserName = "cmc01";
result = UserManager.Create(user);
if (result.Succeeded)
{
result = UserManager.AddToRole(user.Id, "Curriculum Materials Coordinator");
}
//base.Seed(context);
context.SaveChanges();
//context.EAForms.AddOrUpdate(i => i.Course,
// new EAForm
// {
// Course = "Gastrointestinal – FMED 424",
// BlockWeekTitle = "Esophagus and Stomach",
// ActivityTitle = "Neuromuscular Control of Gut Motility",
// ActivityType = "Test Activity Type",
// LastUpdated = DateTime.Now,
// Status = context.EAFormStatuses.Single(i => i.Name == "Imported")
// },
// new EAForm
// {
// Course = "Cerebral Lobes – BMED 301",
// BlockWeekTitle = "Brain",
// ActivityTitle = "Neurological Control of Brain Functions",
// ActivityType = "Test Activity Type",
// LastUpdated = DateTime.Now,
// Status = context.EAFormStatuses.Single(i => i.Name == "Imported")
// }
//);
}
}
}
|
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
namespace Sentry.Extensions.Logging;
internal class SentryLoggingOptionsSetup : ConfigureFromConfigurationOptions<SentryLoggingOptions>
{
public SentryLoggingOptionsSetup(
ILoggerProviderConfiguration<SentryLoggerProvider> providerConfiguration)
: base(providerConfiguration.Configuration)
{ }
}
|
using System.IO;
namespace TechEval.Commands
{
public class FileUploadCommandBase
{
public Stream UploadedFile { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OnboardingSIGDB1.Domain.Empresas.Dtos
{
public class EmpresaFiltroDto
{
public string Cnpj { get; set; }
public string Nome { get; set; }
public DateTime? DataFundacaoInicio { get; set; }
public DateTime? DataFundacaoFim { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NotepadDemo
{
public interface INotepad
{
void WriteOnPage(int pageNumber, string text);
void OverwritePageText(int pageNumber, string text);
void DeletePageText(int pageNumber);
void PrintAllPages();
}
}
|
using AbstractFactory.factory;
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractFactory.ListFactory
{
public class ListLink : Link
{
public ListLink(string caption, string url) : base(caption, url)
{
}
public override string MakeHTML()
{
return $" <li><a href={_url}>{_caption}</a></li>" + "\n";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TableroComando.Clases
{
public abstract class FormMode
{
public FormMode(){}
public abstract void AfterSave<FormClass>(Form form) where FormClass : Form;
public string GuardarBtnText { get; protected set; }
}
public class UpdateMode : FormMode
{
public UpdateMode()
{
GuardarBtnText = "Actualizar";
}
public override void AfterSave<FormClass>(Form form)
{
}
}
public class CreateMode : FormMode
{
public CreateMode()
{
GuardarBtnText = "Guardar";
}
public override void AfterSave<FormClass>(Form form)
{
DialogResult result = MessageBox.Show("Los datos fueron guardados. ¿Desea agregar otro objetivo?", "", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
form.Close();
CreateMode c = new CreateMode();
((Form)Activator.CreateInstance(typeof(FormClass), c)).Show();
}
else form.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Labyrinth
{
public enum Direction{ LEFT, RIGHT, UP, DOWN};
public class Bullet
{
public Vector2 bulletPosA;
private Vector2 startPos;
public Point bulletPosR;
public Point movePosR;
private float bound;
private Direction direction;
private Rectangle hitBox;
public Bullet(Point bulletPosR, Vector2 bulletPosA, Direction direction)
{
this.bulletPosA = bulletPosA;
this.startPos = bulletPosA;
this.bulletPosR = bulletPosR;
this.movePosR = bulletPosR;
this.direction = direction;
this.bound = this.FindBound();
this.hitBox = new Rectangle(bulletPosR.X, bulletPosR.Y, 20, 20);
}
public Rectangle HitBox
{
get { return this.hitBox; }
}
public float Bound
{
get { return this.bound; }
}
public Vector2 StartPos
{
get { return this.startPos; }
}
public Direction Direction
{
get { return this.direction; }
}
public float X
{
get { return bulletPosA.X; }
set {
bulletPosA.X = value; }
}
public float Y
{
get { return bulletPosA.Y; }
set { bulletPosA.Y = value; }
}
//Private method that calculates the distance between the cannon and the opposite wall
private float FindBound()
{
int i;
Point tempP = bulletPosR;
switch (this.direction)
{
case Direction.RIGHT:
for (i = 0; i < C.colsNb; i++)
{
if (C.lbrnt[tempP.X, tempP.Y] != '1')
{
tempP.Y--;
}
else
{
return ((float)i * C.multFactor);
}
}
break;
case Direction.UP:
for (i = 0; i < C.rowsNb; i++)
{
if (C.lbrnt[tempP.X, tempP.Y] != '1')
{
tempP.X++;
}
else
{
return ((float)i * C.multFactor);
}
}
break;
case Direction.DOWN:
for (i = 0; i < C.rowsNb; i++)
{
if (C.lbrnt[tempP.X, tempP.Y] != '1')
{
tempP.X++;
}
else
{
return (((float)i * C.multFactor) + 50 );
}
}
break;
default:
for (i = 0; i < C.colsNb; i++)
{
if (C.lbrnt[tempP.X, tempP.Y] != '1')
{
tempP.Y++;
}
else
{
return ((float)i * C.multFactor);
}
}
break;
}
return -1;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.