text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISP._2_after
{
public class T_Shirt: IProduct
{
public decimal Price
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public int Stock
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket client;
private void button1_Click(object sender, EventArgs e)
{
if (client ==null)
{//新建客户端socket
client = new Socket(AddressFamily.InterNetwork ,SocketType.Stream ,ProtocolType.Tcp );
try
{
client.Connect(IPAddress.Parse(txtip.Text.Trim()), int.Parse(txtport.Text.Trim()));
label3.Text = "连接成功";
label3.ForeColor = Color.Green;
//开启新线程接受服务器发来的消息
ThreadPool.QueueUserWorkItem(new WaitCallback((cliobj) =>
{
Socket clientcom = cliobj as Socket;
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 1];
//接收消息
int r = clientcom.Receive(buffer);
string m = Encoding.UTF8.GetString(buffer, 0, r);
//跨线程修改textbox的值
textBox3.Invoke(new Action<string>(x =>
{
textBox3.AppendText("服务器发来信息" + x + Environment.NewLine);
}), m);
}
}), client);
}
catch (Exception)
{
MessageBox.Show("发生错误,请关闭重试");
}
//连接服务器
}
}
private void button2_Click(object sender, EventArgs e)
{
if (client !=null)
{
try
{
byte[] buffer = Encoding.UTF8.GetBytes(textBox1.Text.Trim());
//发送消息到服务器
client.Send(buffer);
textBox1.Clear();
}
catch (Exception)
{
MessageBox.Show("发生错误,请关闭重试");
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpCommand : Command {
//점프시 점프의 파워를 담당하는 변수
float JUMP = 15f;
Vector3 jumpVector = Vector3.up;
public void Execute(GameObject actor)
{
if (actor.transform.position.y < 1.5f)
actor.GetComponent<Rigidbody>().AddForce(jumpVector*JUMP);
}
}
|
using System;
namespace CoinBot.Core
{
public sealed class MarketSummaryDto
{
public Currency BaseCurrrency { get; set; }
public Currency MarketCurrency { get; set; }
public string Market { get; set; }
public decimal? Volume { get; set; }
public decimal? Last { get; set; }
public DateTime? LastUpdated { get; set; }
}
}
|
using MKService.Messages;
using MKService.ModelUpdaters;
using MKService.Queries;
using MKService.Updates;
namespace MKService.MessageHandlers
{
internal class ClickAddedHandler : ServerMessageHandlerBase<ClickAdd, ClickQuery, IUpdatableClick>
{
public ClickAddedHandler(IModelUpdaterResolver modelUpdaterResolver) : base(modelUpdaterResolver)
{
}
protected override IUpdatableClick LocateQueryComponent(ClickAdd message, ClickQuery query)
{
return query;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using RestSharp;
using Riverside.Cms.Utilities.Net.RestSharpExtensions;
namespace Riverside.Cms.Services.Core.Client
{
public class MasterPageService : IMasterPageService
{
private readonly IOptions<CoreApiOptions> _options;
public MasterPageService(IOptions<CoreApiOptions> options)
{
_options = options;
}
private void CheckResponseStatus<T>(IRestResponse<T> response) where T : new()
{
if (response.ErrorException != null)
throw new CoreClientException($"Core API failed with response status {response.ResponseStatus}", response.ErrorException);
}
public async Task<MasterPage> ReadMasterPageAsync(long tenantId, long masterPageId)
{
try
{
RestClient client = new RestClient(_options.Value.ApiBaseUrl);
RestRequest request = new RestRequest(_options.Value.ApiMasterPageUrl, Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("masterPageId", masterPageId);
IRestResponse<MasterPage> response = await client.ExecuteAsync<MasterPage>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (CoreClientException)
{
throw;
}
catch (Exception ex)
{
throw new CoreClientException("Core API failed", ex);
}
}
public async Task<List<MasterPageZone>> SearchMasterPageZonesAsync(long tenantId, long masterPageId)
{
try
{
RestClient client = new RestClient(_options.Value.ApiBaseUrl);
RestRequest request = new RestRequest(_options.Value.ApiMasterPageZonesUrl, Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("masterPageId", masterPageId);
IRestResponse<List<MasterPageZone>> response = await client.ExecuteAsync<List<MasterPageZone>>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (CoreClientException)
{
throw;
}
catch (Exception ex)
{
throw new CoreClientException("Core API failed", ex);
}
}
public async Task<MasterPageZone> ReadMasterPageZoneAsync(long tenantId, long masterPageId, long masterPageZoneId)
{
try
{
RestClient client = new RestClient(_options.Value.ApiBaseUrl);
RestRequest request = new RestRequest(_options.Value.ApiMasterPageZoneUrl, Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("masterPageId", masterPageId);
request.AddUrlSegment("masterPageZoneId", masterPageZoneId);
IRestResponse<MasterPageZone> response = await client.ExecuteAsync<MasterPageZone>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (CoreClientException)
{
throw;
}
catch (Exception ex)
{
throw new CoreClientException("Core API failed", ex);
}
}
public async Task<List<MasterPageZoneElement>> SearchMasterPageZoneElementsAsync(long tenantId, long masterPageId, long masterPageZoneId)
{
try
{
RestClient client = new RestClient(_options.Value.ApiBaseUrl);
RestRequest request = new RestRequest(_options.Value.ApiMasterPageZoneElementsUrl, Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("masterPageId", masterPageId);
request.AddUrlSegment("masterPageZoneId", masterPageZoneId);
IRestResponse<List<MasterPageZoneElement>> response = await client.ExecuteAsync<List<MasterPageZoneElement>>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (CoreClientException)
{
throw;
}
catch (Exception ex)
{
throw new CoreClientException("Core API failed", ex);
}
}
public async Task<MasterPageZoneElement> ReadMasterPageZoneElementAsync(long tenantId, long masterPageId, long masterPageZoneId, long masterPageZoneElementId)
{
try
{
RestClient client = new RestClient(_options.Value.ApiBaseUrl);
RestRequest request = new RestRequest(_options.Value.ApiMasterPageZoneElementUrl, Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("masterPageId", masterPageId);
request.AddUrlSegment("masterPageZoneId", masterPageZoneId);
request.AddUrlSegment("masterPageZoneElementId", masterPageZoneElementId);
IRestResponse<MasterPageZoneElement> response = await client.ExecuteAsync<MasterPageZoneElement>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (CoreClientException)
{
throw;
}
catch (Exception ex)
{
throw new CoreClientException("Core API failed", ex);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sfShareLib;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using CDSShareLib.Helper;
namespace sfAPIService.Models
{
public class IoTHubModel
{
public class Format_Detail
{
public int Id { get; set; }
public string IoTHubName { get; set; }
public string Description { get; set; }
public string CompanyName { get; set; }
public string IoTHubEndPoint { get; set; }
public string IoTHubConnectionString { get; set; }
public string EventConsumerGroup { get; set; }
public string EventHubStorageConnectionString { get; set; }
public string UploadContainer { get; set; }
public bool EnableMultipleReceiver { get; set; }
}
public class Format_Create
{
[Required]
public string IoTHubName { get; set; }
public string Description { get; set; }
public string IoTHubEndPoint { get; set; }
[Required]
public string IoTHubConnectionString { get; set; }
public string EventConsumerGroup { get; set; }
public string EventHubStorageConnectionString { get; set; }
public string UploadContainer { get; set; }
[Required]
public bool EnableMultipleReceiver { get; set; }
}
public class Format_Update
{
public string IoTHubName { get; set; }
public string Description { get; set; }
public string IoTHubEndPoint { get; set; }
/// <summary>
/// 是否要禁止修改?
/// </summary>
public string IoTHubConnectionString { get; set; }
public string EventConsumerGroup { get; set; }
public string EventHubStorageConnectionString { get; set; }
public string UploadContainer { get; set; }
public bool? EnableMultipleReceiver { get; set; }
}
public List<Format_Detail> GetAllByCompanyId(int companyId)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
var L2Enty = from c in dbEntity.IoTHub.AsNoTracking()
where c.CompanyID == companyId
select c;
return L2Enty.Select(s => new Format_Detail
{
Id = s.Id,
IoTHubName = s.IoTHubName,
Description = s.Description,
CompanyName = s.Company == null ? "" : s.Company.Name,
IoTHubEndPoint = s.IoTHubEndPoint,
IoTHubConnectionString = s.IoTHubConnectionString,
EventConsumerGroup = s.EventConsumerGroup,
EventHubStorageConnectionString = s.EventHubStorageConnectionString,
UploadContainer = s.UploadContainer,
EnableMultipleReceiver = s.EnableMultipleReceiver
}).ToList<Format_Detail>();
}
}
public Format_Detail GetById(int id)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
IoTHub existingData = (from c in dbEntity.IoTHub.AsNoTracking()
where c.Id == id
select c).SingleOrDefault<IoTHub>();
if (existingData == null)
throw new CDSException(10901);
return new Format_Detail()
{
Id = existingData.Id,
IoTHubName = existingData.IoTHubName,
Description = existingData.Description,
CompanyName = existingData.Company == null ? "" : existingData.Company.Name,
IoTHubEndPoint = existingData.IoTHubEndPoint,
IoTHubConnectionString = existingData.IoTHubConnectionString,
EventConsumerGroup = existingData.EventConsumerGroup,
EventHubStorageConnectionString = existingData.EventHubStorageConnectionString,
UploadContainer = existingData.UploadContainer,
EnableMultipleReceiver = existingData.EnableMultipleReceiver
};
}
}
public int Create(int companyId, Format_Create parseData)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
IoTHub newData = new IoTHub()
{
IoTHubName = parseData.IoTHubName,
Description = parseData.Description ?? "",
CompanyID = companyId,
IoTHubEndPoint = parseData.IoTHubEndPoint ?? "",
IoTHubConnectionString = parseData.IoTHubConnectionString ?? "",
EventConsumerGroup = parseData.EventConsumerGroup ?? "",
EventHubStorageConnectionString = parseData.EventHubStorageConnectionString ?? "",
UploadContainer = parseData.UploadContainer ?? "",
EnableMultipleReceiver = parseData.EnableMultipleReceiver
};
dbEntity.IoTHub.Add(newData);
try
{
dbEntity.SaveChanges();
}
catch (DbUpdateException ex)
{
if (ex.InnerException.InnerException.Message.Contains("Cannot insert duplicate key"))
throw new CDSException(10905);
else
throw ex;
}
return newData.Id;
}
}
public void Update(int id, Format_Update parseData)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
IoTHub existingData = dbEntity.IoTHub.Find(id);
if (existingData == null)
throw new CDSException(10901);
if (parseData.IoTHubName != null)
existingData.IoTHubName = parseData.IoTHubName;
if (parseData.Description != null)
existingData.Description = parseData.Description;
if (parseData.IoTHubEndPoint != null)
existingData.IoTHubEndPoint = parseData.IoTHubEndPoint;
if (parseData.IoTHubConnectionString != null)
existingData.IoTHubConnectionString = parseData.IoTHubConnectionString;
if (parseData.EventConsumerGroup != null)
existingData.EventConsumerGroup = parseData.EventConsumerGroup;
if (parseData.EventHubStorageConnectionString != null)
existingData.EventHubStorageConnectionString = parseData.EventHubStorageConnectionString;
if (parseData.UploadContainer != null)
existingData.UploadContainer = parseData.UploadContainer;
if (parseData.EnableMultipleReceiver.HasValue)
existingData.EnableMultipleReceiver = (bool)parseData.EnableMultipleReceiver;
try
{
dbEntity.SaveChanges();
}
catch (DbUpdateException ex)
{
if (ex.InnerException.InnerException.Message.Contains("Cannot insert duplicate key"))
throw new CDSException(10905);
else
throw ex;
}
}
}
public void DeleteById(int id)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
IoTHub existingData = dbEntity.IoTHub.Find(id);
if (existingData == null)
throw new CDSException(10901);
dbEntity.Entry(existingData).State = EntityState.Deleted;
dbEntity.SaveChanges();
}
}
}
} |
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Text;
using TableTopCrucible.Core.Helper;
using TableTopCrucible.Core.Models.Sources;
using TableTopCrucible.Core.Progress.Enums;
namespace TableTopCrucible.Core.Progress.Models
{
public class TaskProgression : ReactiveObject, ITaskProgressionInfo
{
[Reactive]
public TaskState State { get; set; } = TaskState.Todo;
[Reactive]
public string Details { get; set; } = string.Empty;
[Reactive]
public string Title { get; set; } = string.Empty;
[Reactive]
public int CurrentProgress { get; set; } = 0;
[Reactive]
public int RequiredProgress { get; set; } = 1;
[Reactive]
public Exception Error { get; set; }
public IObservable<TaskState> TaskStateChanges { get; }
public IObservable<string> DetailsChanges { get; }
public IObservable<string> TitleChanges { get; }
public IObservable<int> CurrentProgressChanges { get; }
public IObservable<int> RequiredProgressChanges { get; }
public IObservable<TaskProgressionState> TaskProgressionStateChanges { get; }
public IObservable<TaskState> DoneChanges { get; }
public IObservable<Exception> ErrorChanges { get; }
public TaskProgression()
{
this.TaskStateChanges = this.WhenAnyValue(m => m.State);
this.DetailsChanges = this.WhenAnyValue(m => m.Details);
this.TitleChanges = this.WhenAnyValue(m => m.Title);
this.CurrentProgressChanges = this.WhenAnyValue(m => m.CurrentProgress);
this.RequiredProgressChanges = this.WhenAnyValue(m => m.RequiredProgress);
this.ErrorChanges = this.WhenAnyValue(m => m.Error);
this.TaskProgressionStateChanges = this.WhenAnyValue(
m => m.State,
m => m.Details,
m => m.CurrentProgress,
m => m.RequiredProgress)
.Select((items)=>new TaskProgressionState(items.Item1,items.Item2,items.Item3,items.Item4));
this.DoneChanges = TaskStateChanges.Where(state => state.IsIn(TaskState.Done, TaskState.Failed));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Testownik.Model
{
public class TestownikContext : DbContext
{
public TestownikContext()
{
// Turn off the Migrations, (NOT a code first Db)
Database.SetInitializer<TestownikContext>(null);
}
public DbSet<Test> Tests { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
public DbSet<ArchQuestion> ArchQuestions { get; set; }
public DbSet<ArchStat> ArchStats { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Database does not pluralize table names
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
|
using System.Collections.Generic;
namespace AnimalShelter.Models
{
public class Animal
{
public Animal()
{
this.JoinEntities = new HashSet<AnimalTrick>();
}
public int AnimalId { get; set; }
public string Description { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public virtual ICollection<AnimalTrick> JoinEntities { get; }
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
public class DUTaskCenter<T> where T : DUTask
{
private static int _ID;
private float _currentTime;
protected int _maxConcurrentNum = 5;
protected List<T> _waitingList = new List<T>();
protected List<T> _processingList = new List<T>();
protected List<T> _completeTasks = new List<T>();
protected List<T> _errorTasks = new List<T>();
protected List<T> _tmpRunningTasks = new List<T>();
public int maxConcurrentNum
{
get
{
return this._maxConcurrentNum;
}
set
{
this._maxConcurrentNum = value;
}
}
public bool ProcessListNotFull
{
get
{
return this._processingList.get_Count() < this._maxConcurrentNum || this._maxConcurrentNum == 0;
}
}
protected virtual T _FindInByID(List<T> list, int task_id)
{
for (int i = 0; i < list.get_Count(); i++)
{
T t = list.get_Item(i);
if (t.id == task_id)
{
return list.get_Item(i);
}
}
return (T)((object)null);
}
protected virtual T _FindInByLocalPath(List<T> list, string localpath)
{
for (int i = 0; i < list.get_Count(); i++)
{
T t = list.get_Item(i);
if (t.localPath == localpath)
{
return list.get_Item(i);
}
}
return (T)((object)null);
}
public virtual T FindTaskByID(int task_id)
{
T t = this._FindInByID(this._processingList, task_id);
if (t == null)
{
t = this._FindInByID(this._waitingList, task_id);
}
return t;
}
public virtual T FindTaskByLocalpath(string localpath)
{
T t = this._FindInByLocalPath(this._processingList, localpath);
if (t == null)
{
t = this._FindInByLocalPath(this._waitingList, localpath);
}
return t;
}
public virtual bool PauseTaskByID(int task_id)
{
T t = this.FindTaskByID(task_id);
if (t != null)
{
if (t.state == DUTaskState.Running)
{
T task = (T)((object)t.CloneSelf());
t.Pause();
task.Pause();
this._processingList.Remove(t);
this._waitingList.Remove(t);
this._AddToWait(task);
}
return true;
}
return false;
}
public virtual bool CancelTaskByID(int task_id)
{
T t = this.FindTaskByID(task_id);
return t != null && this.CancelTask(t);
}
public virtual bool CancelTask(T task)
{
if (this._processingList.Remove(task))
{
task.Cancel();
task.Close();
return true;
}
if (this._waitingList.Remove(task))
{
task.Cancel();
task.Close();
return true;
}
return false;
}
protected virtual T _CreateTask(int id, string url, string localPath)
{
return (T)((object)null);
}
public virtual T CreateTask(string url, string localpath, bool continueLoad)
{
T t = this.FindTaskByLocalpath(localpath);
if (t == null)
{
t = this._CreateTask(++DUTaskCenter<T>._ID, url, localpath);
this._AddToWait(t);
}
else if (t.state == DUTaskState.Pause)
{
this._UnPause(t);
}
return t;
}
public virtual T StartTaskByID(int task_id)
{
T t = this.FindTaskByID(task_id);
if (t != null)
{
this._UnPause(t);
}
return t;
}
protected virtual void _UnPause(T task)
{
task.UnPause();
}
protected virtual void _DoStartTask(T task)
{
if (!this._processingList.Contains(task))
{
this._processingList.Add(task);
this._RemoveWaiting(task);
task.Begin();
}
}
protected void _AddToWait(T task)
{
if (!this._waitingList.Contains(task))
{
this._waitingList.Add(task);
}
}
protected void _RemoveWaiting(T task)
{
this._waitingList.Remove(task);
}
public virtual void CloseAll()
{
DUTaskCenter<T>._ID = 0;
for (int i = this._waitingList.get_Count() - 1; i >= 0; i--)
{
this.CancelTask(this._waitingList.get_Item(i));
}
for (int j = this._processingList.get_Count() - 1; j >= 0; j--)
{
this.CancelTask(this._processingList.get_Item(j));
}
this._waitingList.Clear();
this._processingList.Clear();
}
public virtual void Update()
{
float param = Time.get_realtimeSinceStartup() - this._currentTime;
this._currentTime = Time.get_realtimeSinceStartup();
if (this._processingList.get_Count() > 0)
{
for (int i = this._processingList.get_Count() - 1; i >= 0; i--)
{
T t = this._processingList.get_Item(i);
switch (t.state)
{
case DUTaskState.Running:
this._tmpRunningTasks.Add(t);
break;
case DUTaskState.Complete:
this._completeTasks.Add(t);
this._processingList.Remove(t);
break;
case DUTaskState.Error:
this._errorTasks.Add(t);
this._processingList.Remove(t);
break;
}
}
}
this.HandleDirtyTaskListAndClear(this._completeTasks, new Action<T>(this._SuccessCompleteTask));
this.HandleDirtyTaskListAndClear(this._errorTasks, new Action<T>(this._ErrorCompleteTask));
this.HandleDirtyTaskListAndClear<float>(this._tmpRunningTasks, new Action<T, float>(this._RunningTask), param);
if (this._waitingList.get_Count() > 0 && this.ProcessListNotFull)
{
for (int j = 0; j < this._waitingList.get_Count(); j++)
{
T task = this._waitingList.get_Item(j);
if (task.state != DUTaskState.Pause)
{
this._DoStartTask(task);
j--;
}
if (!this.ProcessListNotFull)
{
break;
}
}
}
}
protected void _SuccessCompleteTask(T task)
{
this._processingList.Remove(task);
task.FireSuccess();
task.Close();
}
protected void _ErrorCompleteTask(T task)
{
this._processingList.Remove(task);
task.FireError();
task.Close();
}
protected void _RunningTask(T task, float passed)
{
task.Running(passed);
}
protected void HandleDirtyTaskListAndClear(List<T> list, Action<T> call)
{
if (list.get_Count() > 0)
{
for (int i = 0; i < list.get_Count(); i++)
{
call.Invoke(list.get_Item(i));
}
list.Clear();
}
}
protected void HandleDirtyTaskListAndClear<V>(List<T> list, Action<T, V> call, V param)
{
if (list.get_Count() > 0)
{
for (int i = 0; i < list.get_Count(); i++)
{
call.Invoke(list.get_Item(i), param);
}
list.Clear();
}
}
}
|
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CloneDeploy_App.Controllers.Authorization;
using CloneDeploy_Entities;
using CloneDeploy_Entities.DTOs;
using CloneDeploy_Services;
namespace CloneDeploy_App.Controllers
{
public class FileFolderController : ApiController
{
private readonly FileFolderServices _fileFolderServices;
public FileFolderController()
{
_fileFolderServices = new FileFolderServices();
}
[CustomAuth(Permission = "GlobalDelete")]
public ActionResultDTO Delete(int id)
{
var result = _fileFolderServices.DeleteFileFolder(id);
if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
return result;
}
[CustomAuth(Permission = "GlobalRead")]
public FileFolderEntity Get(int id)
{
var result = _fileFolderServices.GetFileFolder(id);
if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
return result;
}
[CustomAuth(Permission = "GlobalRead")]
public IEnumerable<FileFolderEntity> Get(string searchstring = "")
{
return string.IsNullOrEmpty(searchstring)
? _fileFolderServices.SearchFileFolders()
: _fileFolderServices.SearchFileFolders(searchstring);
}
[CustomAuth(Permission = "GlobalRead")]
public ApiStringResponseDTO GetCount()
{
return new ApiStringResponseDTO {Value = _fileFolderServices.TotalCount()};
}
[CustomAuth(Permission = "GlobalCreate")]
public ActionResultDTO Post(FileFolderEntity fileFolder)
{
var result = _fileFolderServices.AddFileFolder(fileFolder);
if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
return result;
}
[CustomAuth(Permission = "GlobalUpdate")]
public ActionResultDTO Put(int id, FileFolderEntity fileFolder)
{
fileFolder.Id = id;
var result = _fileFolderServices.UpdateFileFolder(fileFolder);
if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
return result;
}
}
} |
using System;
using fraction_calculator_dotnet.Operators;
namespace fraction_calculator_dotnet.Entity
{
public class Fraction
{
public long Numerator { get; set; }
private ulong _denominiator;
public ulong Denominator
{
get { return _denominiator; }
set
{
if (value == 0) throw new ArgumentOutOfRangeException("Denominator must be greater than 0");
_denominiator = value;
}
}
public Fraction(long numerator, ulong denominator)
{
Numerator = numerator;
Denominator = denominator;
}
public Fraction Invert()
{
var temp = Numerator;
Numerator = (long)Denominator;
if (temp < 0)
{
Numerator *= -1;
}
Denominator = (ulong)Math.Abs(temp);
return this;
}
public Fraction Reduce()
{
var gcdOperator = new Gcd();
var gcd = gcdOperator.Execute((ulong)Math.Abs(Numerator), Denominator);
var negative = Numerator < 0;
Numerator /= (long)gcd;
if (negative) Numerator *= -1;
Denominator /= (ulong)gcd;
return this;
}
public static bool TryParse(string s, out Fraction f)
{
var parts = s.Split('/');
if (parts.Length == 1)
{
return TryParse($"{s}/1", out f);
}
if (parts.Length != 2)
{
f = null;
return false;
}
if (!long.TryParse(parts[0], out long numerator))
{
f = null;
return false;
}
ulong denominator;
if (parts[1].IndexOf('-') != -1 && long.TryParse(parts[1], out long d))
{
numerator *= -1;
denominator = (ulong)Math.Abs(d);
}
else if (!ulong.TryParse(parts[1], out denominator))
{
f = null;
return false;
}
f = new Fraction(numerator, denominator);
return true;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (!(obj is Fraction other)) return false;
var lcdOperator = new Lcd();
var lcd = lcdOperator.Execute(Denominator, other.Denominator);
return (Numerator * (long)lcd / (long)Denominator) ==
(other.Numerator * (long)lcd / (long)other.Denominator);
}
public override string ToString()
{
var dec = (decimal)(Numerator/(long)Denominator);
if (dec == 1)
return 1.ToString();
return $"{Numerator}/{Denominator}";
}
public override int GetHashCode()
{
return HashCode.Combine(Numerator, Denominator);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabmanGrinderApp
{
class Vial
{
private int weight;
public Vial(int weightOfContents)
{
weight = weightOfContents;
}
public int Weight
{
get { return weight; }
set { weight = value; }
}
public string Location { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using UnityEngine;
namespace Game.Graphics.UI.Screen.Window
{
public class WebWindow : WindowManager
{
public Window ChatWindow, UserInfoWindow, EventsWindow, NewsWindow;
private readonly List<Window> _windows = new List<Window>();
private void Start()
{
_windows.Add(ChatWindow);
_windows.Add(UserInfoWindow);
_windows.Add(EventsWindow);
_windows.Add(NewsWindow);
}
public void ChangeWindow(WebWindowType to)
{
var active = _windows.FirstOrDefault(x => x.IsActive);
if (active != null)
{
Hide(active);
}
switch (to)
{
case WebWindowType.Chat:
Show(ChatWindow);
ChatWindow.IsActive = true;
break;
case WebWindowType.UserInfo:
Show(UserInfoWindow);
UserInfoWindow.IsActive = true;
break;
case WebWindowType.Events:
Show(EventsWindow);
EventsWindow.IsActive = true;
break;
case WebWindowType.News:
Show(NewsWindow);
NewsWindow.IsActive = true;
break;
default:
throw new ArgumentOutOfRangeException(nameof(to), to, null);
}
}
}
public enum WebWindowType
{
Chat,
UserInfo,
Events,
News
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BasicEvent2
{
class Program
{
static void Main(string[] args)
{
MyEventClass instance = new MyEventClass();
//Subscribe method ที่ได้ประกาศไว้
instance.ThresholdReached += Method1;
instance.ThresholdReached += Method2;
instance.ThresholdReached += Method3;
//call method ที่จะทำ data++ จนกว่าจะถึง threshold
int currentData;
currentData = instance.Add();
currentData = instance.Add();
currentData = instance.Add(); //จังหวะนี้จะถึง threshold และ trigger event "ThresholdReached" ส่งผลให้ event "ThresholdReached" ไป notify Method1,Method2,Method3 ที่ได้ subscribe ใน event นี้ไว้
}
static void Method1(int i)
{
Console.WriteLine("This is Method1 argument int i=" + i);
}
static void Method2(int i)
{
Console.WriteLine("This is Method2 argument int i=" + i);
}
static void Method3(int i)
{
Console.WriteLine("This is Method3 argument int i=" + i);
}
}
class MyEventClass
{
//instance constants
private const int threshold = 3;
//instance variables
public delegate void MyEventSignature(int i);
public event MyEventSignature ThresholdReached;
//properties
public int data
{
get;
private set;
}
//constructor
public MyEventClass()
{
data = 0;
}
//ทำเป็น protected virtual เพื่อเผื่อเวลาเอาไปใช้งานจริงแล้วต้อง inherit class นี้ไป class ลูกจะได้สามารถ override logic การ trigger event ได้ ว่าจะให้ trigger ตอนไหนยังไง หรือจะไม่ให้ trigger เลย
protected virtual void OnThresholdReached()
{
ThresholdReached(data);
}
public int Add()
{
data++;
if (data >= threshold) //พอถึง threshold แล้วจะ call method "OnThresholdReached" เพื่อให้ "OnThresholdReached" ไป trigger event อีกทีหนึ่ง
{
OnThresholdReached(); //จริงๆตรงนี้ใช้ ThresholdReached(data); เพื่อ trigger event เลยก็ได้ แต่จะมี scalability น้อยกว่าตรงที่ class ลูกที่ inherit ไปจะปรับแก้ไข logic การ trigger event ว่าจะไม่เอา event หรือแก้เงื่อนไขอะไรไม่ได้
}
return data; //return data กลับไปเพื่อบอกว่าหลังจาก Add แล้ว data เป็นอะไรเฉยๆ
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using EntityFramework.Extensions;
using SO.Urba.Models.ValueObjects;
using SO.Urba.DbContexts;
using SO.Utility.Models.ViewModels;
using SO.Utility;
using SO.Utility.Helpers;
using SO.Utility.Extensions;
namespace SO.Urba.Managers.Base
{
public class ReferralManagerBase
{
public ReferralManagerBase()
{
}
/// <summary>
/// Find Referral matching the referralId (primary key)
/// </summary>
public ReferralVo get(int referralId)
{
using (var db = new MainDb())
{
var res = db.referrals
.Include(a => a.surveyAnswerses)
.Include(q => q.surveyAnswerses.Select(c => c.questionType))
.FirstOrDefault(p => p.referralId == referralId);
return res;
}
}
/// <summary>
/// Get First Item
/// </summary>
public ReferralVo getFirst()
{
using (var db = new MainDb())
{
var res = db.referrals
.Include(a => a.surveyAnswerses)
.FirstOrDefault();
return res;
}
}
public SearchFilterVm search(SearchFilterVm input)
{
using (var db = new MainDb())
{
var query = db.referrals
.Include(a => a.surveyAnswerses)
.OrderByDescending(b => b.created)
.Where(e => (input.isActive == null || e.isActive == input.isActive)
// && (e.accepted.Contains(input.keyword) || string.IsNullOrEmpty(input.keyword))
);
if (input.paging != null)
{
input.paging.totalCount = query.Count();
query = query
.Skip(input.paging.skip)
.Take(input.paging.rowCount);
}
input.result = query.ToList<object>();
return input;
}
}
//
public List<ReferralVo> getAll(bool? isActive = true)
{
using (var db = new MainDb())
{
var list = db.referrals
.Include(a => a.surveyAnswerses)
.Where(e => isActive == null || e.isActive == isActive)
.ToList();
return list;
}
}
public bool delete(int referralId)
{
using (var db = new MainDb())
{
var res = db.referrals
.Where(e => e.referralId == referralId)
.Delete();
return true;
}
}
public ReferralVo update(ReferralVo input, int? referralId = null)
{
using (var db = new MainDb())
{
if (referralId == null)
referralId = input.referralId;
var res = db.referrals.FirstOrDefault(e => e.referralId == referralId);
if (res == null) return null;
input.created = res.created;
// input.createdBy = res.createdBy;
db.Entry(res).CurrentValues.SetValues(input);
db.SaveChanges();
return res;
}
}
public ReferralVo insert(ReferralVo input)
{
using (var db = new MainDb())
{
db.referrals.Add(input);
db.SaveChanges();
return input;
}
}
public int count()
{
using (var db = new MainDb())
{
return db.referrals.Count();
}
}
}
}
|
using System;
using Backend.Samples.Contracts;
using NServiceBus;
using Sample.Backend.Messages.Commands;
namespace Sample.Backend.Endpoint
{
public class ProcessValue : IHandleMessages<DoSomethingWithValue>
{
public IBus Bus { get; set; }
public void Handle(DoSomethingWithValue message)
{
//do some work
//save value to raven or wherever
Console.WriteLine(message);
Bus.Publish<IDidSomethingWithValue>(x => x.Id = "some id we generated or got from raven depending on preference");
}
}
} |
#if !NET461
namespace Unosquare.WaveShare.FingerprintModule.Resources
{
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
/// <summary>
/// Provides access to embedded assembly files.
/// </summary>
internal static class EmbeddedResources
{
internal const string LibCLibrary = "libc";
/// <summary>
/// Initializes static members of the <see cref="EmbeddedResources"/> class.
/// </summary>
static EmbeddedResources()
{
EntryAssembly = typeof(EmbeddedResources).GetTypeInfo().Assembly;
ResourceNames = new ReadOnlyCollection<string>(EntryAssembly.GetManifestResourceNames());
var uri = new UriBuilder(EntryAssembly.CodeBase);
var path = Uri.UnescapeDataString(uri.Path);
EntryAssemblyDirectory = Path.GetDirectoryName(path);
}
/// <summary>
/// Gets the resource names.
/// </summary>
/// <value>
/// The resource names.
/// </value>
public static ReadOnlyCollection<string> ResourceNames { get; }
/// <summary>
/// Gets the entry assembly directory.
/// </summary>
/// <value>
/// The entry assembly directory.
/// </value>
public static string EntryAssemblyDirectory { get; }
public static Assembly EntryAssembly { get; }
/// <summary>
/// Changes file permissions on a Unix file system.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="mode">The mode.</param>
/// <returns>The result.</returns>
[DllImport(LibCLibrary, EntryPoint = "chmod", SetLastError = true)]
public static extern int Chmod(string filename, uint mode);
/// <summary>
/// Converts a string to a 32 bit integer. Use endpointer as IntPtr.Zero.
/// </summary>
/// <param name="numberString">The number string.</param>
/// <param name="endPointer">The end pointer.</param>
/// <param name="numberBase">The number base.</param>
/// <returns>The result.</returns>
[DllImport(LibCLibrary, EntryPoint = "strtol", SetLastError = true)]
public static extern int StringToInteger(string numberString, IntPtr endPointer, int numberBase);
/// <summary>
/// Extracts all the file resources to the specified base path.
/// </summary>
public static void ExtractAll()
{
var basePath = EntryAssemblyDirectory;
foreach (var resourceName in ResourceNames)
{
var filename = resourceName
.Substring($"{typeof(EmbeddedResources).Namespace}.".Length);
var targetPath = Path.Combine(basePath, filename.Replace(".temp", string.Empty));
if (File.Exists(targetPath)) return;
using (var stream =
EntryAssembly.GetManifestResourceStream($"{typeof(EmbeddedResources).Namespace}.{filename}"))
{
using (var outputStream = File.OpenWrite(targetPath))
{
stream?.CopyTo(outputStream);
}
try
{
Chmod(targetPath, (uint)StringToInteger("0777", IntPtr.Zero, 8));
}
catch
{
/* Ignore */
}
}
}
}
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace ISISFighters
{
class Enemy
{
public Texture2D enemytexture;
public Texture2D destroytexture;
public Texture2D smoketexture;
public Texture2D shelltexture;
public Texture2D exptexture;
public Rectangle enemyrectangle;
public Rectangle smokerectangle;
public Rectangle explrc;
public Vector2 originalposition;
public Vector2 position;
public Vector2 position2;
public Vector2 position3;
public int framewidth;
public int frameheight;
public int currentframe;
public int currentframe2;
public int currentframe3;
public int currentframe4;
public int lastframe;
public float timer;
public float timer2;
public float timer3;
public float atimer;
public float reloadtime;
public float interval = 80;
public float extimer;
public int action = 2;
public int lastaction;
public int health;
public int hit;
public int damage;
public TankShell shell;
public Explosion exp;
public Player target;
public FireAim playeraim;
public float x;
public float y;
public bool explode;
internal bool reloaded = true;
public List<Allies> allies;
public void Timer(GameTime gameTime)
{
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
currentframe++;
timer = 0;
if (currentframe > 4)
currentframe = 4;
}
}
public virtual void Update()
{
}
public virtual void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(enemytexture, position, enemyrectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
public virtual void Set()
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
}
public virtual void Scroll()
{
if (Keyboard.GetState().IsKeyDown(Keys.Right))
position.X -= 3;
}
public virtual void GetDamage(GameTime gameTime)
{
if (health > 0)
health -= damage;
}
public virtual void Kill(GameTime gameTime)
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
Timer(gameTime);
}
}
// Syrian Infantry soldier
class SyrianSoldier: Enemy
{
public SyrianSoldier(Texture2D syriansoldiertexture, Vector2 newposition, Player player, List<Allies> targets, int newframewidth, int newframeheight)
{
enemytexture = syriansoldiertexture;
position = newposition;
framewidth = newframewidth;
frameheight = newframeheight;
health = 100;
hit = 0;
allies = targets;
target = player;
}
// set - place the soldier to the initial position in the game
public override void Set()
{
base.Set();
}
// soldier moves to attack
public void Update(GameTime gameTime, SoundEffect ak47, SoundEffect scream, SoundEffect scream2)
{
// shooting allies
if (allies.Any<Allies>(i => position.X - i.position.X < 400 && i.health > 0))
{
action = 3;
if (allies.Any<Allies>(i => i.action == 3))
health -= 2;
else { health -= 0; }
}
// shooting player
else if (position.X - target.position.X < 800 && position.X - target.position.X >= 400)
action = 1;
else if (position.X - target.position.X <= 400 && target.health > 0)
action = 3;
else { action = 2; }
if (position.X - target.position.X <= 400 && health > 0 && action == 3)
target.health -= hit;
// moving
if (health > 0)
{
if (action == 1)
{
position.X -= 2;
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
if (currentframe == 1)
{ currentframe = 5; }
currentframe++;
timer = 0;
if (currentframe > 7)
currentframe = 5;
}
}
// stand still
else if (action == 2)
{
position.X += 0;
currentframe = 0;
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
}
// attack
else if (action == 3)
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
timer2 += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer2 > interval)
{
if (currentframe == 0)
{ currentframe = 7;
}
currentframe++;
timer2 = 0;
if (currentframe > 12)
currentframe = 0;
if (currentframe == 8)
{
hit = 1;
ak47.Play(0.5f, 0, 0);
}
else { hit = 0; }
}
}
}
else
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
Random rand = new Random();
timer3 += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer3 > interval)
{
int sample = rand.Next(0, 2);
if (currentframe >= 5)
{ currentframe = 0; }
currentframe++;
timer3 = 0;
if (currentframe == 1)
{
if (sample == 0)
{
scream.Play(0.5f, 0, 0);
}
else
{
scream2.Play(0.2f, 0, 0);
}
}
if (currentframe > 4)
{
currentframe = 4;
}
}
}
}
// scrolling while the player is moving
public override void Scroll()
{
base.Scroll();
}
}
// RPG
class RPG : Enemy
{
private int lastframe;
public RPG(Texture2D rpgtexture, Texture2D shelltx, Texture2D smoketx, Texture2D exptx, Vector2 newposition, Player player, List<Allies> targets, int newframewidth, int newframeheight)
{
enemytexture = rpgtexture;
shelltexture = shelltx;
smoketexture = smoketx;
exptexture = exptx;
position = newposition;
framewidth = newframewidth;
frameheight = newframeheight;
health = 100;
hit = 0;
allies = targets;
target = player;
reloadtime = 0;
shell = new TankShell(shelltexture, position, 38, 8);
y = -20;
}
// set - place the soldier to the initial position in the game
public override void Set()
{
base.Set();
}
// soldier moves to attack
public void Update(GameTime gameTime, SoundEffect shoot, SoundEffect scream, SoundEffect scream2, SoundEffect blow)
{
// shooting allies
if (allies.Any<Allies>(i => position.X - i.position.X < 400 && i.health > 0))
{
action = 3;
if (allies.Any<Allies>(i => i.action == 3))
health -= 2;
else { health -= 0; }
}
// shooting player
else if (position.X - target.position.X < 800 && position.X - target.position.X >= 400)
action = 1;
else if (position.X - target.position.X <= 400 && target.health > 0)
action = 3;
else { action = 2; }
if (position.X - target.position.X <= 400 && health > 0 && action == 3)
target.health -= hit;
// moving
if (health > 0)
{
// roadkill
if (target.position.X + 50 >= position.X)
health = 0;
if (action == 1)
{
position.X -= 2;
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
if (currentframe == 1)
{ currentframe = 5; }
currentframe++;
timer = 0;
if (currentframe > 7)
currentframe = 5;
}
}
// stand still
else if (action == 2)
{
position.X += 0;
currentframe = 0;
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
}
// attack
else if (action == 3)
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
{
atimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
reloadtime += (float)gameTime.ElapsedGameTime.TotalSeconds;
// reload
if (reloadtime >= 3)
{
reloadtime = 0;
reloaded = true;
currentframe = 8;
}
else
{
reloaded = false;
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
timer = 0;
currentframe++;
}
if (currentframe > 12)
currentframe = 12;
}
if(currentframe == 8 && lastframe != 8)
shoot.Play(0.7f, 0, 0);
// shell firing
if (atimer >= 0.002)
{
atimer = 0;
if (position.X - x > target.position.X && x != -41)
x += 12;
else if (x == -41 && reloaded)
x += 12;
else if (x == -41 && !reloaded)
x = -41;
else { x = -41; }
}
// hiting the player
if (position.X - x <= target.position.X)
{
target.health -= 15;
explode = true;
blow.Play(0.7f, 0, 0);
}
if (explode)
{
smokerectangle = new Rectangle(currentframe2 * 120, 0, 120, 120);
timer2 += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (timer2 > 0.15)
{
timer2 = 0;
currentframe2++;
}
if (currentframe2 > 4)
{
currentframe2 = 0;
// shooting.Play(0.2f, 0, 0);
explode = false;
}
// shooting sound
}
// fire smoke
if (x > -40)
{
smokerectangle = new Rectangle(currentframe2 * 120, 0, 120, 120);
timer3 += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (timer3 > 0.15)
{
timer3 = 0;
currentframe2++;
}
if (currentframe2 > 4)
currentframe2 = 0;
// shooting sound
// if (x > -40 && reloaded)
// shooting.Play(0.2f, 0, 0);
// if (action == 3 && lastaction != 3)
// shooting.Play(0.2f, 0, 0);
}
}
lastaction = action;
lastframe = currentframe;
}
}
else
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
Random rand = new Random();
timer3 += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer3 > interval)
{
int sample = rand.Next(0, 2);
if (currentframe >= 5)
{ currentframe = 0; }
currentframe++;
timer3 = 0;
if (currentframe == 1)
{
if (sample == 0)
{
scream.Play(0.5f, 0, 0);
}
else
{
scream2.Play(0.2f, 0, 0);
}
}
if (currentframe > 4)
{
currentframe = 4;
}
}
}
}
// scrolling while the player is moving
public override void Scroll()
{
base.Scroll();
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (action == 3 && health > 0)
{
if (x > -40)
spriteBatch.Draw(shelltexture, new Vector2(position.X - x, position.Y - y), shell.firerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
// if (x > -40 && health > 0)
// spriteBatch.Draw(smoketexture, new Vector2(position.X - 10, position.Y - 15), smokerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
if (explode && health > 0)
spriteBatch.Draw(smoketexture, new Vector2(target.position.X, target.position.Y - 50), smokerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
if (health < 0)
spriteBatch.Draw(exptexture, new Vector2(position.X + 50, position.Y - 70), explrc, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
}
// Syrian Machinegun
class MachineGun: Enemy
{
public MachineGun(Texture2D machineguntexture, Vector2 newposition, int newframewidth, int newframeheight)
{
enemytexture = machineguntexture;
position = newposition;
framewidth = newframewidth;
frameheight = newframeheight;
health = 200;
}
public override void Set()
{
base.Set();
}
public void Update(GameTime gameTime, SoundEffect machinegunsound, SoundEffect explosion)
{
if(health > 0)
{
// stand still
if (action == 2)
{
currentframe = 0;
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
}
// attack
else if (action == 3)
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
machinegunsound.Play(0.6f, 0, 0);
if (currentframe == 0)
{
currentframe = 6;
}
currentframe++;
timer = 0;
if (currentframe > 10)
currentframe = 0;
if(currentframe == 7)
hit = 1;
else { hit = 0; }
}
}
}
// killing sequence
else
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
timer2 += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer2 > interval)
{
if (currentframe > 6)
{ currentframe = 0; }
currentframe++;
timer2 = 0;
if (currentframe == 1)
{ explosion.Play(0.3f, 0, 0); }
if (currentframe > 5)
{
currentframe = 6;
}
}
}
}
public override void Scroll()
{
base.Scroll();
}
}
class Tower: Enemy
{
public Tower(Texture2D towertexture, Texture2D destroy, Player player, List<Allies> targets, Vector2 newposition, int newframewidth, int newframeheight)
{
enemytexture = towertexture;
position = newposition;
framewidth = newframewidth;
frameheight = newframeheight;
health = 400;
destroytexture = destroy;
target = player;
allies = targets;
}
public override void Set()
{
base.Set();
}
public void Update(GameTime gameTime, SoundEffect machinegunsound, SoundEffect explosion)
{
if (health > 0)
{
if (allies.Any<Allies>(i => position.X - i.position.X < 400 && i.health > 0))
{
action = 3;
if (allies.Any<Allies>(i => i.action == 3))
health -= 2;
else { health -= 0; }
}
// shooting player
else if (position.X - target.position.X <= 400 && target.health > 0)
action = 3;
else { action = 2; }
// stand still
if (action == 2)
{
currentframe = 0;
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
}
// attack
else if (action == 3)
{
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
machinegunsound.Play(0.4f, 0, 0);
if (currentframe > 2)
{
currentframe = 0;
hit = 1;
}
else { hit = 0; }
currentframe++;
timer = 0;
}
if (position.X - target.position.X <= 400 && health > 0 && action == 3)
target.health -= hit;
}
}
// killing sequence
else
{
if (enemytexture != destroytexture)
{ currentframe = 0;
explosion.Play(1.0f, 0, 0);
}
enemyrectangle = new Rectangle(currentframe * framewidth, 0, framewidth, frameheight);
enemytexture = destroytexture;
timer2 += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer2 > interval)
{
timer2 = 0;
currentframe++;
if (currentframe > 3)
currentframe = 4;
}
}
}
public override void Scroll()
{
base.Scroll();
}
}
class Artillery : Enemy
{
public Artillery(Texture2D arttexture, Texture2D destroy, Texture2D smoke, Texture2D shelltx, Texture2D newexptexture, Vector2 newposition, Vector2 newposition2, int newframewidth, int newframeheight)
{
enemytexture = arttexture;
position = newposition;
position2 = newposition;
framewidth = newframewidth;
frameheight = newframeheight;
health = 350;
destroytexture = destroy;
smoketexture = smoke;
shelltexture = shelltx;
exptexture = newexptexture;
currentframe3 = 0;
shell = new TankShell(shelltexture, position, 18, 18);
x = 0;
y = 0;
}
public void Update(GameTime gameTime, SoundEffect artshoot, SoundEffect explosion, SoundEffect shellblow)
{
if (health > 0)
{
// stand still
if (action == 2)
{
currentframe = 0;
enemyrectangle = new Rectangle(0 * currentframe * framewidth, 0, framewidth, frameheight);
}
// attack
else if (action == 3)
{
enemyrectangle = new Rectangle(0, currentframe4*frameheight, framewidth, frameheight);
smokerectangle = new Rectangle(currentframe2 * 120, 0, 120, 120);
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
timer3 += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (currentframe4 > 7)
currentframe4 = 0;
if (timer3 > 0.22)
{
timer3 = 0;
currentframe4++;
}
// shell traectory
if (timer > 50)
{
x += 32;
if (x <= 300)
y += 20;
else if (x <= 400)
y += 10;
else if (x <= 500)
y -= 13;
else if (x <= 800)
y -= 25;
else
{
x = 0;
y = 0;
artshoot.Play(1.0f, 0, 0);
}
if(x >= 800)
{
explode = true;
position3 = new Vector2(position.X - x - 35, position.Y - y - 40);
shellblow.Play();
}
if (explode)
{
timer2 += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
exp = new Explosion(smoketexture, position3, 120, 120);
exp.firerectangle = new Rectangle(currentframe3*120, 0, 120, 120);
if (timer2 >= 4)
{
timer2 = 0;
currentframe3++;
if(currentframe3 == 0)
hit = 5;
else { hit = 0; }
if (currentframe3 >= 4)
{
currentframe3 = -1;
explode = false;
}
}
}
else { hit = 0; }
if (currentframe > 2)
{
currentframe = 0;
}
if (currentframe2 > 5)
currentframe2 = -20;
currentframe++;
currentframe2++;
timer = 0;
}
}
}
// killing sequence
else
{
explode = false;
currentframe2 = 0;
if (enemytexture != destroytexture)
{
currentframe = 0;
explosion.Play(1.0f, 0, 0);
}
enemytexture = destroytexture;
explrc = new Rectangle(currentframe * 350, 0, 350, 350);
extimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
enemyrectangle = new Rectangle(currentframe2*framewidth, 0, framewidth, frameheight);
if (extimer > 0.2)
{
extimer = 0;
currentframe++;
}
if (currentframe > 4)
currentframe = 5;
}
}
public override void Scroll()
{
base.Scroll();
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (action == 3)
{
spriteBatch.Draw(smoketexture, new Vector2(position.X - 30, position.Y - 25), smokerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
spriteBatch.Draw(shelltexture, new Vector2(position.X - x, position.Y - y), shell.firerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
if (explode)
spriteBatch.Draw(smoketexture, position3, exp.firerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
if (health < 0)
spriteBatch.Draw(exptexture, new Vector2(position.X + 50, position.Y - 70), explrc, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
}
class EnemyTank : Enemy
{
public EnemyTank(Texture2D tanktexture, Texture2D destroy, Texture2D smoke, Texture2D shelltx, Texture2D exptx, Vector2 newposition, Vector2 newposition2, Player tanktarget, FireAim aim, int newframewidth, int newframeheight)
{
enemytexture = tanktexture;
position = newposition;
position2 = newposition;
framewidth = newframewidth;
frameheight = newframeheight;
health = 850;
destroytexture = destroy;
smoketexture = smoke;
shelltexture = shelltx;
enemyrectangle = new Rectangle(0, 0, framewidth, frameheight);
target = tanktarget;
playeraim = aim;
exptexture = exptx;
currentframe3 = 0;
shell = new TankShell(shelltexture, position, 96, 16);
}
public void Update(GameTime gameTime, SoundEffect shooting, SoundEffect explosion)
{
if (health > 0)
{
// stand still
if (playeraim.position.X >= position.X - framewidth / 2 &&
playeraim.position.X <= position.X + framewidth / 2 &&
playeraim.position.Y >= position.Y - frameheight / 2 &&
playeraim.position.Y >= position.Y - frameheight / 2 &&
Keyboard.GetState().IsKeyDown(Keys.Space))
health -= target.hit;
if (position.X - target.position.X < 800 && position.X - target.position.X >= 700)
action = 1;
else if (position.X - target.position.X < 700 && target.health > 0)
action = 3;
else { action = 2; }
if(action != 3)
{
x = -40;
y = -25;
}
if (action == 2)
{
currentframe = 0;
}
// move
else if (action == 1)
{
currentframe = 0;
position.X -= 3;
}
// attack
if (action == 3)
{
atimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
reloadtime += (float)gameTime.ElapsedGameTime.TotalSeconds;
// reload
if (reloadtime >= 3)
{
reloadtime = 0;
reloaded = true;
}
else { reloaded = false; }
// shell firing
if (atimer >= 0.002)
{
atimer = 0;
if (position.X - x > target.position.X && x != -41)
x += 12;
else if (x == -41 && reloaded)
x += 12;
else if (x == -41 && !reloaded)
x = -41;
else { x = -41; }
}
// hiting the player
if (position.X - x <= target.position.X)
{
target.health -= 50;
explode = true;
}
if (explode)
{
smokerectangle = new Rectangle(currentframe2 * 120, 0, 120, 120);
timer2 += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (timer2 > 0.15)
{
timer2 = 0;
currentframe2++;
}
if (currentframe2 > 4)
{
currentframe2 = 0;
shooting.Play(0.2f, 0, 0);
explode = false;
}
// shooting sound
}
// fire smoke
if (x > -40)
{
smokerectangle = new Rectangle(currentframe2 * 120, 0, 120, 120);
timer3 += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (timer3 > 0.15)
{
timer3 = 0;
currentframe2++;
}
if (currentframe2 > 4)
currentframe2 = 0;
// shooting sound
if (x > -40 && reloaded)
shooting.Play(0.8f, 0, 0);
if(action == 3 && lastaction != 3)
shooting.Play(0.8f, 0, 0);
}
}
lastaction = action;
}
// killing sequence
else
{
explrc = new Rectangle(currentframe * 350, 0, 350, 350);
extimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if(extimer < 0.05 && enemytexture != destroytexture)
explosion.Play(1.0f, 0, 0);
enemyrectangle = new Rectangle(0, 0, framewidth, frameheight);
if (extimer > 0.2)
{
extimer = 0;
currentframe++;
}
if(currentframe > 2)
enemytexture = destroytexture;
if (currentframe > 4)
{
currentframe = 5;
}
lastframe = currentframe;
}
}
public override void Scroll()
{
base.Scroll();
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (action == 3 && health > 0)
{
if(x > -40)
spriteBatch.Draw(shelltexture, new Vector2(position.X - x, position.Y - y), shell.firerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
if (x > - 40 && health > 0)
spriteBatch.Draw(smoketexture, new Vector2(position.X - 10, position.Y - 15), smokerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
if (explode && health > 0)
spriteBatch.Draw(smoketexture, new Vector2(target.position.X, target.position.Y - 100), smokerectangle, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
if (health < 0)
spriteBatch.Draw(exptexture, new Vector2(position.X + 50, position.Y - 70), explrc, Color.White, 0f, originalposition, 1.0f, SpriteEffects.None, 0);
}
}
}
|
namespace AmqpNetLiteRpcCore.Util
{
internal interface IPendingRequest
{
void SetResult(AmqpRpcResponse response);
void SetError(string error);
}
}
|
using System;
public class Programa1
{
public static void Main()
{
// Programa I
//https://youtu.be/QdCoEuhkTng
//Entradas
Console.WriteLine("Ingrese el lado 1");
double z = double.Parse(Console.ReadLine());
Console.WriteLine("Ingrese el lado 2");
double y = double.Parse(Console.ReadLine());
//Proceso
//Hipotenusa
double t = Math.Sqrt((y*y)+(z*z));
//Angulo c
double c = Math.Asin(z / t);
c = c * (180 / Math.PI); //Otra forma es usando el operador *=
//Angulo a
double a = 180 - c - 90;
//Salidas
Console.WriteLine("La Hipotenusa es:");
Console.WriteLine(t);
Console.WriteLine("Sus angulos son: ");
Console.WriteLine(c.ToString() + " " + a.ToString());
}
}
|
namespace MediaSystem.Api.Controllers
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using MediaSystem.Api.Models;
using MediaSystem.Data;
using MediaSystem.Models;
using MediaSystem.Services.Data;
using MediaSystem.Services.Data.Interfaces;
using StudentSystem.Data;
public class AlbumController : ApiController
{
private readonly IAlbumService albumService;
public AlbumController()
{
var db = new MediaSystemContext();
this.albumService = new AlbumService(new EfGenericRepository<Album>(db), new EfGenericRepository<Producer>(db), new EfGenericRepository<Artist>(db), new EfGenericRepository<Song>(db));
}
public IHttpActionResult Get()
{
var result = this.albumService
.GetAll()
.ToList()
.Select(MapAlbum)
.ToList();
return this.Ok(result);
}
public IHttpActionResult Get(int id)
{
var result = this.albumService.GetById(id);
if (result == null)
{
return this.NotFound();
}
return this.Ok(MapAlbum(result));
}
public IHttpActionResult Post(AlbumApiModel album)
{
if (!this.ModelState.IsValid)
{
return this.BadRequest(this.ModelState);
}
if (album == null)
{
return this.BadRequest("No data");
}
this.albumService.Add(album.Title, album.Year, album.Producer, album.ArtistsIds, album.SongsIds);
return this.Ok();
}
public IHttpActionResult Put(int id, AlbumApiModel album)
{
if (album == null)
{
return this.BadRequest("No data");
}
if (this.albumService.Update(id, album.Title, album.Year, album.Producer, album.ArtistsIds, album.SongsIds))
{
return this.Ok();
}
return this.NotFound();
}
public IHttpActionResult Delete(int id)
{
if (this.albumService.DeleteById(id))
{
return this.Ok();
}
return this.NotFound();
}
private static AlbumApiModel MapAlbum(Album album)
{
string producerName;
if (album.Producer == null)
{
producerName = null;
}
else
{
producerName = album.Producer.Name;
}
return new AlbumApiModel() { Id = album.Id, Title = album.Title, Producer = producerName, Year = album.Year,
ArtistsIds = album.Artists.Select(a => a.Id).ToList(),
SongsIds = album.Songs.Select(s => s.Id).ToList() };
}
}
}
|
using MaterialSurface;
using System;
using System.Windows.Forms;
using TutteeFrame2.Controller;
using TutteeFrame2.Model;
using TutteeFrame2.Utils;
namespace TutteeFrame2.View
{
public partial class FormClassView : UserControl
{
FormClassController controller;
public HomeView Home;
public Teacher mainTeacher;
public FormClassView()
{
InitializeComponent();
controller = new FormClassController(this);
}
public void Fetch()
{
controller.FetchData();
}
public void SetHome(HomeView _home, Teacher _teacher)
{
this.Home = _home;
mainTeacher = _teacher;
lbFormClass.Text = _teacher.FormClassID;
}
public void ShowData()
{
if (controller.students == null)
{
Dialog.Show(Home, "Đã có lỗi xảy ra, vui lòng thử lại", "Lỗi");
return;
}
lbTotalStudentInClass.Text = controller.students.Count.ToString();
listviewStudentInClass.Items.Clear();
for (int i = 0; i < controller.students.Count; i++)
{
listviewStudentInClass.Items.Add(new ListViewItem(new string[] { (i + 1).ToString(), controller.students[i].ID, controller.students[i].GetName(),
"--","","--","","--",""}));
if (controller.averageScoreList[controller.students[i].ID][0].Value > -1)
listviewStudentInClass.Items[i].SubItems[3].Text = controller.averageScoreList[controller.students[i].ID][0].Value.ToString("F");
listviewStudentInClass.Items[i].SubItems[4].Text = controller.studentConducts[controller.students[i].ID].Conducts[0].GetReadableValue();
if (controller.averageScoreList[controller.students[i].ID][1].Value > -1)
listviewStudentInClass.Items[i].SubItems[5].Text = controller.averageScoreList[controller.students[i].ID][1].Value.ToString("F");
listviewStudentInClass.Items[i].SubItems[6].Text = controller.studentConducts[controller.students[i].ID].Conducts[1].GetReadableValue();
if (controller.averageScoreList[controller.students[i].ID][2].Value > -1)
listviewStudentInClass.Items[i].SubItems[7].Text = controller.averageScoreList[controller.students[i].ID][2].Value.ToString("F");
listviewStudentInClass.Items[i].SubItems[8].Text = controller.studentConducts[controller.students[i].ID].Conducts[2].GetReadableValue();
}
}
private void OnChooseStudent(object sender, EventArgs e)
{
btnViewInfo.Enabled = btnViewStudentScore.Enabled = btnSetConduct.Enabled = btnAddFault.Enabled = (listviewStudentInClass.SelectedItems.Count > 0);
}
private void OnViewStudent(object sender, EventArgs e)
{
string selectedStudentID = listviewStudentInClass.SelectedItems[0].SubItems[1].Text;
StudentCardView cardView = new StudentCardView(selectedStudentID);
OverlayForm _ = new OverlayForm(this.Home, cardView);
cardView.Show();
}
private void OnUpdateStudentConduct(object sender, EventArgs e)
{
string selectedStudentID = listviewStudentInClass.SelectedItems[0].SubItems[1].Text;
string studentName = listviewStudentInClass.SelectedItems[0].SubItems[2].Text;
int grade = int.Parse(mainTeacher.FormClassID.Substring(0, 2));
UpdateConductView updateConduct = new UpdateConductView(selectedStudentID, grade);
OverlayForm _ = new OverlayForm(this.Home, updateConduct);
updateConduct.FormClosed += (s, ev) =>
{
if (updateConduct.doneSet)
{
Snackbar.MakeSnackbar(this.Home, string.Format("Đã cập nhật hạnh kiểm thành công cho học sinh {0} ({1})", studentName, selectedStudentID), "OK");
Fetch();
}
};
updateConduct.Show();
}
private void OnAddFault(object sender, EventArgs e)
{
string selectedStudentID = listviewStudentInClass.SelectedItems[0].SubItems[1].Text;
OnePunishmentView addFault = new OnePunishmentView(selectedStudentID, OnePunishmentView.Mode.Add, OnePunishmentView.OpenMode.FaultOnly);
OverlayForm _ = new OverlayForm(this.Home, addFault);
addFault.Show();
}
private void OnViewDetailScoreboard(object sender, EventArgs e)
{
string selectedStudentID = listviewStudentInClass.SelectedItems[0].SubItems[1].Text;
string studentName = listviewStudentInClass.SelectedItems[0].SubItems[2].Text;
int grade = int.Parse(mainTeacher.FormClassID.Substring(0, 2));
DetailScoreboardView detailScoreboard = new DetailScoreboardView(selectedStudentID, studentName, grade);
OverlayForm _ = new OverlayForm(this.Home, detailScoreboard);
detailScoreboard.Show();
}
}
}
|
using System;
using System.Net;
using System.Windows.Media;
using WMagic.Cache;
namespace WMagic.Image.Policy
{
/// <remarks>
/// -----------------------------------------------------------------------
/// 部件名:SyncLoadImage
/// 工程名:WMagic
/// 版权:CopyRight (c) 2013
/// 创建人:ZFL
/// 描述:同步载图类
/// 创建日期:2013.05.27
/// 修改人:
/// 修改日期:
/// -----------------------------------------------------------------------
/// </remarks>
/// <summary>
/// 同步载图类
/// </summary>
public class SyncLoadImage
{
#region 变量
// 数据源
private String path;
// 数据缓存
private MagicCache cache;
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="path">数据源</param>
/// <param name="cache">数据缓存</param>
public SyncLoadImage(String path, MagicCache cache)
{
this.path = path;
this.cache = cache;
}
#endregion
#region 函数方法
/// <summary>
/// 获取图像数据
/// </summary>
public ImageSource DownLoad()
{
if (this.cache.IsExist(this.path))
{
return ImageUtils.Format(this.cache.Fetch(this.path) as byte[]);
}
else
{
using (WebClient http = new WebClient())
{
byte[] data = http.DownloadData(new Uri(this.path));
if (!MatchUtils.IsEmpty(data) && this.cache.Store(this.path, data))
{
return ImageUtils.Format(data);
}
}
}
return null;
}
#endregion
}
} |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.DebugAdapter;
namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class DebugEvaluateHandler : IEvaluateHandler
{
private readonly ILogger _logger;
private readonly PowerShellContextService _powerShellContextService;
private readonly DebugService _debugService;
public DebugEvaluateHandler(
ILoggerFactory factory,
PowerShellContextService powerShellContextService,
DebugService debugService)
{
_logger = factory.CreateLogger<DebugEvaluateHandler>();
_powerShellContextService = powerShellContextService;
_debugService = debugService;
}
public async Task<EvaluateResponseBody> Handle(EvaluateRequestArguments request, CancellationToken cancellationToken)
{
string valueString = "";
int variableId = 0;
bool isFromRepl =
string.Equals(
request.Context,
"repl",
StringComparison.CurrentCultureIgnoreCase);
if (isFromRepl)
{
var notAwaited =
_powerShellContextService
.ExecuteScriptStringAsync(request.Expression, false, true)
.ConfigureAwait(false);
}
else
{
VariableDetailsBase result = null;
// VS Code might send this request after the debugger
// has been resumed, return an empty result in this case.
if (_powerShellContextService.IsDebuggerStopped)
{
// First check to see if the watch expression refers to a naked variable reference.
result =
_debugService.GetVariableFromExpression(request.Expression, request.FrameId);
// If the expression is not a naked variable reference, then evaluate the expression.
if (result == null)
{
result =
await _debugService.EvaluateExpressionAsync(
request.Expression,
request.FrameId,
isFromRepl);
}
}
if (result != null)
{
valueString = result.ValueString;
variableId =
result.IsExpandable ?
result.Id : 0;
}
}
return new EvaluateResponseBody
{
Result = valueString,
VariablesReference = variableId
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Kinect;
namespace GestureRecognizer
{
public class GestureRecognitionEngine
{
public event EventHandler<GestureEventArgs> GestureRecognized;
public event EventHandler<GestureEventArgs> GestureNotRecognized;
// public GestureType GestureType;
// class exercise 4
public List<GestureType> GestureTypes = new List<GestureType>();
public void StartRecognize(Skeleton skeleton)
{
foreach (GestureType gt in GestureTypes) // for class exercise 4
{
switch (gt)
//switch (this.GestureType) // for class exercise 4
{
case GestureType.HandsClapping:
this.MatchHandClappingGesture(skeleton);
break;
case GestureType.HandsRaisedAboveHead:
MatchHandsRaisedAboveHeadGesture(skeleton);
break;
case GestureType.HandsAtChestLevel:
MatchHandsAtChestLevel(skeleton);
break;
default:
break;
}
}
}
private float GetJointDistance(Joint j1, Joint j2)
{
float distanceX = j1.Position.X - j2.Position.X;
float distanceY = j1.Position.Y - j2.Position.Y;
float distanceZ = j1.Position.Z - j2.Position.Z;
return (float)Math.Sqrt(distanceX * distanceX
+ distanceY * distanceY + distanceZ * distanceZ);
}
private float prev_dist = 0.0f;
private float threshold = 0.2f;
private void MatchHandClappingGesture(Skeleton skeleton)
{
if (skeleton == null) return;
// class exercise 1
Joint hr = skeleton.Joints[JointType.HandRight];
Joint hl = skeleton.Joints[JointType.HandLeft];
if (hr.TrackingState != JointTrackingState.NotTracked && hl.TrackingState != JointTrackingState.NotTracked)
{
float curr_dist = GetJointDistance(hr, hl);
if (curr_dist < threshold && prev_dist > threshold)
{
if (GestureRecognized != null) // already existing some subscriber?
{
this.GestureRecognized(this, new GestureEventArgs(RecognitionResult.Success));
}
}
prev_dist = curr_dist;
}
}
// class exercise 3
private SkeletonPoint prev_posi_lh = new SkeletonPoint();
private SkeletonPoint prev_posi_rh = new SkeletonPoint();
private float hands_up_threshold = 0.1f;
private void MatchHandsRaisedAboveHeadGesture(Skeleton skeleton)
{
if (skeleton == null) return;
Joint handL = skeleton.Joints[JointType.HandLeft];
Joint handR = skeleton.Joints[JointType.HandRight];
Joint head = skeleton.Joints[JointType.Head];
if (handL.TrackingState != JointTrackingState.NotTracked &&
handR.TrackingState != JointTrackingState.NotTracked &&
head.TrackingState != JointTrackingState.NotTracked)
{
SkeletonPoint curr_posi_lh = handL.Position;
SkeletonPoint curr_posi_rh = handR.Position;
// requires both hands move from "below head" to "above head"
if ((prev_posi_lh.Y < head.Position.Y && curr_posi_lh.Y > head.Position.Y &&
curr_posi_rh.Y > head.Position.Y - hands_up_threshold && curr_posi_rh.Y < head.Position.Y + hands_up_threshold) ||
(prev_posi_rh.Y < head.Position.Y && curr_posi_rh.Y > head.Position.Y &&
curr_posi_lh.Y > head.Position.Y - hands_up_threshold && curr_posi_lh.Y < head.Position.Y + hands_up_threshold))
{
if (this.GestureRecognized != null)
this.GestureRecognized(this, new GestureEventArgs(RecognitionResult.Success));
}
prev_posi_lh = handL.Position;
prev_posi_rh = handR.Position;
}
}
//Both hands at chest level
private void MatchHandsAtChestLevel(Skeleton skeleton)
{
if (skeleton == null) return;
// class exercise 1
Joint hr = skeleton.Joints[JointType.HandRight];
Joint hl = skeleton.Joints[JointType.HandLeft];
if (hr.TrackingState != JointTrackingState.NotTracked && hl.TrackingState != JointTrackingState.NotTracked)
{
if (hr.Position.Y < skeleton.Joints[JointType.Head].Position.Y && hl.Position.Y < skeleton.Joints[JointType.Head].Position.Y &&
hr.Position.Y > skeleton.Joints[JointType.Spine].Position.Y && hl.Position.Y > skeleton.Joints[JointType.Spine].Position.Y)
{
if (GestureRecognized != null) // already existing some subscriber?
{
this.GestureRecognized(this, new GestureEventArgs(RecognitionResult.Success));
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
//using System.Reflection; //Descomentar esto me permitira abreviar en la linea 11 y 22, Poniendo solamemente
//Assembly, en vez de System.Reflection.Assembly
namespace Gestion {
public class FormData {
public int CatId;
public string FormName;
public string FormTypeName;
public FormData(int _catId, string _formName, string _formTypeName) {
CatId = _catId;
FormName = _formName;
FormTypeName = _formTypeName;
}
}
public class Get_Forms {
public List<Type> Formlist = new List<Type>();
public Get_Forms() {
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly();
Type[] Types = myAssembly.GetTypes();
Formlist.Clear();
foreach (Type myType in Types) {
if (myType.BaseType == null)
continue;
if (myType.BaseType.FullName == "System.Windows.Forms.Form")
Formlist.Add(myType);
}
}
public Get_Forms(string target) {
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly();
Type[] Types = myAssembly.GetTypes();
Formlist.Clear();
foreach (Type myType in Types) {
if (myType.BaseType == null)
continue;
if (myType.BaseType.FullName == target)
Formlist.Add(myType);
}
}
public virtual List<string> Exceptions() {
List<string> exceptions = new List<string>();
exceptions.Add("MainForm");
exceptions.Add("EnClasesForm");
exceptions.Add("OwnForm");
exceptions.Add("MainForm");
return exceptions;
}
public bool Exceptions_check(Type formToCheck) {
foreach (string name in Exceptions()) {
if (formToCheck.Name == name)
return true;
}
return false;
}
}
}
|
// <copyright file="InvestmentDataTest.cs" company="Hewlett-Packard">Copyright © Hewlett-Packard 2011</copyright>
using System;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Server.UserData;
namespace Server.UserData
{
[TestClass]
[PexClass(typeof(InvestmentData))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
public partial class InvestmentDataTest
{
[PexMethod]
public string StockGroupGet([PexAssumeUnderTest]InvestmentData target)
{
string result = target.StockGroup;
return result;
// TODO: add assertions to method InvestmentDataTest.StockGroupGet(InvestmentData)
}
[PexMethod]
public void InvestmentPercentageSet([PexAssumeUnderTest]InvestmentData target, uint value)
{
target.InvestmentPercentage = value;
// TODO: add assertions to method InvestmentDataTest.InvestmentPercentageSet(InvestmentData, UInt32)
}
[PexMethod]
public uint InvestmentPercentageGet([PexAssumeUnderTest]InvestmentData target)
{
uint result = target.InvestmentPercentage;
return result;
// TODO: add assertions to method InvestmentDataTest.InvestmentPercentageGet(InvestmentData)
}
[PexMethod]
public InvestmentData Constructor(string stockGroup, uint investmentPercentage)
{
InvestmentData target = new InvestmentData(stockGroup, investmentPercentage);
return target;
// TODO: add assertions to method InvestmentDataTest.Constructor(String, UInt32)
}
}
}
|
using System;
using Logic.Resource;
namespace Logic.TechnologyClasses {
public class TechnologyResearcher {
public int ResearchProgress { get; private set; }
public int ResearchDuration { get; }
public IComparableResources CostPerTurn { get; }
private readonly Technology technologyBeingResearched;
public event EventHandler<ResearchCompletedEventArgs> ResearchCompleted;
public TechnologyResearcher(Technology tecnology, IBasicResources costPerTurn, int researchDuration) {
if (costPerTurn == null) {
throw new ArgumentNullException(nameof(costPerTurn));
}
if(tecnology == null) {
throw new ArgumentNullException(nameof(tecnology));
}
this.technologyBeingResearched = tecnology;
this.CostPerTurn = new ReadOnlyResources(costPerTurn);
this.ResearchDuration = researchDuration;
}
public void OneTurnProgress(IMutableResources from) {
if (from == null) {
throw new ArgumentNullException(nameof(from));
}
if (from.CanSubtract(this.CostPerTurn)) {
from.Subtract(this.CostPerTurn);
this.ResearchProgress++;
}
if(this.ResearchProgress == this.ResearchDuration) {
OnResearchCompleted();
}
}
private void OnResearchCompleted() {
ResearchCompleted?.Invoke(this, new ResearchCompletedEventArgs());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ChatHistoryLib.Contracts;
namespace ChatHistoryLib.Implementation
{
public class HistoryDataStatefulManager : IHistoryDataManager
{
private readonly IHistoryDataProvider _dataProvider;
public HistoryDataStatefulManager(IHistoryDataProvider dataProvider)
{
_dataProvider = dataProvider;
try
{
dataProvider.Connect();
}
catch (FailedToConnectException)
{
Console.WriteLine("Failed To connect to Data Provider");
throw;
}
}
public IQueryable<HistoryItem> DataSet => _dataProvider.RetrieveData();
public IQueryable<(String TimePoint, List<string>)> GetActionsSummeryHourlyPerDay(DateTime day)
{
return this.DataSet
.Where(x => x.TimeStamp.ToShortDateString() == day.ToShortDateString())
.GroupBy(x => x.TimeStamp.ToString("hh a"))
.OrderBy(x => x.Key)
.Select(x => BeautifyActions(x, false));
}
public IQueryable<(string TimePoint, List<string>)> GetActionsSummeryMinuteByMinutePerDay(DateTime day)
{
return this.DataSet
.Where(x => x.TimeStamp.ToShortDateString() == day.ToShortDateString())
.GroupBy(x => x.TimeStamp.ToShortTimeString())
.OrderBy(x => x.Key)
.Select(x => BeautifyActions(x, true));
}
private (String TimePoint, List<string>) BeautifyActions(IGrouping<string, HistoryItem> historyItems,
bool expandActions)
{
var resultsList = new List<string>();
if (expandActions)
{
foreach (var item in historyItems)
{
switch (item.Type)
{
case ActionType.EnterRoom:
resultsList.Add($"{item.FromUserName} enters the room");
break;
case ActionType.LeaveRoom:
resultsList.Add($"{item.FromUserName} leaves");
break;
case ActionType.Comment:
resultsList.Add($"{item.FromUserName} comments: {item.Message}");
break;
case ActionType.HighFive:
resultsList.Add($"{item.FromUserName} high-fives to {item.ToUserName}");
break;
default:
throw new ArgumentOutOfRangeException(
$"{nameof(historyItems)}Contains undefind action type");
}
}
return new(historyItems.Key, resultsList);
}
else
{
var groupedActionsList = historyItems
.GroupBy(x => x.Type)
.Select(x => new
{
action = x.Key, items = x.GroupBy(p => p.FromUserName)
.ToList()
});
groupedActionsList.ToList().ForEach(z =>
{
switch (z.action)
{
case ActionType.EnterRoom:
// It's meant here to treat the same person with multiple actions as one action for convince
resultsList.Add($"{z.items.Count} entered");
break;
case ActionType.LeaveRoom:
// It's meant here to treat the same person with multiple actions as one action for convince
resultsList.Add($"{z.items.Count} left");
break;
case ActionType.Comment:
resultsList.Add($"{z.items.Sum(i => i.Count())} comments");
break;
case ActionType.HighFive:
resultsList
.Add($"{z.items.Count} high-five {z.items.Sum(i => i.GroupBy(t=>t.ToUserName).ToList().Count)}");
break;
default:
throw new ArgumentOutOfRangeException(
$"{nameof(historyItems)}Contains undefind action type");
}
});
}
return new(historyItems.Key, resultsList);
}
}
} |
using UnityEngine;
using System.Collections;
public class LevelManager : MonoBehaviour {
public Animator transitionOut;
void Start()
{
transitionOut = GameObject.Find("TransitionOUT").GetComponent<Animator>();
}
public void LoadLevel(string name){
Invoke("TransitionOut", 1f);
Application.LoadLevel(name);
}
public void QuitRequest(){
Debug.Log ("Quit requested");
Application.Quit ();
}
void TransitionOut()
{
transitionOut.enabled = true;
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class Initializer : MonoBehaviour {
public GameObject Vehicle;
public GameObject Light;
public enum simState
{
lightSetup,
vehicleSetup,
simulating
}
public simState state;
public List<Transform> lights = new List<Transform>();
public List<Braitenberg> vehicles = new List<Braitenberg>();
public string k00 = "0";
public string k01 = "0";
public string k10 = "0";
public string k11 = "0";
public string theta = "0";
// Update is called once per frame
void Update () {
switch(state)
{
case simState.lightSetup:
if(Input.GetMouseButtonDown(0) && GUIUtility.hotControl == 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.CompareTag("Floor"))
{
GameObject newLight = Instantiate(Light,new Vector3(hit.point.x, 4, hit.point.z), Quaternion.identity) as GameObject;
lights.Add(newLight.transform);
}
}
}
break;
case simState.vehicleSetup:
if (Input.GetMouseButtonDown(0) && GUIUtility.hotControl == 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.CompareTag("Floor"))
{
GameObject newVehicle = Instantiate(Vehicle, new Vector3(hit.point.x, 0.1f, hit.point.z), Quaternion.Euler(0, float.Parse(theta), 0) * Quaternion.identity) as GameObject;
vehicles.Add(newVehicle.GetComponent<Braitenberg>());
vehicles[vehicles.Count-1].k.K11 = float.Parse(k00);
vehicles[vehicles.Count-1].k.K12 = float.Parse(k01);
vehicles[vehicles.Count-1].k.K21 = float.Parse(k10);
vehicles[vehicles.Count-1].k.K22 = float.Parse(k11);
}
}
}
break;
}
}
void OnGUI() {
switch (state)
{
case simState.lightSetup:
if (GUI.Button(new Rect(20, 80, 80, 20), "Next"))
{
state = simState.vehicleSetup;
}
break;
case simState.vehicleSetup:
if (GUI.Button(new Rect(20, 80, 80, 20), "Start"))
{
state = simState.simulating;
foreach(Braitenberg v in vehicles)
{
v.lights = lights;
v.simRunning = true;
}
}
GUILayout.BeginHorizontal("");
GUILayout.Label("k00");
k00 = GUILayout.TextField(k00, GUILayout.Width(40));
GUILayout.Label("k01");
k01 = GUILayout.TextField(k01, GUILayout.Width(40));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal("");
GUILayout.Label("k10");
k10 = GUILayout.TextField(k10, GUILayout.Width(40));
GUILayout.Label("k11");
k11 = GUILayout.TextField(k11, GUILayout.Width(40));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal("");
GUILayout.Label("theta");
theta = GUILayout.TextField(theta, GUILayout.Width(40));
GUILayout.EndHorizontal();
break;
case simState.simulating:
if (GUI.Button(new Rect(20, 80, 80, 20), "New Sim"))
{
foreach(Braitenberg v in vehicles)
{
Destroy(v.gameObject);
}
foreach(Transform l in lights)
{
Destroy(l.gameObject);
}
vehicles.Clear();
lights.Clear();
state = simState.lightSetup;
}
break;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using AbcPlaza.Api;
using AbcPlaza.Api.Request;
using AbcPlaza.Api.Response;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
namespace AbcPlaza.C_Sharp
{
[Activity(Label = "DemoActivity")]
public class DemoActivity : Activity
{
Button button;
protected override void OnCreate(Bundle bundle)
{
try
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.demo);
button = FindViewById<Button>(Resource.Id.btn_demo);
button.Click += async delegate
{
var model = new RestApi();
var request = new DemoRequest();
request.Name = "morpheus";
request.Job = "leader";
HttpResponseMessage message = await model.PostAsync("https://reqres.in/api/users", request);
if (message.IsSuccessStatusCode)
{
var content = await message.Content.ReadAsStringAsync();
var info = JsonConvert.DeserializeObject<DemoResponse>(content);
}
else
{
Log.Error("Some errors"," errors");
}
};
}
catch (Exception ex)
{
Log.Error("Error", ex.Message);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Controllers
{
public class UploadController : Controller
{
private IHostingEnvironment evn;
public UploadController(IHostingEnvironment evn)
{
this.evn = evn;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> CKImage()
{
string callback = Request.Query["CKEditorFuncNum"];
var upimage = Request.Form.Files[0];
string tpl = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(\"{1}\", \"{0}\", \"{2}\");</script>";
if (upimage == null)
return Json(new { uploaded = false, url = "" });
var data = Request.Form.Files["upload"];
string filePath = evn.WebRootPath + @"\UpLoad\Images";
string imgname = DateTime.Now.ToString("yyyyMMdd") + "\\" + Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(upimage.FileName);
string path = Path.Combine(filePath, imgname);
string strDir = Path.GetDirectoryName(path);
try
{
if (!Directory.Exists(strDir))
Directory.CreateDirectory(strDir);
if (data != null)
{
await Task.Run(() =>
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
data.CopyTo(fs);
}
});
}
}
catch (Exception ex)
{
return Json(new { uploaded = false, url = "" });
}
return Json(new { uploaded = true, url = @"\UpLoad\Images\" + imgname });
}
public IActionResult File()
{
return null;
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Particle
{
class Scene
{
#region Properties
public static float PixelPerMeter = 100f;
protected Emitter emitter;
protected StringBuilder DebugInfo;
protected SpriteFont font;
#endregion
#region Constructor
public Scene()
{
Emitter.EmitterBehaviour emitterType = new Emitter.EmitterBehaviour();
emitterType.EmitterType = Emitter.EType.Circular;
emitterType.ParticleType = Emitter.PType.Water;
emitter = new Emitter(emitterType, new Vector2(512, 100), 100, 15f);
DebugInfo = new StringBuilder();
}
#endregion
#region Methods
public void Initialize()
{
emitter.Initialize();
}
public void LoadContent(ContentManager Content)
{
emitter.LoadContent(Content);
font = Content.Load<SpriteFont>("font");
}
public void Update(GameTime gameTime)
{
emitter.Update(gameTime);
DebugInfo.Clear();
DebugInfo.AppendLine(emitter.ParticleCount.ToString());
}
public void Draw(SpriteBatch spriteBatch, GraphicsDevice Graphics)
{
Graphics.Clear(Color.Gray);
spriteBatch.Begin();
emitter.Draw(spriteBatch);
spriteBatch.DrawString(font, DebugInfo, new Vector2(10, 10), Color.Black);
spriteBatch.End();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DogDoors
{
public class Bark
{
private string _sound;
public Bark(string sound)
{
_sound = sound;
}
public string Sound
{
get
{
return _sound;
}
}
public override bool Equals(object bark)
{
if (bark is Bark)
{
Bark otherBark = (Bark)bark;
if (_sound.Equals(otherBark.Sound, StringComparison.CurrentCultureIgnoreCase))
{
return true;
}
}
return false;
}
}
} |
namespace Columns.Enums
{
public class ColumnEnums
{
public enum ColumnTypes
{
Double,
String
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grupo5_Hotel.Entidades.Excepciones
{
public class ClienteExistenteException : Exception
{
public ClienteExistenteException(int id) : base("Ya existe el cliente con id " + id) { }
}
}
|
using System;
using Controllers;
using Cysharp.Threading.Tasks;
using UnityEngine;
using Zenject;
namespace Models.BuildingModels
{
public abstract class Mine : Building
{
[SerializeField] protected MineData data;
[Inject] private ResourceWallet wallet;
private MiningState currentState;
public override void OnBuild()
{
MiningCycle();
}
protected virtual async void MiningCycle()
{
while (true)
{
currentState = MiningState.Mining;
await UniTask.Delay(TimeSpan.FromSeconds(data.MiningTimeInSeconds));
currentState = MiningState.Ready;
var marker = Instantiate(data.ResourcePrefab, transform.position + Vector3.up, Quaternion.identity);
await UniTask.WaitWhile(() => currentState == MiningState.Ready);
Destroy(marker);
}
}
private void OnMouseDown()
{
if(currentState != MiningState.Ready)
return;
var reminder = wallet.TryAddResource(data.Resource, data.ResourceAmount);
if (reminder == 0)
currentState = MiningState.Mining;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SubSonic.Extensions;
namespace Pes.Core
{
public partial class T_Test_Result
{
#region Insert, Update, Delete
/// <summary>
/// INSERT Test_Result
/// </summary>
/// <param name="ob">Test_Result</param>
/// <returns>1 success or -1 fail</returns>
public static int Insert(Object ob)
{
try
{
Add(ob as T_Test_Result);
return 1;
}
catch
{
return -1;
}
}
/// <summary>
/// Update TEST_RESULTS
/// </summary>
/// <param name="ob">TEST_RESULTS</param>
/// <returns>1 success or -1 fail</returns>
public static int Update(object ob)
{
try
{
Update(ob as T_Test_Result);
return 1;
}
catch
{
return -1;
}
}
/// <summary>
/// Delete TEST_RESULTS
/// </summary>
/// <param name="ob">TEST_RESULTS</param>
/// <returns>1 success or -1 fail</returns>
public static int Delete(Object ob)
{
try
{
Delete(ob as T_Test_Result);
return 1;
}
catch
{
return -1;
}
}
#endregion
#region Ultility
/// <summary>
/// GetObject Test_Result
/// </summary>
/// <returns>list all TEST_RESULTS</returns>
public IQueryable<T_Test_Result> GetObject()
{
try
{
return T_Test_Result.All();
}
catch
{
return null;
}
}
/// <summary>
/// GetTestResult
/// </summary>
/// <param name="id">TestResultID</param>
/// <returns>TEST_RESULTS</returns>
public T_Test_Result GetTest_Result(int id)
{
return (from m in GetObject() where m.TestResultID == id select m).FirstOrDefault();
}
#endregion
}
}
|
using Ljc.Com.NewsService.Entity;
using LJC.FrameWork.Data.EntityDataBase;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TX.Framework.WindowUI.Controls;
using TX.Framework.WindowUI.Forms;
namespace Ljc.Com.CjzfNews.UI.SubForm
{
public partial class NewsClassManager : TX.Framework.WindowUI.Forms.FormInfoListEntity
{
public NewsClassManager()
{
InitializeComponent();
this.ShowInTaskbar = false;
this.toolBar.Add += toolBar_Add;
this.toolBar.Edit += toolBar_Edit;
this.toolBar.Refresh += toolBar_Refresh;
this.toolBar.Delete += toolBar_Delete;
this.tlvList.MultiSelect = false;
this.tlvList.Columns.Add(new TX.Framework.WindowUI.Controls.TemplateColumnHeader
{
Template = "$this.ClassName",
Text="类名",
Width=150
});
this.tlvList.Columns.Add(new TX.Framework.WindowUI.Controls.TemplateColumnHeader
{
Template = "$this.Id",
Text = "类编号",
TextAlign = HorizontalAlignment.Center
});
this.tlvList.Columns.Add(new TX.Framework.WindowUI.Controls.TemplateColumnHeader
{
Template = "$this.Isvalid",
Text = "是否有效",
});
}
void toolBar_Delete(object sender, EventArgs e)
{
var selecteditems = this.tlvList.SelectedItems;
if (selecteditems == null)
{
return;
}
if (selecteditems[0].Tag is NewsClassEntity)
{
var delclassname=((NewsClassEntity)selecteditems[0].Tag).ClassName;
if(TXMessageBoxExtensions.Question("要删除 "+delclassname)==DialogResult.OK)
{
try
{
BigEntityTableEngine.LocalEngine.Delete<NewsClassEntity>("NewsClassEntity", delclassname);
BindData();
}
catch (Exception ex)
{
TXMessageBoxExtensions.Error(ex.Message);
}
}
}
}
void toolBar_Refresh(object sender, EventArgs e)
{
BindData();
}
void toolBar_Edit(object sender, EventArgs e)
{
var selecteditems = this.tlvList.SelectedItems;
if (selecteditems.Count==0)
{
return;
}
if (selecteditems[0].Tag is NewsClassEntity)
{
if (new AddNewsClassSubForm(((NewsClassEntity)selecteditems[0].Tag).ClassName).ShowDialog() == DialogResult.OK)
{
BindData();
}
}
}
void toolBar_Add(object sender, EventArgs e)
{
if(new AddNewsClassSubForm().ShowDialog()==DialogResult.OK)
{
BindData();
}
}
protected void BindData()
{
var newsclasslist = LJC.FrameWork.Data.EntityDataBase.BigEntityTableEngine.LocalEngine.Find<NewsClassEntity>("NewsClassEntity", p => true).ToList();
this.tlvList.DataSource = newsclasslist;
pager.Total = newsclasslist.Count;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
BindData();
}
private void toolBar_Load(object sender, EventArgs e)
{
}
}
}
|
using Core.DataAccess;
using Entities.Concrete;
namespace DataAccess.Abstract
{
public interface ICityDal:IEntityRepository<City>
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Labrat
{
class Program
{
static void Main(string[] args)
{
//Labrat.Lab01.teht1();
//Lab01.teht2();
// Lab01.teht3();
//Lab01.teht4();
//Lab01.teht5();
// Lab01.teht6();
//Lab01.teht7();
//Lab01.teht8();
// Lab01.teht9();
//Lab01.teht10();
//Lab01.teht11();
//Lab01.teht12();
//Lab01.teht13();
//Lab01.teht14();
//Lab01.teht15();
//Lab01.teht16();
//Lab01.teht17();
//Lab01.teht18();
// Lab01.teht19();
//Lab02_teht1.pytty_päälle();
//pesukone();
//tv_päälle();
PrintData();
}
static void pesukone()
{
Lab02_teht2 pesukone = new Lab02_teht2();
pesukone.Päällä_teht2 = true;
pesukone.Linkous = true;
pesukone.Loppu = false;
Console.WriteLine("Onko pesukone päällä: {0}", pesukone.Päällä_teht2);
Console.WriteLine("Linkous? : {0}", pesukone.Linkous);
Console.WriteLine("Veden lämpötila: {0}", pesukone.veden_lämpötila);
Console.WriteLine("Valmista? : {0}", pesukone.Loppu);
}
static void tv_päälle()
{
televisio televisio = new televisio();
televisio.Päällä = true;
televisio.Kanava = 4;
televisio.Volume = 100;
Console.WriteLine("Onko tv päällä: {0}", televisio.Päällä);
Console.WriteLine("Kanava: {0}", televisio.Kanava);
Console.WriteLine("Bassot jytkyy, Äänenvoimakkuus: {0}", televisio.Volume);
}
static void PrintData()
{
Vehicle vehicle = new Vehicle();
vehicle.Name = "Lamborghini Centenario";
vehicle.Speed = 300;
vehicle.Tyres = 21;
Console.WriteLine("Auton nimi: {0}", vehicle.Name);
Console.WriteLine("Auton nopeus: {0}", vehicle.Speed);
Console.WriteLine("Auton renkaitten tuumat: {0}", vehicle.Tyres);
Console.WriteLine(vehicle.tostring());
}
static void PrintOpiskelijat()
{
Opiskelija opiskelija_1 = new Opiskelija();
Opiskelija opiskelija_2 = new Opiskelija();
Opiskelija opiskelija_3 = new Opiskelija();
Opiskelija opiskelija_4 = new Opiskelija();
Opiskelija opiskelija_5 = new Opiskelija();
opiskelija_1.Nimi = "Pete Tötterström";
opiskelija_2.Nimi = "Jarmo Tötterström";
opiskelija_3.Nimi = "Pekka Tötterström";
opiskelija_4.Nimi = "Mikko Tötterström";
opiskelija_5.Nimi = "Mirva Tötterström";
opiskelija_1.Keskiarvo = 3;
opiskelija_2.Keskiarvo = 1;
opiskelija_3.Keskiarvo = 2;
opiskelija_4.Keskiarvo = 5;
opiskelija_5.Keskiarvo = 4;
opiskelija_1.Opintopisteet = 0;
opiskelija_2.Opintopisteet = 10;
opiskelija_3.Opintopisteet = 20;
opiskelija_4.Opintopisteet = 30;
opiskelija_5.Opintopisteet = 40;
}
}
}
|
using SQLite;
using System;
namespace CapstoneTravelApp.DatabaseTables
{
public class Entertainment_Table
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int EntertainId { get; set; }
[NotNull]
public string EntertainName { get; set; }
public DateTime EntertaninStart { get; set; }
public DateTime EntertainEnd { get; set; }
public string EnterainAddress { get; set; }
public string EntertainPhone { get; set; }
public string EntertainNotes { get; set; }
[NotNull]
public int TripId { get; set; }
public int EntertainNotifications { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using NetPayroll.Guides.Common;
namespace NetPayroll.Guides.Contract.Employ
{
public class GuidesEmploy : GuidesLegal
{
protected readonly Int32 __WeeklyWorkingDays;
protected readonly Int32 __DailyWorkingHours;
protected readonly Int32 __DailyWorkingSeconds;
protected readonly Int32 __WeeklyWorkingSeconds;
protected GuidesEmploy(uint legalYear,
Int32 weeklyWorkingDays, Int32 dailyWorkingHours) : base(legalYear)
{
__WeeklyWorkingDays = weeklyWorkingDays;
__DailyWorkingHours = dailyWorkingHours;
__DailyWorkingSeconds = OperationsEmploy.WorkingSecondsDaily(__DailyWorkingHours);
__WeeklyWorkingSeconds = OperationsEmploy.WorkingSecondsWeekly(__WeeklyWorkingDays, __DailyWorkingHours);
}
public virtual object Clone()
{
GuidesEmploy other = (GuidesEmploy)this.MemberwiseClone();
return other;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Atendimento_V2
{
class ControllerSenhasGuiches
{
//atributos - Classes performadoras
private Guiches listaGuiches;
private Senhas filaSenhas;
public ControllerSenhasGuiches()
{
this.filaSenhas = new Senhas();
this.listaGuiches = new Guiches();
}
public bool gerarSenha()
{
try
{
filaSenhas.gerarSenha();
return true;
}
catch(Exception)
{
return false;
}
}
public List<string> listarSenhas(int id)
{
if(id > 0) return listaGuiches.dadosResumidosGuiche(id);
else return filaSenhas.dadosResumido();
}
public bool adicionarGuiche()
{
try
{
listaGuiches.adicionarGuiche();
return true;
}
catch(Exception)
{
return false;
}
}
public int contarGuiches()
{
return listaGuiches.contarGuiches();
}
public bool guicheExiste(int idGuiche)
{
if (listaGuiches.getGuiche(idGuiche) != null) return true;
else return false;
}
public bool chamarSenhaNoGuiche(int idGuiche)
{
try
{
Guiche guiche = listaGuiches.getGuiche(idGuiche);
guiche.chamarSenha(filaSenhas.getSenha());
return true;
}
catch(Exception)
{
return false;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class RandomMove : MonoBehaviour {
public GameObject robot;
GameObject robotLight;
Vector3 vec;
Vector3 veclight;
int interval;
public int velparameter;
//public Vector4 fieldSize;
public Vector2 Field;
public Vector2 localO;
public bool IsHeigh;
public bool IsLight;
Vector2 rangex;
Vector2 rangez;
float pretime;
// Use this for initialization
void Start ()
{
this.Chenge();
this.interval = 5;
this.rangex = new Vector2(-this.localO.x, this.Field.x - this.localO.x);
this.rangez = new Vector2( - this.Field.y + this.localO.y, this.localO.y);
this.veclight = Vector3.zero;
this.pretime = 0 ;
this.robotLight = this.robot.transform.FindChild("RobotLight").gameObject;
}
// Update is called once per frame
void Update ()
{
float time = Time.realtimeSinceStartup;
if ((int)time % this.interval == 0 && (time - this.pretime) > 1f)
{
this.pretime = time;
this.Chenge();
this.interval = Random.Range(3, 10);
//Debug.Log("Change + " + time);
}
if (!this.IsHeigh) this.vec.y = 0;
if (!this.IsLight) this.veclight = Vector3.zero;
//ロボットの動き
Vector3 pos = this.robot.transform.position + this.vec;
if (pos.x > this.rangex.x && pos.x < this.rangex.y && pos.z > this.rangez.x && pos.z < this.rangez.y)
{
this.robot.transform.position += this.vec;
}
else
{
this.Chenge();
//Debug.Log("change" + pos);
}
//光源の動き
if (this.IsLight)
{
Vector3 lightPos = this.robotLight.transform.position + this.veclight;
if (lightPos.y > 0.5f && lightPos.y < 3)
this.robotLight.transform.position += this.veclight;
else this.Chenge();
}
}
void Chenge()
{
this.vec = new Vector3(Random.Range(-50, 50), Random.Range(-50, 50), Random.Range(-50, 50));
this.vec /= (this.vec.magnitude * this.velparameter);
this.veclight.y = this.vec.y;
}
}
|
/*
* The sequence of triangle numbers is generated by adding the natural numbers.
* So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
*
* 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
*
* Let us list the factors of the first seven triangle numbers:
*
* 1: 1
* 3: 1, 3
* 6: 1, 2, 3, 6
* 10: 1, 2, 5, 10
* 15: 1, 3, 5, 15
* 21: 1, 3, 7, 21
* 28: 1, 2, 4, 7, 14, 28
*
* We can see that 28 is the first triangle number to have over five divisors.
*
* What is the value of the first triangle number to have over five hundred divisors?
*/
int i = 1;
int current = 0;
var factorCount = 0;
do
{
current = current + i++;
factorCount = GetFactors(current).Count();
} while (factorCount <= 500);
Console.WriteLine(current);
private static IEnumerable<int> GetFactors(int n)
{
var factors = new List<int>();
for (int i = 1; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
factors.Add(i);
if (n / i != i)
factors.Add(n / i);
}
}
factors.Sort();
return factors;
}
|
using UnityEngine;
using System.Collections;
using Puppet.Core.Model;
using Puppet;
public class LobbyRowType2 : MonoBehaviour
{
#region Unity Editor
public GameObject lbRoomNumber, lbMoneyStep, lbMoneyMinMax, lbPeopleNumber;
public UISprite divider;
#endregion
public DataLobby data;
public static LobbyRowType2 Create(DataLobby data, UITable parent)
{
GameObject go = GameObject.Instantiate(Resources.Load("Prefabs/Lobby/LobbyRowType2")) as GameObject;
go.transform.parent = parent.transform;
go.transform.localPosition = Vector3.zero;
go.transform.localScale = Vector3.one;
go.name = data.roomId + " - " + data.roomName;
LobbyRowType2 item = go.GetComponent<LobbyRowType2>();
item.SetData(data);
return item;
}
public void SetData(DataLobby data)
{
divider.leftAnchor.Set(gameObject.transform.parent.parent, 0, 0);
divider.rightAnchor.Set(gameObject.transform.parent.parent, 1, 0);
this.data = data;
lbRoomNumber.GetComponent<UILabel>().text = data.roomId.ToString();
double smallBind = data.gameDetails.betting / 2;
double minBind = smallBind * 20;
double maxBind = smallBind * 400;
lbMoneyStep.GetComponent<UILabel>().text = "$" + smallBind + "/" + data.gameDetails.betting;
lbMoneyMinMax.GetComponent<UILabel>().text = "$" + Utility.Convert.ConvertShortcutMoney(minBind) + "/" + Utility.Convert.ConvertShortcutMoney(maxBind);
string numberUser = "0/" + data.gameDetails.numPlayers;
if(data.users != null){
numberUser = data.users.Length + "/" + data.gameDetails.numPlayers;
}
lbPeopleNumber.GetComponent<UILabel>().text = numberUser;
}
void OnClick()
{
GameObject.FindObjectOfType<LobbyScene>().JoinGame(this.data);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portal.repo;
namespace Portal
{
public partial class userDetail : System.Web.UI.Page
{
protected usersRepo usersRepos;
public userDetail()
{
usersRepos = new usersRepo();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userType"] == "government")
{
Response.Redirect("login.aspx");
}
if (!IsPostBack)
{
userDetails();
}
}
protected void saveUser_Profile(object sender, EventArgs e)
{
string user_id = Request.QueryString["user_id"];
if ((!string.IsNullOrEmpty(user_id.Trim())) && (!user_id.Trim().Equals("0")))
{
bool approved = (userApproved.Checked) ? true : false;
//string birthday = txt_birthday.Value;
//string email = txt_email.Value;
//bool fastTrackIsAuto = (fastTrackIsAutoActive.Checked) ? true : false;
//string full_name = txt_fullname.Value;
//string gender = (maleGender.Checked) ? "1" : "0";
//string language = (englishLanguage.Checked) ? "English" : "Farsi";
//string number = txt_number.Value;
//string password = txt_password.Value;
//string receive_email = (activeReceiveEmail.Checked) ? "1" : "0";
//string status = (activeStatus.Checked) ? "1" : "0";
//if ((string.IsNullOrWhiteSpace(birthday)) ||
// (string.IsNullOrWhiteSpace(email)) ||
// (string.IsNullOrWhiteSpace(full_name)) ||
// (string.IsNullOrWhiteSpace(gender)) ||
// (string.IsNullOrWhiteSpace(number)) ||
// (string.IsNullOrWhiteSpace(language)) ||
// (string.IsNullOrWhiteSpace(password)) ||
// (string.IsNullOrWhiteSpace(receive_email)) ||
// (string.IsNullOrWhiteSpace(status)))
//{
// ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('All fields required.');", true);
// return;
//}
if (usersRepos.updateUserInfo(new tbl_profile
{
approved = approved,
// birthday = birthday,
//email = email,
//fastTrackIsAuto = fastTrackIsAuto,
//full_name = full_name,
//gender = gender,
//language = language,
//number = number,
//password = password,
//receive_email = receive_email,
//status = status,
user_id = int.Parse(user_id)
}))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Updated Successfully.');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Something went wrong.');", true);
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Something went wrong.');", true);
}
}
protected void resetUser_Profile(object sender, EventArgs e)
{
userDetails();
}
public void userDetails()
{
try
{
string user_id = Request.QueryString["user_id"];
if ((!string.IsNullOrEmpty(user_id.Trim())) && (!user_id.Trim().Equals("0")))
{
var data = usersRepos.getUserDetail(int.Parse(user_id));
txt_email.Value = data.email;
txt_fullname.Value = data.full_name;
txt_number.Value = data.number;
txt_password.Value = data.password;
txt_email.Disabled = true;
txt_fullname.Disabled = true;
txt_number.Disabled = true;
txt_password.Disabled = true;
//txt_birthday.Value = string.IsNullOrWhiteSpace(data.birthday) ? "" : data.birthday;
//if (!string.IsNullOrWhiteSpace(data.gender))
//{
// if (data.gender.ToLower().Equals("male") || data.gender.Equals("1"))
// {
// maleGender.Checked = true;
// femaleGender.Checked = false;
// }
// else if (data.gender.ToLower().Equals("female") || data.gender.Equals("0"))
// {
// maleGender.Checked = false;
// femaleGender.Checked = true;
// }
//}
//if (!string.IsNullOrWhiteSpace(data.language))
//{
// if (data.language.ToLower().Equals("english"))
// {
// englishLanguage.Checked = true;
// farsiLanguage.Checked = false;
// }
// else if (data.language.ToLower().Equals("farsi"))
// {
// englishLanguage.Checked = false;
// farsiLanguage.Checked = true;
// }
//}
//if (!string.IsNullOrWhiteSpace(data.receive_email))
//{
// if (data.receive_email.Equals("1"))
// {
// activeReceiveEmail.Checked = true;
// inactiveReceiveEmail.Checked = false;
// }
// else if (data.receive_email.Equals("0"))
// {
// activeReceiveEmail.Checked = false;
// inactiveReceiveEmail.Checked = true;
// }
//}
//if (data.status.Equals("Active"))
//{
// activeStatus.Checked = true;
// inactiveStatus.Checked = false;
//}
//else if (data.status.Equals("InActive"))
//{
// activeStatus.Checked = false;
// inactiveStatus.Checked = true;
//}
if (data.approved == true)
{
userApproved.Checked = true;
userNotApproved.Checked = false;
}
else if (data.approved == false)
{
userApproved.Checked = false;
userNotApproved.Checked = true;
}
//if (data.fastTrackIsAuto == true)
//{
// fastTrackIsAutoActive.Checked = true;
// fastTrackIsAutoNotActive.Checked = false;
//}
//else if (data.fastTrackIsAuto == false)
//{
// fastTrackIsAutoActive.Checked = false;
// fastTrackIsAutoNotActive.Checked = true;
//}
}
else
{
Response.Redirect("users.aspx");
}
}
catch (Exception)
{
Response.Redirect("users.aspx");
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
//MANY serialize fields
[Header("Gameplay")]
[SerializeField]
private int scoreToWin;
[Header("Round/Flow Management")]
[SerializeField]
private float startGameDelay;
[SerializeField]
private float scoreTheatricsDelay;
[SerializeField]
private float scoreTickDelay;
[SerializeField]
private float endGameDelay;
[SerializeField]
private float flashSpeed;
[SerializeField]
private int numberOfScoreFlashes = 3;
[Header("UI")]
[SerializeField]
private Text redTeamText;
[SerializeField]
private Text blueTeamText;
[SerializeField]
private Text centerColonText;
[SerializeField]
private Text fullMessageText;
[Header("Ball and Scoring")]
[SerializeField]
private Transform ballSpawnLocation;
[SerializeField]
private Rigidbody ballPrefab;
private float launchForce = 30;
[Header("Screenshake")]
[SerializeField]
private CameraShake cameraShake;
[SerializeField]
private float shakeDuration;
//Gameplay variables
private int team1Score; //red team
private int team2Score; //blue team
private bool canScore;
private bool gameHasEnded;
private AudioSource source;
public int Team1Score //red team
{
get { return team1Score; }
set
{
if (canScore)
{
team1Score = value;
StartCoroutine(ScoreTheatricsCoroutine());
}
}
}
public int Team2Score //blue team
{
get { return team2Score; }
set
{
if (canScore)
{
team2Score = value;
StartCoroutine(ScoreTheatricsCoroutine());
}
}
}
//coroutine storage
private WaitForSeconds startGameWaitCoroutine;
// Use this for initialization
void Start ()
{
source = GetComponent<AudioSource>();
startGameWaitCoroutine = new WaitForSeconds(startGameDelay);
StartCoroutine(GameLoopCoroutine());
}
//Keeps track of gamestate and progresses as necessary
private IEnumerator GameLoopCoroutine()
{
yield return StartCoroutine(GameStartCoroutine());
yield return StartCoroutine(GamePlayingCoroutine());
yield return StartCoroutine(GameEndingCoroutine());
}
//UI and game process for the beginning of the game
private IEnumerator GameStartCoroutine()
{
gameHasEnded = false;
//turn off score
disableScoreText();
//run a startup procedure on the message canvas
fullMessageText.text = "First to " + scoreToWin + " wins";
yield return new WaitForSeconds(endGameDelay);
source.Play();
fullMessageText.text = "Ready?";
yield return startGameWaitCoroutine;
source.Play();
fullMessageText.text = "Begin!";
//enable scoring
canScore = true;
//launch the first ball
launchNewBall();
yield return startGameWaitCoroutine;
//initialize all the gamespace canvases
fullMessageText.text = string.Empty;
enableScoreText();
updateScoreText();
}
private IEnumerator GamePlayingCoroutine()
{
while (!gameHasEnded)
{
yield return null;
}
}
private IEnumerator GameEndingCoroutine()
{
//disable scoring
canScore = false;
//flash the final score
for (int i = 0; i < numberOfScoreFlashes; i++)
{
enableScoreText();
yield return new WaitForSeconds(flashSpeed);
disableScoreText();
yield return new WaitForSeconds(flashSpeed);
}
source.Play();
//if the Red Team Won
if (team1Score > team2Score)
{
fullMessageText.text = "Red Team Wins!";
}
//if the Blue Team Won
else
{
fullMessageText.text = "Blue Team Wins!";
}
StartCoroutine(EndSlatePopupCoroutine());
}
private IEnumerator EndSlatePopupCoroutine()
{
yield return new WaitForSeconds(endGameDelay);
fullMessageText.text = "Thank you for Playing";
yield return new WaitForSeconds(endGameDelay);
SceneManager.LoadScene("Menu");
}
//return true if either team has reached the point maximum
private bool MaxScoreReached()
{
return team1Score == scoreToWin || team2Score == scoreToWin;
}
private void disableScoreText()
{
redTeamText.enabled = false;
blueTeamText.enabled = false;
centerColonText.enabled = false;
}
private void enableScoreText()
{
redTeamText.enabled = true;
blueTeamText.enabled = true;
centerColonText.enabled = true;
}
private void launchNewBall()
{
Rigidbody newBall = Instantiate(ballPrefab, ballSpawnLocation);
newBall.velocity = new Vector3(0, 0, -launchForce);
}
//flash score text, then increment
private IEnumerator ScoreTheatricsCoroutine()
{
cameraShake.shakeDuration += shakeDuration;
disableScoreText();
for (int i = 0; i < numberOfScoreFlashes; i++)
{
fullMessageText.text = "Score!";
yield return new WaitForSeconds(flashSpeed);
fullMessageText.text = string.Empty;
yield return new WaitForSeconds(flashSpeed);
}
enableScoreText();
if (team1Score == scoreToWin || team2Score == scoreToWin)
{
yield return new WaitForSeconds(scoreTickDelay);
updateScoreText();
gameHasEnded = true;
}
else
{
launchNewBall();
yield return new WaitForSeconds(scoreTickDelay);
updateScoreText();
}
}
private void updateScoreText()
{
source.Play();
//set team1Score (red team)
if (team1Score < 10)
redTeamText.text = "0" + team1Score;
else
redTeamText.text = Convert.ToString(team1Score);
//set team2Score (blue team)
if (team2Score < 10)
blueTeamText.text = "0" + team2Score;
else
blueTeamText.text = Convert.ToString(team2Score);
}
}
|
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 PracticaForm13_11
{
public partial class FormDatos : Form
{
public FormDatos()
{
InitializeComponent();
}
public void ActualizarNombre(string n)
{
this.label1.Text = n;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using RTI;
namespace RTI_UnitTests
{
public class ReplacePressureVerticalBeamTests
{
/// <summary>
/// Ensemble 1.
/// </summary>
RTI.DataSet.Ensemble ensemble1;
[SetUp]
public void Setup()
{
// Create the ensemble
// 4 Beams, 5 Bins
ensemble1 = EnsembleHelper.GenerateEnsemble(5, 4, true);
ensemble1.EnsembleData.EnsembleNumber = 12;
ensemble1.AncillaryData.Heading = 10.2f;
ensemble1.AncillaryData.TransducerDepth = 5.5f;
}
/// <summary>
/// Not the correct subsystem type.
/// </summary>
[Test]
public void TestReplaceFailNotCorrectSS()
{
bool result = RTI.ScreenData.ReplacePressureVerticalBeam.Replace(ref ensemble1);
Assert.AreEqual(10.2f, ensemble1.AncillaryData.Heading, 0.001);
Assert.AreEqual(5.5f, ensemble1.AncillaryData.TransducerDepth, 0.001);
Assert.AreEqual(true, result);
}
/// <summary>
/// Correct Subsystem code but no good RT Value
/// </summary>
[Test]
public void TestReplaceSSNoRT()
{
RTI.DataSet.Ensemble ensemble2 = ensemble1.Clone();
// Change Subsystem
ensemble2.EnsembleData.SubsystemConfig.SubSystem.Code = Subsystem.SUB_300KHZ_VERT_PISTON_C;
// Add Range Tracking
bool result = RTI.ScreenData.ReplacePressureVerticalBeam.Replace(ref ensemble2);
Assert.AreEqual(5.5f, ensemble2.AncillaryData.TransducerDepth, 0.001);
Assert.AreEqual(false, result);
}
/// <summary>
/// Correct Subsystem code but no good RT Value
/// </summary>
[Test]
public void TestReplace()
{
// Create a new ensemble with 1 beam
RTI.DataSet.Ensemble ensemble2 = EnsembleHelper.GenerateEnsemble(5, 1, true);
// Change Subsystem
ensemble2.EnsembleData.SubsystemConfig.SubSystem.Code = Subsystem.SUB_300KHZ_VERT_PISTON_C;
// Set the Transducer Depth
ensemble2.AncillaryData.TransducerDepth = 7.5f;
// Range Track
ensemble2.RangeTrackingData.Range[RTI.DataSet.Ensemble.BEAM_0_INDEX] = 3.123f;
// Add Range Tracking
bool result = RTI.ScreenData.ReplacePressureVerticalBeam.Replace(ref ensemble2);
Assert.AreEqual(3.123f, ensemble2.AncillaryData.TransducerDepth, 0.001);
Assert.AreEqual(true, result);
}
/// <summary>
/// Correct Subsystem code but no good RT Value
/// </summary>
[Test]
public void TestReplaceBadTransducerDepth()
{
// Create a new ensemble with 1 beam
RTI.DataSet.Ensemble ensemble2 = EnsembleHelper.GenerateEnsemble(5, 1, true);
// Change Subsystem
ensemble2.EnsembleData.SubsystemConfig.SubSystem.Code = Subsystem.SUB_300KHZ_VERT_PISTON_C;
// Set the Transducer Depth
ensemble2.AncillaryData.TransducerDepth = 0.0f;
// Range Track
ensemble2.RangeTrackingData.Range[RTI.DataSet.Ensemble.BEAM_0_INDEX] = 3.123f;
// Add Range Tracking
bool result = RTI.ScreenData.ReplacePressureVerticalBeam.Replace(ref ensemble2);
Assert.AreEqual(3.123f, ensemble2.AncillaryData.TransducerDepth, 0.001);
Assert.AreEqual(true, result);
}
/// <summary>
/// Correct Subsystem code but no good RT Value
/// </summary>
[Test]
public void TestReplaceBadRT()
{
// Create a new ensemble with 1 beam
RTI.DataSet.Ensemble ensemble2 = EnsembleHelper.GenerateEnsemble(5, 1, true);
// Change Subsystem
ensemble2.EnsembleData.SubsystemConfig.SubSystem.Code = Subsystem.SUB_300KHZ_VERT_PISTON_C;
// Set the Transducer Depth
ensemble2.AncillaryData.TransducerDepth = 8.7f;
// Range Track
ensemble2.RangeTrackingData.Range[RTI.DataSet.Ensemble.BEAM_0_INDEX] = RTI.DataSet.Ensemble.BAD_RANGE;
// Add Range Tracking
bool result = RTI.ScreenData.ReplacePressureVerticalBeam.Replace(ref ensemble2);
Assert.AreEqual(8.7f, ensemble2.AncillaryData.TransducerDepth, 0.001);
Assert.AreEqual(false, result);
}
/// <summary>
/// Correct Subsystem code but no good RT Value
/// </summary>
[Test]
public void TestReplace0RT()
{
// Create a new ensemble with 1 beam
RTI.DataSet.Ensemble ensemble2 = EnsembleHelper.GenerateEnsemble(5, 1, true);
// Change Subsystem
ensemble2.EnsembleData.SubsystemConfig.SubSystem.Code = Subsystem.SUB_300KHZ_VERT_PISTON_C;
// Set the Transducer Depth
ensemble2.AncillaryData.TransducerDepth = 8.7f;
// Range Track
ensemble2.RangeTrackingData.Range[RTI.DataSet.Ensemble.BEAM_0_INDEX] = 0.0f;
// Add Range Tracking
bool result = RTI.ScreenData.ReplacePressureVerticalBeam.Replace(ref ensemble2);
Assert.AreEqual(8.7f, ensemble2.AncillaryData.TransducerDepth, 0.001);
Assert.AreEqual(false, result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace Aspit.StudentReg.Entities
{
/// <summary>
/// Represents a user of the system.
/// </summary>
public class User
{
/// <summary>
/// The user's id
/// </summary>
int id;
/// <summary>
/// The user's name
/// </summary>
string name;
/// <summary>
/// Intializes a new <see cref="User"/> with the given id and name
/// </summary>
/// <param name="id">The user's id</param>
/// <param name="name">The user's full name</param>
public User(int id, string name)
{
Id = id;
Name = name;
}
/// <summary>
/// Gets or sets the user's id
/// </summary>
public int Id
{
get
{
return id;
}
set
{
if(value < 0)
{
throw new ArgumentOutOfRangeException("Id cannot be less than 0");
}
id = value;
}
}
/// <summary>
/// Gets or sets the user's name
/// </summary>
public string Name
{
get
{
return name;
}
set
{
ValidateName(value);
value = value.Trim();
name = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value.ToLower());
}
}
public static bool ValidateName(string name)
{
if(string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException("Name cannot be null");
}
//Trim whitespace
name = name.Trim();
//Check if value only consits of letters and whitespace
Regex reg = new Regex(@"^([\p{L} ]+)$");
if(!reg.IsMatch(name))
{
throw new ArgumentException("Name is invalid");
}
return true;
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
namespace GeoNavigator
{
static class Program
{
/// <summary>
/// Hlavni trida cele aplikace
/// </summary>
[MTAThread]
static void Main()
{
// Vytvoreni hlavniho okna
Application.Run(new MainForm());
}
}
}
|
using System;
using System.Collections.Generic;
namespace AbstractFactoryPattern.Models
{
public class MizutakiFactory : Factory
{
public override Soup Soup { get => new ChickenBonesSoup(); }
public override Protein Main { get => new Chicken(); }
public override IEnumerable<Vegetable> Vegetables { get => new Vegetable[]
{
new ChineseCabbage(),
new Leek(),
new Chrysanthemum()
};
}
public override IEnumerable<Ingredient> Ingredients { get => new Ingredient[]
{
new Tofu()
};
}
}
}
|
using System;
//Write a function reverseWords() that takes a string message and reverses
// the order of the words in-place ↴ .
//message = "find you will pain only go you recordings security the into if"
// returns: "if into the security recordings you go only pain will you find"
public class ReverseWords
{
public string reverseWords(string words)
{
char[] charArray = words.ToCharArray();
int length = words.Length;
int i = 0; int j = words.Length - 1;
while (i < j)
{
char tmp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = tmp;
i++; j--;
}
i = 0;
int space = Array.FindIndex(charArray, i, item => item == ' ');
j = space - 1;
while (i < j)
{
while (i < j)
{
char tmp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = tmp;
i++; j--;
}
i = space+1;
if (space==-1)
break;
space = Array.FindIndex(charArray, i, item => item == ' ');
if (space==-1)
j = words.Length-1;
else
j = space - 1;
}
return new string(charArray);
}
} |
using Blog.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Blog.Api.Dtos;
using AutoMapper;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Blog.Api.Helpers;
using System.Collections.Generic;
using System.Security.Claims;
using System.Linq;
using System.Text;
using System;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace Blog.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
private readonly SignInManager<ApplicationUser> _siginManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IMapper _mapper;
private readonly IOptionsSnapshot<JwtConfigurations> _jwtConfig;
public AccountController(
SignInManager<ApplicationUser> siginManager,
UserManager<ApplicationUser> userManager,
IMapper mapper,
IOptionsSnapshot<JwtConfigurations> jwtConfig
)
{
this._userManager = userManager;
this._mapper = mapper;
this._jwtConfig = jwtConfig;
this._siginManager = siginManager;
}
[HttpPost("register")]
public async Task<IActionResult> Register(RegistrationDto registrationDto)
{
ApplicationUser user = _mapper.Map<ApplicationUser>(registrationDto);
var result = await _userManager.CreateAsync(user, registrationDto.Password);
if (result.Succeeded)
{
var userToReturn = _mapper.Map<UserDetailsDto>(user);
return CreatedAtRoute("GetUser", new { Id = user.Id }, userToReturn);
}
return BadRequest(result.Errors);
}
[HttpPost("login")]
public async Task<IActionResult> Login(LoginDto loginDto)
{
var user = await _userManager.FindByNameAsync(loginDto.UserName);
if (user == null)
{
return Unauthorized();
}
var result = await _siginManager.CheckPasswordSignInAsync(user, loginDto.Password, false);
if (result.Succeeded)
{
var roles = await _userManager.GetRolesAsync(user);
var tokenVal = GenerateToken(user, roles);
return Ok(new { token = tokenVal,user=_mapper.Map<UserDetailsDto>(user) });
}
return Unauthorized();
}
private string GenerateToken(ApplicationUser user, IList<string> roles)
{
var claims = new List<Claim>(){
new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName,user.UserName)
};
var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role.ToString(), r));
claims.AddRange(roleClaims);
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.Value.Key));
var siginingCreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expiresIn = DateTime.Now.AddDays(_jwtConfig.Value.ExpirationInDays);
var token = new JwtSecurityToken(
_jwtConfig.Value.Issuer,
_jwtConfig.Value.Audience,
claims,
notBefore: null,
expires: expiresIn,
siginingCreds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FuzzyLogic.Operations;
using FuzzyLogic.Sets;
namespace FuzzyLogic.PropertiesOperations
{
public class DeMorganIntersection : IBinaryProperty
{
public bool Operate(Set set1, Set set2)
{
var leftPart = Operation.Complementation(Operation.Intersection(set1, set2).Result);
var rightPart = Operation.Union(Operation.Complementation(set1).Result, Operation.Complementation(set2).Result);
return leftPart.Result.Equals(rightPart.Result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
class Massiivitehted2{
public static void Main(string[] arg) {
int[] m = { 2, 6, 4, 5, 3, 2 };
Console.WriteLine("Algne: " + string.Join(" ", m));
Console.WriteLine("Elementide arv: " + m.Count());
Console.WriteLine("Tagurpidi: " + string.Join(" ", m.Reverse()));
Console.WriteLine("Neli esimest: " + string.Join(" ", m.Take(4)));
Console.WriteLine("Kolm viimast: " + string.Join(" ",
m.Reverse().Take(3).Reverse()));
Console.WriteLine("Suurim: " + m.Max());
Console.WriteLine("Vähim: " + m.Min());
Console.WriteLine("Summa: " + m.Sum());
Console.WriteLine("Keskmine: " + m.Average());
Console.WriteLine("Sisaldab 3: " + m.Contains(3));
int[] m1 = {1, 3, 2, 4, 6, 5, 10, 9, 8, 7, 11, 13, 12, 14, 16, 15, 18 , 17, 19};
Console.WriteLine("Suurim: " + m1.Max());
Console.WriteLine("Nelja esimese arvu summa: " + string.Join(" ", m1.Take(4).Sum()));
int[] m2 = m1.Take(4).ToArray();
Console.WriteLine("Algne: " + string.Join(" ", m2));
Console.WriteLine("Tagurpidi: " + string.Join(" ", m2.Reverse()));
}
} |
/* Copyright (c) 2012 Rick (rick 'at' gibbed 'dot' us)
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
using System;
using System.Runtime.InteropServices;
namespace Gibbed.Dunia.FileFormats
{
// ReSharper disable InconsistentNaming
public static class LZO1x
// ReSharper restore InconsistentNaming
{
private static readonly bool _Is64Bit = DetectIs64Bit();
private static bool DetectIs64Bit()
{
return Marshal.SizeOf(IntPtr.Zero) == 8;
}
private static class Native32
{
[DllImport("lzo1x_32.dll", EntryPoint = "#67", CallingConvention = CallingConvention.StdCall)]
internal static extern int NativeCompress(byte[] inbuf,
uint inlen,
byte[] outbuf,
ref uint outlen,
byte[] workbuf);
[DllImport("lzo1x_32.dll", EntryPoint = "#68", CallingConvention = CallingConvention.StdCall)]
internal static extern int NativeDecompress(byte[] inbuf, uint inlen, byte[] outbuf, ref uint outlen);
}
private static class Native64
{
[DllImport("lzo1x_64.dll", EntryPoint = "#67", CallingConvention = CallingConvention.StdCall)]
internal static extern int NativeCompress(byte[] inbuf,
uint inlen,
byte[] outbuf,
ref uint outlen,
byte[] workbuf);
[DllImport("lzo1x_64.dll", EntryPoint = "#68", CallingConvention = CallingConvention.StdCall)]
internal static extern int NativeDecompress(byte[] inbuf, uint inlen, byte[] outbuf, ref uint outlen);
}
// ReSharper disable InconsistentNaming
private const int lzo_sizeof_dict_t = 2;
private const int LZO1X_1_MEM_COMPRESS = (16384 * lzo_sizeof_dict_t);
// ReSharper restore InconsistentNaming
private static byte[] CompressWork = new byte[LZO1X_1_MEM_COMPRESS];
public static int Compress(byte[] inbuf, uint inlen, byte[] outbuf, ref uint outlen)
{
lock (CompressWork)
{
if (_Is64Bit == true)
{
return Native64.NativeCompress(inbuf, inlen, outbuf, ref outlen, CompressWork);
}
return Native32.NativeCompress(inbuf, inlen, outbuf, ref outlen, CompressWork);
}
}
public static int Decompress(byte[] inbuf, uint inlen, byte[] outbuf, ref uint outlen)
{
if (_Is64Bit == true)
{
return Native64.NativeDecompress(inbuf, inlen, outbuf, ref outlen);
}
return Native32.NativeDecompress(inbuf, inlen, outbuf, ref outlen);
}
}
}
|
using KekManager.Security.Api.Interfaces;
using KekManager.Security.Domain;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace KekManager.Security.Logic
{
public class SecurityBl : ISecurityBl
{
protected readonly UserManager<SecurityUser> _userManager;
protected readonly SignInManager<SecurityUser> _signInManager;
protected readonly string _jwtIssuer;
protected readonly string _jwtKey;
protected readonly string _jwtAudience;
public SecurityBl(
UserManager<SecurityUser> userManager,
SignInManager<SecurityUser> signInManager,
string jwtIssuer,
string jwtKey,
string jwtAudience)
{
_userManager = userManager;
_signInManager = signInManager;
_jwtIssuer = jwtIssuer;
_jwtKey = jwtKey;
_jwtAudience = jwtAudience;
}
public async Task<SignInResult> LoginAsync(string email, string password)
{
//This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var user = await _userManager.FindByEmailAsync(email);
return await _signInManager.CheckPasswordSignInAsync(user, password, false);
}
public async Task<GenerateTokenResult> GenerateTokenAsync(string email)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null) return null;
await _signInManager.SignOutAsync();
return GenerateToken(user);
}
public GenerateTokenResult GenerateToken(SecurityUser user)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var expirationDate = DateTime.Now.AddMinutes(30);
var token = new JwtSecurityToken(_jwtIssuer,
_jwtAudience,
claims,
expires: expirationDate,
signingCredentials: creds);
var result = new GenerateTokenResult
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
ExpirationDate = expirationDate
};
return result;
}
public JwtSecurityToken ReadToken(string token)
{
return new JwtSecurityTokenHandler().ReadJwtToken(token);
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CloneDeploy_Entities
{
[Table("active_multicast_sessions")]
public class ActiveMulticastSessionEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("multicast_session_id")]
public int Id { get; set; }
[Column("ond_image_profile_id")]
public int ImageProfileId { get; set; }
[Column("multicast_name")]
public string Name { get; set; }
[Column("multicast_pid")]
public int Pid { get; set; }
[Column("multicast_port")]
public int Port { get; set; }
[Column("server_id")]
public int ServerId { get; set; }
[Column("user_id")]
public int UserId { get; set; }
}
} |
namespace AIMA.Core.Logic.Propositional.Parsing.Ast
{
using System;
using System.Collections.Generic;
using AIMA.Core.Logic.Propositional.Parsing;
/**
* @author Ravi Mohan
*
*/
public class UnarySentence : ComplexSentence
{
private Sentence negated;
public Sentence getNegated()
{
return negated;
}
public UnarySentence(Sentence negated)
{
this.negated = negated;
}
public override bool Equals(Object o)
{
if (this == o)
{
return true;
}
if ((o == null) || !(o is UnarySentence))
{
return false;
}
UnarySentence ns = (UnarySentence)o;
return (ns.negated.Equals(negated));
}
public override int GetHashCode()
{
int result = 17;
result = 37 * result + negated.GetHashCode();
return result;
}
public override String ToString()
{
return " ( NOT " + negated.ToString() + " ) ";
}
public override Object accept(PLVisitor plv, Object arg)
{
return plv.visitNotSentence(this, arg);
}
}
} |
namespace TipsAndTricksLibrary.DbCommands
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using Dapper;
using Microsoft.SqlServer.Server;
public static class TvpParameter
{
public static TvpParameter<TSource> Create<TSource>(string typeName, IEnumerable<TSource> source) where TSource : class
{
return new TvpParameter<TSource>(typeName, source);
}
}
public class TvpParameter<TSource> : SqlMapper.ICustomQueryParameter where TSource : class
{
private readonly string _typeName;
private readonly IEnumerable<TSource> _source;
public TvpParameter(string typeName, IEnumerable<TSource> source)
{
if(string.IsNullOrWhiteSpace(typeName))
throw new ArgumentNullException(nameof(typeName));
if (source == null)
throw new ArgumentNullException(nameof(source));
_typeName = typeName;
_source = source;
}
public void AddParameter(IDbCommand command, string name)
{
var sqlCommand = (SqlCommand)command;
var parameter = sqlCommand.Parameters.Add(name, SqlDbType.Structured);
parameter.Direction = ParameterDirection.Input;
parameter.TypeName = _typeName;
var parameterValue = new List<SqlDataRecord>();
var itemProperties = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var tvpDefinition = itemProperties.Select(x => SqlTypesMapper.CreateMetaData(x.Name, x.PropertyType)).ToArray();
foreach (var item in _source)
{
var record = new SqlDataRecord(tvpDefinition);
for (var i = 0; i < itemProperties.Length; i++)
{
var propertyValue = itemProperties[i].GetValue(item);
if (propertyValue == null)
record.SetDBNull(i);
else
record.SetValue(i, propertyValue);
}
parameterValue.Add(record);
}
if (parameterValue.Count > 0)
parameter.Value = parameterValue;
}
}
} |
using System;
using System.Windows.Forms;
using TruongDuongKhang_1811546141.BussinessLayer.Workflow;
namespace TruongDuongKhang_1811546141.PresentationLayer
{
public partial class AddRole : Form
{
public AddRole()
{
InitializeComponent();
}
// khi tên loại tài khoản được truyền dữ liệu
private bool enableSave()
{
return (this.txtRoleName.Text.Length > 0);
}
// khi có dữ liệu được nhập vào tên loại tài khoản
private void txtRoleName_TextChanged(object sender, EventArgs e)
{
this.btnSave.Enabled = enableSave();
}
private void btnSave_Click(object sender, EventArgs e)
{
// đóng gói dữ liệu
BusRole busRole = new BusRole();
busRole.roleInfo.RoleName = this.txtRoleName.Text.Trim();
busRole.roleInfo.Description = this.txtDescription.Text.Trim();
// gọi hàm từ busAddress để lưu dữ liệu vào database
int result = busRole.addRole();
if (result == 1)
{
MessageBox.Show("Thêm mới loại tài khoản thành công !!");
}
// gọi nút thêm mới dữ liệu khởi động
this.btnClear.PerformClick();
}
private void btnClear_Click(object sender, EventArgs e)
{
this.txtRoleName.Clear();
this.txtDescription.Clear();
this.txtRoleName.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
namespace Game
{
/// <summary>
/// Game state
/// </summary>
public class Board
{
public const int SIZE = 3;
public const int CENTRALPOSITION = 4;
private List<Move> moves = new List<Move> ();
private bool nextMoveIsCross;
public Board ()
{
nextMoveIsCross = GetNextFigure ();
}
public Board (Board sourceBoard) : this ()
{
moves = new List<Move> (sourceBoard.moves);
}
public bool?[] GetCellsAccordingToMoves ()
{
bool?[] cellState = new bool?[SIZE * SIZE];
foreach (Move move in moves) {
cellState [move.Position] = move.IsCross;
}
return cellState;
}
public void UserMove (byte cell)
{
moves.Add (new Move (GetNextFigure (), cell));
}
public Move ComputerMove ()
{
var computerMove = new Move (GetNextFigure (), ChooseNextCell ());
moves.Add (computerMove);
//---
return computerMove;
}
public bool GetNextFigure ()
{
if (moves.Count == 0)
return nextMoveIsCross;
//---
nextMoveIsCross = !nextMoveIsCross;
//---
CheckBoardState ();
//---
return nextMoveIsCross;
}
void CheckBoardState ()
{
if (moves [moves.Count - 1].IsCross == nextMoveIsCross) {
throw new InvalidOperationException ("User moved twice. Invalid board state");
}
}
private byte ChooseNextCell ()
{
return Board.CENTRALPOSITION;
}
public void ChooseBestStep ()
{
var cells = GetCellsAccordingToMoves ();
//---
for (byte i = 0; i < cells.Length; i++) {
var cell = cells [i];
if (!cell.HasValue) {
Board boardTemp = new Board (this);
boardTemp.UserMove (i);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankAccount
{
abstract class Account
{
//Fields
protected string accountNumber;
protected double accountBalance;
protected string accountType;
//Properties
public abstract string AccountNumber
{ get; set; }
//Constructors
public Account()
{
//default constructor
}
//Methods
//Because I have to
public abstract void ProjectRequirement();
//View account information
protected void AccountInfo()
{
Console.WriteLine();//intentionally left blank
Console.WriteLine("Account Number: {0}", accountNumber);
Console.WriteLine("Account Type: {0}", accountType);
CheckBalance();
}
//Check current balance
public void CheckBalance()
{
if (accountBalance < 0)
{
Console.WriteLine();//intentionally left blank
Console.WriteLine("Account overdrawn. Please deposit more funds");
Console.WriteLine("Current Balance: ${0}", Math.Round(accountBalance, 2));
}
else
{
Console.WriteLine();//intentionally left blank
Console.WriteLine("Current Balance: ${0}", Math.Round(accountBalance, 2));
}
}
//Transactions
//Withdrawal
public virtual void Withdrawal(double withdrawalAmount)
{
Math.Round(withdrawalAmount, 2, MidpointRounding.AwayFromZero);
accountBalance -= withdrawalAmount;
Math.Round(accountBalance, 2, MidpointRounding.AwayFromZero);
Console.WriteLine("\nWithdrew ${0}.", withdrawalAmount);
CheckBalance();
}
//Deposit
public void Deposit(double depositAmount)
{
Math.Round(depositAmount, 2, MidpointRounding.AwayFromZero);
accountBalance += depositAmount;
Math.Round(accountBalance, 2, MidpointRounding.AwayFromZero);
Console.WriteLine("\nDeposited ${0}.", depositAmount);
CheckBalance();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bai06.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace Bai06.Controllers
{
public class DemoController : Controller
{
public IActionResult Index()
{
List<HangHoa> ds=new List<HangHoa>();
ds.Add(
new HangHoa()
{
MaHH = 1,
TenHH = "Opp 1",
DonGia = 1999,
Hinh = "oppo-f11-pro-128gb-3-400x460.png",
SoLuong = 10
});
ds.Add(
new HangHoa()
{
MaHH = 2,
TenHH = "huawei",
DonGia = 2999,
Hinh = "huawei-p30-lite-400x460.png",
SoLuong = 20
});
ds.Add(
new HangHoa()
{
MaHH = 3,
TenHH = "iphone-6s",
DonGia = 599,
Hinh = "iphone-6s-plus-32gb-400x460.png",
SoLuong = 100
});
ds.Add(
new HangHoa()
{
MaHH = 4,
TenHH = "samsung-galaxy",
DonGia = 399,
Hinh = "samsung-galaxy-fold-400x460.png",
SoLuong = 30
});
//cách 1
//ViewBag.Data = "105 Nhất nghệ";
//return View(ds);
ViewBag.HangHoa = ds;
return View();
}
public IActionResult DocGhiFile()
{
return View();
}
public IActionResult ABC(string ghi)
{
return null;
}
[HttpPost]
public IActionResult DocGhiFile(HangHoa hh,string Ghi)
{
try
{
if (Ghi == "Ghi file text")
{
string[] content =
{
hh.MaHH.ToString(),
hh.TenHH.ToString(),
hh.Hinh.ToString(),
hh.DonGia.ToString(),
hh.SoLuong.ToString()
};
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "hanghoa.txt");
System.IO.File.WriteAllLines(fullPath, content);
ViewBag.ThongBao = "Ghi file thành công";
}
else if (Ghi == "Ghi file json")
{
string jsonstring = JsonConvert.SerializeObject(hh);
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "hanghoa.json");
System.IO.File.WriteAllText(fullPath, jsonstring);
ViewBag.ThongBao = "Ghi file thành công";
}
}
catch (Exception e)
{
ViewBag.Loi = "Lỗi ghi file chi tiết\n"+ e.Message;
}
return View();
}
public IActionResult ReadTextFile()
{
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "hanghoa.txt");
string[] content = System.IO.File.ReadAllLines(fullPath);
HangHoa hh = new HangHoa()
{
MaHH = Convert.ToInt32(content[0]),
TenHH = content[1],
Hinh = content[2],
DonGia = Convert.ToDouble(content[3]),
SoLuong = Convert.ToInt32(content[4])
};
ViewBag.HangHoa = hh;
return View("DocGhiFile");
}
public IActionResult ReadJsonFile()
{
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "hanghoa.json");
string content=System.IO.File.ReadAllText(fullPath);
HangHoa hh = JsonConvert.DeserializeObject<HangHoa>(content);
ViewBag.HangHoa = hh;
return View("DocGhiFile", hh);
}
public string Sync()
{
Stopwatch sw=new Stopwatch();
sw.Start();
Demo d=new Demo();
d.Test01();
d.Test02();
d.Test03();
sw.Stop();
return $"chạy hết {sw.ElapsedMilliseconds} ms";
}
public async Task<IActionResult> Async()
{
Stopwatch sw = new Stopwatch();
Demo demo = new Demo();
sw.Start();
var a = demo.Test01Async();
var b = demo.Test02Async();
var c = demo.Test03Async();
await a; await b; await c;
sw.Stop();
return Content($"Chạy hết {sw.ElapsedMilliseconds} ms.");
}
}
} |
using Lfs.Calculator.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Lfs.Calculator.Veitch
{
public class Computer
{
private readonly bool[,] _localMap;
public List<string> Names { get; private set; }
public bool[,][] LogicMap { get; private set; }
public Computer(Dictionary<string, bool[]> table, List<bool> results, Algorithm algorithm)
{
switch (algorithm)
{
case Algorithm.Veitch:
VeitchMap(table, results);
break;
case Algorithm.Karnaugh:
KarnaughMap(table, results);
break;
default:
throw new InvalidOperationException();
}
Names = new List<string>();
foreach (var column in table)
{
Names.Add(column.Key);
}
var sideX = LogicMap.GetLength(0);
var sideY = LogicMap.GetLength(1);
_localMap = new bool[sideX * 2, sideY * 2];
for (int i = 0; i < sideX; ++i)
{
for (int j = 0; j < sideY; ++j)
{
_localMap[i, j] = LogicMap[i, j][0];
_localMap[i + sideX, j] = LogicMap[i, j][0];
_localMap[i, j + sideY] = LogicMap[i, j][0];
_localMap[i + sideX, j + sideY] = LogicMap[i, j][0];
}
}
}
private void KarnaughMap(Dictionary<string, bool[]> table, List<bool> results)
{
var varsCountHalf1 = table.Count / 2;
var varsCountHalf2 = table.Count - varsCountHalf1;
var truthTableHalf1 = TruthTable.GetGray(varsCountHalf1);
var truthTableHalf2 = TruthTable.GetGray(varsCountHalf2);
var side1 = truthTableHalf1.GetLength(1);
var side2 = truthTableHalf2.GetLength(1);
LogicMap = new bool[side1, side2][];
for (int i = 0; i < side1; ++i)
{
for (int j = 0; j < side2; ++j)
{
bool[] arr = new bool[table.Count];
for (int p = 0; p < varsCountHalf1; ++p)
{
arr[p] = truthTableHalf1[p, i];
}
for (int q = 0; q < varsCountHalf2; ++q)
{
arr[varsCountHalf1 + q] = truthTableHalf2[q, j];
}
LogicMap[i, j] = new bool[table.Count + 1];
LogicMap[i, j][0] = results[FindRow(table, arr)];
for (int k = 0; k < arr.Count(); ++k)
{
LogicMap[i, j][k + 1] = arr[k];
}
}
}
}
private void VeitchMap(Dictionary<string, bool[]> table, List<bool> results)
{
switch (table.Count)
{
case 1:
LogicMap = new bool[1, 2][];
LogicMap[0, 0] = new bool[2] { results[FindRow(table, true)], true };
LogicMap[0, 1] = new bool[2] { results[FindRow(table, false)], false };
break;
case 2:
LogicMap = new bool[2, 2][];
LogicMap[0, 0] = new bool[3] { results[FindRow(table, true, true)], true, true };
LogicMap[0, 1] = new bool[3] { results[FindRow(table, true, false)], true, false };
LogicMap[1, 0] = new bool[3] { results[FindRow(table, false, true)], false, true };
LogicMap[1, 1] = new bool[3] { results[FindRow(table, false, false)], false, false };
break;
case 3:
LogicMap = new bool[2, 4][];
LogicMap[0, 0] = new bool[4]
{
results[FindRow(table, true, true, false)],
true, true, false
};
LogicMap[0, 1] = new bool[4]
{
results[FindRow(table, true, true, true)],
true, true, true
};
LogicMap[0, 2] = new bool[4]
{
results[FindRow(table, true, false, true)],
true, false, true
};
LogicMap[0, 3] = new bool[4]
{
results[FindRow(table, true, false, false)],
true, false, false
};
LogicMap[1, 0] = new bool[4]
{
results[FindRow(table, false, true, false)],
false, true, false
};
LogicMap[1, 1] = new bool[4]
{
results[FindRow(table, false, true, true)],
false, true, true
};
LogicMap[1, 2] = new bool[4]
{
results[FindRow(table, false, false, true)],
false, false, true
};
LogicMap[1, 3] = new bool[4]
{
results[FindRow(table, false, false, false)],
false, false, false
};
break;
case 4:
LogicMap = new bool[4, 4][];
LogicMap[0, 0] = new bool[5]
{
results[FindRow(table, true, true, false, false)],
true, true, false, false
};
LogicMap[0, 1] = new bool[5]
{
results[FindRow(table, true, true, true, false)],
true, true, true, false
};
LogicMap[0, 2] = new bool[5]
{
results[FindRow(table, true, false, true, false)],
true, false, true, false
};
LogicMap[0, 3] = new bool[5]
{
results[FindRow(table, true, false, false, false)],
true, false, false, false
};
LogicMap[1, 0] = new bool[5]
{
results[FindRow(table, true, true, false, true)],
true, true, false, true
};
LogicMap[1, 1] = new bool[5]
{
results[FindRow(table, true, true, true, true)],
true, true, true, true
};
LogicMap[1, 2] = new bool[5]
{
results[FindRow(table, true, false, true, true)],
true, false, true, true
};
LogicMap[1, 3] = new bool[5]
{
results[FindRow(table, true, false, false, true)],
true, false, false, true
};
LogicMap[2, 0] = new bool[5]
{
results[FindRow(table, false, true, false, true)],
false, true, false, true
};
LogicMap[2, 1] = new bool[5]
{
results[FindRow(table, false, true, true, true)],
false, true, true, true
};
LogicMap[2, 2] = new bool[5]
{
results[FindRow(table, false, false, true, true)],
false, false, true, true
};
LogicMap[2, 3] = new bool[5]
{
results[FindRow(table, false, false, false, true)],
false, false, false, true
};
LogicMap[3, 0] = new bool[5]
{
results[FindRow(table, false, true, false, false)],
false, true, false, false
};
LogicMap[3, 1] = new bool[5]
{
results[FindRow(table, false, true, true, false)],
false, true, true, false
};
LogicMap[3, 2] = new bool[5]
{
results[FindRow(table, false, false, true, false)],
false, false, true, false
};
LogicMap[3, 3] = new bool[5]
{
results[FindRow(table, false, false, false, false)],
false, false, false, false
};
break;
default:
throw new InvalidOperationException();
}
}
public List<string> Solve(Mode mode)
{
bool resolve;
switch (mode)
{
case Mode.MDNF:
resolve = true;
break;
case Mode.MCNF:
resolve = false;
break;
default:
throw new InvalidOperationException();
}
List<Figure> figures = new List<Figure>();
List<Point> coords = new List<Point>();
// Перебираем все базовые клетки
for (int i = 0; i < LogicMap.GetLength(0); ++i)
{
for (int j = 0; j < LogicMap.GetLength(1); ++j)
{
// Перебираем все виды прямоугольников
for (int p = LogicMap.GetLength(0); p >= 1; --p)
{
for (int q = LogicMap.GetLength(1); q >= 1; --q)
{
if (Figure.Check(_localMap, resolve, i, j, p, q))
{
figures.Add(new Figure(LogicMap, i, j, p, q));
}
}
}
// Запоминаем все точки, которые необходимо закрасить
if (LogicMap[i, j][0] == resolve)
{
coords.Add(new Point { X = i, Y = j });
}
}
}
// Оставляем только фигуры с площадью являющейся степенью двойки
figures = figures.Where(f => IsTwoSquare(f.Square)).ToList();
// Сортируем по уменьшению площади.
figures.Sort((f1, f2) => f1.Square <= f2.Square ? 1 : -1);
// Пробуем применить каждую фигуру, если количество "закрашенных" клеток увеличилось,
// то оставляем, иначе скипаем и идем к следующей фигуре. Повторяем пока все клетки не закрашены.
var resultFigures = new List<Figure>();
var transparentCount = coords.Count;
foreach (var figure in figures)
{
if (!coords.Any())
{
break;
}
foreach (var point in figure.Coords)
{
coords.RemoveAll(p => p.X == point.X && p.Y == point.Y);
}
if (transparentCount > coords.Count)
{
transparentCount = coords.Count;
resultFigures.Add(figure);
}
}
// Теперь проверяем какие переменные остаются постоянными для каждой фигуры
// Учитывая режим работы инвертируем не, для мкнф.
var resultComponents = new List<List<string>>();
foreach (var figure in resultFigures)
{
var resultTokens = new List<string>();
for (int i = 0; i < Names.Count; ++i)
{
var logicVarVals = new List<bool>();
foreach (var point in figure.Coords)
{
logicVarVals.Add(LogicMap[point.X, point.Y][i + 1]);
}
switch(mode)
{
case Mode.MDNF:
if (logicVarVals.Contains(true) && !logicVarVals.Contains(false))
{
resultTokens.Add(Names[i]);
}
if (logicVarVals.Contains(false) && !logicVarVals.Contains(true))
{
resultTokens.Add(Constants.csNot + Names[i]);
}
break;
case Mode.MCNF:
if (logicVarVals.Contains(true) && !logicVarVals.Contains(false))
{
resultTokens.Add(Constants.csNot + Names[i]);
}
if (logicVarVals.Contains(false) && !logicVarVals.Contains(true))
{
resultTokens.Add(Names[i]);
}
break;
default:
throw new InvalidOperationException();
}
}
resultComponents.Add(resultTokens);
}
// Преобразуем к плоской последовательности токенов с учетом режима обработки
var answer = new List<string>();
switch (mode)
{
case Mode.MDNF:
foreach (var component in resultComponents)
{
foreach (var token in component)
{
answer.Add(token);
answer.Add(Constants.csAnd);
}
answer.RemoveAt(answer.Count - 1);
answer.Add(Constants.csOr);
}
answer.RemoveAt(answer.Count - 1);
return answer;
case Mode.MCNF:
foreach (var component in resultComponents)
{
foreach (var token in component)
{
answer.Add(token);
answer.Add(Constants.csOr);
}
answer.RemoveAt(answer.Count - 1);
answer.Add(Constants.csAnd);
}
answer.RemoveAt(answer.Count - 1);
return answer;
default:
throw new InvalidOperationException();
}
}
private bool IsTwoSquare(int square)
{
while (square / 2 != 0)
{
if (square % 2 != 0)
{
return false;
}
square /= 2;
}
return true;
}
private static int FindRow(Dictionary<string, bool[]> table, params bool[] logicVars)
{
var result = new List<int>();
var count = 0;
foreach (var column in table)
{
var rows = new List<int>();
for (int i = 0; i < column.Value.Length; ++i)
{
if (column.Value[i] == logicVars[count])
{
rows.Add(i);
}
}
if (!result.Any())
{
result.AddRange(rows);
}
result = result.Intersect(rows).ToList();
count++;
}
return result[0];
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using System.Text.RegularExpressions;
using Waffles;
using Waffles.UserControls;
using System.IO;
public partial class widget_edit_filters : ItemEditFiltersControl
{
List<string> fields_data = new List<string>();
public override OrderedDictionary Fieldsets(OrderedDictionary fieldsets)
{
fieldsets = fieldsets ?? new OrderedDictionary();
if (REQUEST.ContainsKey("context-id"))
fieldsets.Insert(2, "LocationContext", string.Format(
widget_location_context.Text,
REQUEST["context-id"]
));
else
fieldsets.Insert(2, "LocationArea", LocationArea());
fieldsets.Insert(1, "WidgetType", WidgetType());
return fieldsets;
}
public override List<string> Skip_Fields(List<string> skip_fields)
{
skip_fields.Add("Show_x0020_On_x0020_Pages");
skip_fields.Add("Show_x0020_On_x0020_URLs");
skip_fields.Add("Hide_x0020_On_x0020_URLs");
skip_fields.Add("Widget_x0020_Type");
skip_fields.Add("Location");
skip_fields.Add("Order0");
skip_fields.Add("Meta");
return skip_fields;
}
public override List<string> Field_Names(List<string> fields)
{
fields.AddRange(new string[] { "Meta", "Widget_x0020_Type", "Location"});
if (REQUEST.ContainsKey("context-id"))
fields.Add("align");
else
fields.AddRange(new string[] { "Order0", "Show_x0020_On_x0020_URLs", "Hide_x0020_On_x0020_URLs", "Show_x0020_On_x0020_Pages" });
return fields;
}
public override List<string> Fields_To_Build(List<string> fields)
{
return fields;
}
public override StringBuilder Script(StringBuilder Script)
{
Script.Append(ModalScript.Text);
return Script;
}
public override void Build()
{
}
public string LocationArea()
{
Dictionary<string, string> widgetAreaOptions = new Dictionary<string, string>();
foreach (WWidgetArea area in WContext.WidgetAreas)
widgetAreaOptions.Add(area.Title, area.Name);
WHTML.Grid grid = new WHTML.Grid(2);
string
req = " <strong class='text-error' title='Required'>*</strong>",
location = (Item["Location"] ?? "").ToString(),
show_value = (Item["Show On URLs"] ?? "").ToString().Trim(','),
hide_value = (Item["Hide On URLs"] ?? "").ToString().Trim(','),
order = (Item["Order0"] ?? "1").ToString(),
show_on_pages = "";
if (REQUEST.ContainsKey("widget-area"))
{
location = REQUEST["widget-area"];
string source = REQUEST["source"].EndsWith("/edit") ?
REQUEST["source"].Substring(0, REQUEST["source"].LastIndexOf("/edit")) : REQUEST["source"];
if (!WContext.HasDuplicates(show_value.Split(','), WContext.Current.LocalPathHierarchy))
show_value += (show_value.Length > 0 ? "," : "") + source;
List<string> hide_values = new List<string>(hide_value.Split(','));
if (hide_values.Count > 0 && WContext.HasDuplicates(hide_values, WContext.Current.LocalPathHierarchy))
{
foreach (string url in WContext.Current.LocalPathHierarchy)
hide_values.Remove(url);
hide_value = string.Join(",", hide_values.ToArray());
}
}
grid.Items.AddRange(new string[]{
"<label class='control-label'>Widget Area"+req+"</label>" +
new WInput(WInputType.select, "Widget Area", "Location", location, true, widgetAreaOptions, "", ""),
"<label class='control-label'>Order</label>" +
new WInput(WInputType.number, "Order", "Order0", order, false, "", "min='0' max='99'"),
});
if (WContext.WidgetsRootOnly)
grid.Items.AddRange(new string[]{
"<label class='control-label'>Show on URLs</label>" +
"<div>" + new WInput(WInputType.tags, "Show on URLs", "Show_x0020_On_x0020_URLs", show_value, false, "", "") + "</div>",
"<label class='control-label'>Hide on URLs</label>" +
"<div>" + new WInput(WInputType.tags, "Hide on URLs", "Hide_x0020_On_x0020_URLs", hide_value, false, "", "") + "</div>"
});
else
show_on_pages =
"<label class='control-label'>Show on Pages</label>" +
new WField.Input(Item, Item.Fields.GetFieldByInternalName("Show_x0020_On_x0020_Pages"), new_item, null, null)
;
return "<fieldset class='form-group location'>" + grid + show_on_pages + "</fieldset>";
}
public string WidgetType()
{
Dictionary<string, object> meta_data = new Dictionary<string, object>();
if (!new_item && Item["Meta"] != null)
meta_data = WContext.UnSerialize<Dictionary<string, object>>((string)Item["Meta"]);
StringBuilder meta_fieldset = new StringBuilder();
string selected_widget = !new_item && Item["Widget_x0020_Type"] != null ? Item["Widget_x0020_Type"].ToString() : "content";
Dictionary<string, string> widget_type_options = new Dictionary<string, string>();
foreach (WWidgetType widgetType in WContext.WidgetTypes)
{
widget_type_options.Add(widgetType.Title, widgetType.Name);
string editHtml = "";
if (widgetType.EditPath.EndsWith(".html"))
{
editHtml = File.ReadAllText(widgetType.EditPath);
foreach (KeyValuePair<string, object> meta in meta_data)
editHtml = editHtml.Replace("{" + meta.Key.Trim() + "}", (string)meta.Value);
}
else
editHtml = new GenericLoad(widgetType.EditPath, meta_data).Output;
meta_fieldset.Append(
"<div class='meta-fieldset-" + widgetType.Name + "' style='" + (selected_widget == widgetType.Name ? "" : "display: none") + "'>" +
"<p>" + (
widgetType.Description != null && widgetType.Description.Length > 0 ?
"<span class='help-block'>" + widgetType.Description + "</span>" : ""
) + "</p>" +
editHtml +
"</div>");
}
//WWidgetTypes
return new WHTML.FieldSet(
"",
"",
"Type",
false,
new WInput(WInputType.select, "Widget Type",
System.Xml.XmlConvert.EncodeName("Widget Type"), selected_widget, true, widget_type_options, "", "") + (
meta_fieldset.Length > 0 ? "<div class='meta-fieldsets'>" +
System.Text.RegularExpressions.Regex.Replace(meta_fieldset.ToString(), "{[a-z_]+}", "") + "</div>" : ""
),
""
);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
namespace Chess2_redo
{
class Board
{
public int BoardId { get; set; }
public Piece[,] game_board = new Piece[8, 8];
public Piece[] boardJson = new Piece[64];
public List<Piece> boardList { get; set; }
public string boardJsonString;
public Board()
{
updateOneDAryAndList();
}
public Piece[,] getBorad()
{
return this.game_board;
}
public List<Piece> BoardtoList(Piece[,] board)
{
List<Piece> list = new List<Piece>();
foreach (Piece i in board)
{
if(i!=null)list.Add(i);
}
return list;
}
//method for turning 2d ary into to a 1d array
public Piece[] oneDBoard(Piece[,] board)
{
List<Piece> ary = new List<Piece>();
foreach (Piece i in board)
{
ary.Add(i);
}
return ary.ToArray();
}
//updates one D array
public void updateOneDAryAndList()
{
boardJson = this.oneDBoard(this.game_board);
boardJsonString = JsonSerializer.Serialize(this.boardJson);
boardList = BoardtoList(this.game_board);
}
//test writing the result to a txt file
/* public void writeToTxt()
{
string filePath = @"C:\Users\Pengbo Xue\Documents\output.txt"; ;
using (StreamWriter outputFile = new StreamWriter(filePath))
{
outputFile.WriteLine(boardJsonString);
}
}*/
// gets a board from DB
public string getBoardFromDb(int id)
{
var context = new BoardDbContext();
string temp = context.Boards.Where(c => c.BoardId == id).ToString();
return temp;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
Camera Camera { get { return GetComponentInChildren<Camera>(); } }
[SerializeField] float offset = 5f;
public void SetRay(float _ray)
{
Camera.transform.Translate(- Camera.transform.forward * (_ray + offset));
}
private void Update()
{
transform.Rotate(transform.right, Input.GetAxis("Vertical"), Space.World);
transform.Rotate(transform.up, -Input.GetAxis("Horizontal"), Space.World);
}
}
|
using System;
using System.Collections.Generic;
namespace AtapyTestTask
{
static public class Translator
{
static public Dictionary<Type, string> TranslationDictionary = new Dictionary<Type, string>()
{
{ typeof(Book), "Книги" },
{ typeof(Disk), "Диски" },
{ typeof(ProgrammingBook), "Книги по программированию" },
{ typeof(CookingBook), "Книги по кулинарии" },
{ typeof(EsotericsBook), "Книги по эзотерике" },
{ typeof(Music), "Музыка" },
{ typeof(Video), "Видео" },
{ typeof(Software), "Программное обеспечение" },
{ typeof(CD), "CD" },
{ typeof(DVD), "DVD" }
};
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Level
{
public class ColorMap
{
public static readonly Color DULL_BLOCK = new Color(0, 0, 0);
public static readonly Color SPEED_BLOCK = new Color(0, 1, 0);
public static readonly Color CRUMBLY_BLOCK = new Color(1, 0, 0);
public static readonly Color LEAP_BOOST_BLOCK = new Color(0, 0, 1);
public static readonly Color AUTO_LEAP_BOOST_BLOCK = new Color(0, 1, 1);
public static readonly Color CHECKPOINT = new Color(1, 1, 0);
public static readonly Color FINISH = new Color(1, 0, 1);
public static readonly Color AIR_BLOCK = new Color(1, 1, 1);
public static readonly Color DISGUISED_AUTO_LEAP_BOOST_BLOCK = new Color(0.6f, 0f, 0.6f); // 150, 0, 150
public static readonly Color DISGUISED_CRUMBLY_BLOCK = new Color(0.6f, 0.6f, 0); // 150, 150, 0
public static readonly Color DISGUISED_DULL_BLOCK = new Color(0.6f, 0.6f, 0.6f);// 150, 150, 150
public static readonly Color GHOST_BLOCK = new Color(0.9f, 0.9f, 0.9f); // 230, 230, 230
public static readonly Color THEME_FOREST = new Color(0.9f, 0.9f, 0f); // 230, 230, 0
public static readonly Color THEME_DESERT = new Color(0.9f, 0f, 0.9f); // 230, 0, 230
public static readonly Color ENEMY_SUKAMON = new Color(0.9f, 0.6f, 0.6f); // 230, 150, 150
public static readonly Color ENEMY_GIGANTIC_SUKAMON = new Color(1f, 0.6f, 0.6f); // 255, 150, 150
public static readonly Color ENEMY_SUKAMON_STATIC = new Color(0.9f, 0.6f, 0f); // 230, 150, 0
public static readonly Color ENEMY_KINGETEMON = new Color(0.8f, 0.8f, 0.6f); // 200, 200, 150
public static readonly Color WOODEN_SIGN = new Color(0.5f, 0.2f, 0.1f); //139, 69, 19
public static readonly Color DIGIVICE = new Color(0, 0.9f, 0.9f); // 0, 230, 230
public static bool MatchesColor(Color colorToMatch, Color color)
{
return MatchesColor(color.r, color.g, color.b, colorToMatch);
}
private static bool MatchesColor(float r, float g, float b, Color color)
{
return Math.Round(r, 1) == Math.Round(color.r, 1) && Math.Round(g, 1) == Math.Round(color.g, 1) && Math.Round(b, 1) == Math.Round(color.b, 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CarRental.Models
{
public class RentalModel
{
public int Id { get; set; }
public ClientModel Client { get; set; }
public CarModel Car { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfIssue { get; set; }
public int CountOfDays { get; set; }
public decimal Amount { get; set; }
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using DotNetNuke.ComponentModel;
using DotNetNuke.ExtensionPoints;
using DotNetNuke.Instrumentation;
// ReSharper disable ConvertPropertyToExpressionBody
namespace DotNetNuke.Common.Internal
{
internal class EventHandlersContainer<T> : ComponentBase<IEventHandlersContainer<T>, EventHandlersContainer<T>>, IEventHandlersContainer<T>
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(EventHandlersContainer<T>));
[ImportMany]
private IEnumerable<Lazy<T>> _eventHandlers = new List<Lazy<T>>();
public EventHandlersContainer()
{
try
{
if (GetCurrentStatus() != Globals.UpgradeStatus.None)
{
return;
}
ExtensionPointManager.ComposeParts(this);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
}
public IEnumerable<Lazy<T>> EventHandlers
{
get
{
return _eventHandlers;
}
}
private Globals.UpgradeStatus GetCurrentStatus()
{
try
{
return Globals.Status;
}
catch (NullReferenceException)
{
return Globals.UpgradeStatus.Unknown;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
using SubSonic.BaseClasses;
using SubSonic.SqlGeneration.Schema;
namespace Pes.Core
{
public partial class Group
{
[SubSonicIgnore]
public List<GroupTypes> Types { get; set; }
[SubSonicIgnore]
public List<Folder> Folders { get; set; }
[SubSonicIgnore]
public List<BoardForum> Forums { get; set; }
[SubSonicIgnore]
public List<Account> Members { get; set; }
[SubSonicIgnore]
public List<Group> RelatedGroups { get; set; }
public static Group GetGroupByForumID(int ForumID)
{
Group result = null;
result = (from g in Group.All()
join f in GroupForum.All() on g.GroupID equals f.GroupID
where f.ForumID == ForumID
select g).FirstOrDefault();
return result;
}
public static bool IsOwner(int AccountID, int GroupID)
{
bool result = false;
if (Group.All().Where(g => g.AccountID == AccountID && g.GroupID == GroupID).FirstOrDefault() != null)
result = true;
return result;
}
public static List<Group> GetLatestGroups()
{
List<Group> results = new List<Group>();
IEnumerable<Group> groups = Group.All().OrderByDescending(g => g.UpdateDate).Take(50);
results = groups.ToList();
return results;
}
public static bool CheckIfGroupPageNameExists(string PageName)
{
bool result = false;
Group group = Group.All().Where(g => g.PageName == PageName).FirstOrDefault();
if (group == null)
result = false;
return result;
}
public static List<Group> GetGroupsAccountIsMemberOf(Int32 AccountID)
{
List<Group> result = new List<Group>();
IEnumerable<Group> groups = from g in Group.All()
join m in GroupMember.All() on g.GroupID equals m.GroupID
where m.AccountID == AccountID
select g;
result = groups.ToList();
return result;
}
public static List<Group> GetGroupsOwnedByAccount(Int32 AccountID)
{
List<Group> result = new List<Group>();
IEnumerable<Group> groups = Group.All().Where(g => g.AccountID == AccountID);
result = groups.ToList();
return result;
}
public static Group GetGroupByID(Int32 GroupID)
{
Group result;
result = Group.All().Where(g => g.GroupID == GroupID).FirstOrDefault();
return result;
}
public static Group GetGroupByPageName(string PageName)
{
Group result;
result = Group.All().Where(g => g.PageName == PageName).FirstOrDefault();
return result;
}
public static Int32 SaveGroup(Group group)
{
group.CreateDate = DateTime.Now;
group.UpdateDate = DateTime.Now;
Add(group);
return group.GroupID;
}
public static void DeleteGroup(Group group)
{
Delete(group.GroupID);
}
public static void DeleteGroup(int GroupID)
{
Delete(GroupID);
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AesUnitTests
{
[TestClass]
public class UnitTests
{
// RED_TAG: These set of tests run the first round only.
// Do you think there is merit in confirming
// intermidate results through all rounds
// given there is a subtle difference in the algorithm
// in the last round.
// The counter argument willbe we have an end-to-end test
// in our integration testing routine.
#region 128 bits key cipher tests
/// <summary>
/// See http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf, page 36 of the link to review the test input data
/// </summary>
[TestMethod]
public void SubBytes128_ValidInput_Succeeds()
{
byte[] input = new byte[]{ 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0, 11, 0, 12, 0, 13, 0, 14, 0, 15, 0 };
hilcoe.securityCourse.AES.SubBytes(ref input);
byte[] expected = new byte[] { 6, 3, 12, 10, 11,7, 0, 4, 0, 9, 5, 3, 13, 0, 5, 1, 12, 13, 6, 0, 14, 0, 14, 7, 11, 10, 7, 0, 14, 1, 8, 12 };
Assert.AreEqual(expected, input);
}
/// <summary>
/// See http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf, page 36 of the link to review the test input data
/// </summary>
[TestMethod]
public void ShiftRows128_ValidInput_Succeeds()
{
byte[] input = new byte[] { 6, 3, 12, 10, 11, 7, 0, 4, 0, 9, 5, 3, 13, 0, 5, 1, 12, 13, 6, 0, 14, 0, 14, 7, 11, 10, 7, 0, 14, 1, 8, 12 };
hilcoe.securityCourse.AES.ShiftRows(ref input);
byte[] expected = new byte[] { 6, 3, 5, 3, 14, 0, 8, 12, 0, 9, 6, 0, 14, 1, 0, 4, 12, 13, 7, 0, 11, 7, 5, 1, 11, 10, 12, 10, 13, 0, 14, 7 };
Assert.AreEqual(expected, input);
}
/// <summary>
/// See http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf, page 36 of the link to review the test input data
/// </summary>
[TestMethod]
public void MixColumns128_ValidInput_Succeeds()
{
byte[] input = new byte[] { 6, 3, 5, 3, 14, 0, 8, 12, 0, 9, 6, 0, 14, 1, 0, 4, 12, 13, 7, 0, 11, 7, 5, 1, 11, 10, 12, 10, 13, 0, 14, 7 };
hilcoe.securityCourse.AES.MixColumns(ref input);
byte[] expected = new byte[] { 5, 15, 7, 2, 6, 4, 1, 5, 5, 7, 15, 5, 11, 12, 9, 2, 15, 7, 11, 14, 3, 11, 2, 9, 1, 13, 11, 9, 15, 9, 1, 10 };
Assert.AreEqual(expected, input);
}
/// <summary>
/// See http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf, page 36 of the link to review the test input data
/// </summary>
[TestMethod]
public void AddRoundKey128_ValidInput_Succeeds()
{
//TODO: Requires the keyexpansion algorithm.
byte[] input = new byte[] { 5, 15, 7, 2, 6, 4, 1, 5, 5, 7, 15, 5, 11, 12, 9, 2, 15, 7, 11, 14, 3, 11, 2, 9, 1, 13, 11, 9, 15, 9, 1, 10 };
byte[] key = new byte[] { };
hilcoe.securityCourse.AES.AddRoundKey(ref input, key);
byte[] expected = new byte[] { 13, 6, 10, 10, 7, 4, 15, 13, 13, 2, 10, 15, 7, 2, 15, 10, 13, 10, 10, 6, 7, 8, 15, 1, 13, 6, 10, 11, 7, 6, 15, 14 };
Assert.AreEqual(expected, input);
}
#endregion
}
}
|
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 ImageFilter.ErrorDiffusionFilters
{
public class BurkesFilter : ErrorDiffusionAlgorithm
{
public BurkesFilter(uint R, uint G, uint B) : base(3, 5, 2)
{
KR = R;
KG = G;
KB = B;
Weigths[1, 3] = 8;
Weigths[1, 4] = 8;
Weigths[2, 0] = 2;
Weigths[2, 1] = 4;
Weigths[2, 2] = 8;
Weigths[2, 3] = 4;
Weigths[2, 4] = 2;
for (int i = 0; i < Heigth; i++)
for (int j = 0; j < Width; j++)
Weigths[i, j] = Weigths[i, j] / 32;
}
}
}
|
using EducationManual.Interfaces;
using EducationManual.Models;
using System;
namespace EducationManual.Repositories
{
public class UnitOfWork : IUnitOfWork, IDisposable
{
private ApplicationContext db;
private GenericRepository<School> schoolRepository;
private GenericRepository<Classroom> classroomRepository;
private IUserRepository userManager;
public UnitOfWork()
{
db = new ApplicationContext();
}
public IGenericRepository<School> Schools
{
get
{
if (schoolRepository == null)
schoolRepository = new GenericRepository<School>(db);
return schoolRepository;
}
}
public IGenericRepository<Classroom> Classrooms
{
get
{
if (classroomRepository == null)
classroomRepository = new GenericRepository<Classroom>(db);
return classroomRepository;
}
}
public IUserRepository UserManager
{
get
{
if (userManager == null)
userManager = new UserRepository(db);
return userManager;
}
}
public void Save()
{
db.SaveChanges();
}
private bool disposed = false;
public virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
db.Dispose();
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
} |
using AutoMapper;
using CheckMySymptoms.Forms.Parameters.Common;
using CheckMySymptoms.Forms.View.Common;
using System;
using System.Collections.Generic;
namespace CheckMySymptoms.AutoMapperProfiles
{
public class CommonParametersMappingProfile : Profile
{
public CommonParametersMappingProfile()
{
CreateMap<AboutFormSettingsParameters, AboutFormSettingsView>().ReverseMap();
CreateMap<AggregateDefinitionParameters, AggregateDefinitionView>().ReverseMap();
CreateMap<AggregateTemplateFieldsParameters, AggregateTemplateFieldsView>().ReverseMap();
CreateMap<AggregateTemplateParameters, AggregateTemplateView>().ReverseMap();
CreateMap<CellListTemplateParameters, CellListTemplateView>().ReverseMap();
CreateMap<CellTemplateParameters, CellTemplateView>().ReverseMap();
CreateMap<ColumnSettingsParameters, ColumnSettingsView>().ReverseMap();
CreateMap<CommandColumnParameters, CommandColumnView>().ReverseMap();
CreateMap<ConditionGroupParameters, ConditionGroupView>().ReverseMap();
CreateMap<ConditionParameters, ConditionView>().ReverseMap();
CreateMap<ContentTemplateParameters, ContentTemplateView>().ReverseMap();
CreateMap<DataRequestStateParameters, DataRequestStateView>().ReverseMap();
CreateMap<DetailDropDownTemplateParameters, DetailDropDownTemplateView>().ReverseMap();
CreateMap<DetailFieldSettingParameters, DetailFieldSettingView>().ReverseMap();
CreateMap<DetailFieldTemplateParameters, DetailFieldTemplateView>().ReverseMap();
CreateMap<DetailFormSettingsParameters, DetailFormSettingsView>().ReverseMap();
CreateMap<DetailGroupSettingsParameters, DetailGroupSettingsView>().ReverseMap();
CreateMap<DetailGroupTemplateParameters, DetailGroupTemplateView>().ReverseMap();
CreateMap<DetailListSettingsParameters, DetailListSettingsView>().ReverseMap();
CreateMap<DetailListTemplateParameters, DetailListTemplateView>().ReverseMap();
CreateMap<DirectiveArgumentParameters, DirectiveArgumentView>().ReverseMap();
CreateMap<DirectiveDescriptionParameters, DirectiveDescriptionView>().ReverseMap();
CreateMap<DirectiveParameters, DirectiveView>().ReverseMap();
CreateMap<DomainRequestParameters, DomainRequestView>().ReverseMap();
CreateMap<DropDownTemplateParameters, DropDownTemplateView>().ReverseMap();
CreateMap<DummyConstructor, DummyConstructor>().ReverseMap();
CreateMap<EditFormSettingsParameters, EditFormSettingsView>().ReverseMap();
CreateMap<FilterDefinitionParameters, FilterDefinitionView>().ReverseMap();
CreateMap<FilterGroupParameters, FilterGroupView>().ReverseMap();
CreateMap<FilterTemplateParameters, FilterTemplateView>().ReverseMap();
CreateMap<FlowCompleteParameters, FlowCompleteView>().ReverseMap();
CreateMap<FormControlSettingsParameters, FormControlSettingsView>().ReverseMap();
CreateMap<FormGroupArraySettingsParameters, FormGroupArraySettingsView>().ReverseMap();
CreateMap<FormGroupSettingsParameters, FormGroupSettingsView>().ReverseMap();
CreateMap<FormGroupTemplateParameters, FormGroupTemplateView>().ReverseMap();
CreateMap<FormValidationSettingParameters, FormValidationSettingView>().ReverseMap();
CreateMap<GridSettingsParameters, GridSettingsView>().ReverseMap();
CreateMap<GroupParameters, GroupView>().ReverseMap();
CreateMap<HtmlPageSettingsParameters, HtmlPageSettingsView>().ReverseMap();
CreateMap<MessageTemplateParameters, MessageTemplateView>().ReverseMap();
CreateMap<MultiSelectFormControlSettingsParameters, MultiSelectFormControlSettingsView>().ReverseMap();
CreateMap<MultiSelectTemplateParameters, MultiSelectTemplateView>().ReverseMap();
CreateMap<RequestDetailsParameters, RequestDetailsView>().ReverseMap();
CreateMap<SelectParameters, SelectView>().ReverseMap();
CreateMap<SortParameters, SortView>().ReverseMap();
CreateMap<TextFieldTemplateParameters, TextFieldTemplateView>().ReverseMap();
CreateMap<ValidationMessageParameters, ValidationMessageView>().ReverseMap();
CreateMap<ValidationMethodParameters, ValidationMethodView>().ReverseMap();
CreateMap<ValidatorArgumentParameters, ValidatorArgumentView>().ReverseMap();
CreateMap<ValidatorDescriptionParameters, ValidatorDescriptionView>().ReverseMap();
CreateMap<VariableDirectivesParameters, VariableDirectivesView>().ReverseMap();
}
}
} |
using System;
using System.IO;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
namespace Common.Graphics.FrameBuffer
{
public class FrameBufferManager
{
#region main framebuffer
public int MainDepthMapBufferObject { get; set; }
public int MainDepthMapBufferTextureId { get; set; }
public int MainRenderBufferObject { get; set; }
public int AttrVertexFrameLocation { get; set; }
public int AttrTexcoordFrameLocation { get; set; }
public int UniformTextureFrame { get; set; }
public int vertexBufferForFrameAddress;
public int texCoordsForFrameAddress;
public int MainFrameBufferProgramId { get; set; }
#endregion
#region auxillary framebuffer
public int SecondDepthMapBufferObject { get; set; }
public int SecondDepthMapBufferTextureId { get; set; }
public int SecondRenderBufferObject { get; set; }
public int AttrVertexFrameSecondLocation { get; set; }
public int AttrTexcoordFrameSecondLocation { get; set; }
public int UniformTextureFrameSecond { get; set; }
public int vertexBufferForFrameSecondAddress;
public int texCoordsForFrameSecondAddress;
public int SecondFrameBufferProgramId { get; set; }
#endregion
public int Width { get; set; }
public int Height { get; set; }
public bool DebugDepth { get; set; }
public int FrameBufferProgramId { get; private set; }
public FrameBufferManager(int width, int height)
{
Width = width;
Height = height;
CreateFrameBufferProgram();
CreateMainFrameBuffer();
CreateSecondFrameBuffer();
}
private void CreateMainFrameBuffer()
{
MainFrameBufferProgramId = FrameBufferProgramId;
var frameBufDesc = FrameBufferDesc.GetMainFrameBuffer(Width, Height);
MainDepthMapBufferObject = frameBufDesc.FramBufferObject;
MainDepthMapBufferTextureId = frameBufDesc.TextureId;
MainRenderBufferObject = frameBufDesc.RenderBufferObject;
GL.UseProgram(MainFrameBufferProgramId);
AttrVertexFrameLocation = GL.GetAttribLocation(MainFrameBufferProgramId, "vPosition");
AttrTexcoordFrameLocation = GL.GetAttribLocation(MainFrameBufferProgramId, "vTexCoordinate");
UniformTextureFrame = GL.GetUniformLocation(MainFrameBufferProgramId, "uTexture");
GL.GenBuffers(1, out texCoordsForFrameAddress);
GL.GenBuffers(1, out vertexBufferForFrameAddress);
}
private FrameBufferDesc CreateSecondFrameBuffer()
{
FrameBufferDesc frameBufDesc = FrameBufferDesc.GetFrameBuffer(Width, Height);
SecondDepthMapBufferObject = frameBufDesc.FramBufferObject;
SecondDepthMapBufferTextureId = frameBufDesc.TextureId;
CreateFrameBufferProgram();
GL.UseProgram(SecondFrameBufferProgramId);
AttrVertexFrameLocation = GL.GetAttribLocation(SecondFrameBufferProgramId, "vPosition");
AttrTexcoordFrameLocation = GL.GetAttribLocation(SecondFrameBufferProgramId, "vTexCoordinate");
UniformTextureFrame = GL.GetUniformLocation(SecondFrameBufferProgramId, "uTexture");
GL.GenBuffers(1, out texCoordsForFrameSecondAddress);
GL.GenBuffers(1, out vertexBufferForFrameSecondAddress);
return frameBufDesc;
}
public void EnableAuxillaryFrameBuffer()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, SecondDepthMapBufferObject);
GL.Viewport(0, 0, Width, Height);
}
public void FlushAuxillaryFrameBuffer()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
}
public void EnableMainFrameBuffer()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, MainDepthMapBufferObject);
GL.Viewport(0, 0, Width, Height);
}
public void FlushMainFrameBuffer()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
GL.Disable(EnableCap.DepthTest);
GL.ClearColor(1, 0f, 0f, 0);
GL.Clear(ClearBufferMask.ColorBufferBit);
GL.UseProgram(MainFrameBufferProgramId);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferForFrameAddress);
var points = GetFrameBufferVertices();
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(6 * Vector2.SizeInBytes), points, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(AttrVertexFrameLocation, 2, VertexAttribPointerType.Float, false, 0, 0);
GL.EnableVertexAttribArray(AttrVertexFrameLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, texCoordsForFrameAddress);
var texCoords = GetFrameBufferTextureCoords();
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(6 * Vector2.SizeInBytes), texCoords, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(AttrTexcoordFrameLocation, 2, VertexAttribPointerType.Float, false, 0, 0);
GL.EnableVertexAttribArray(AttrTexcoordFrameLocation);
GL.ActiveTexture(TextureUnit.Texture0);
GL.Uniform1(UniformTextureFrame, 0);
if (DebugDepth)
{
GL.BindTexture(TextureTarget.Texture2D, SecondDepthMapBufferTextureId);
}
else
{
GL.BindTexture(TextureTarget.Texture2D, MainDepthMapBufferTextureId);
}
GL.DrawArrays(PrimitiveType.Triangles, 0, 6);
GL.BindVertexArray(0);
GL.Flush();
}
public void CreateFrameBufferProgram()
{
var programId = GL.CreateProgram();
var vertexShader = GL.CreateShader(ShaderType.VertexShader);
using (var rd = new StreamReader(@"Assets\Shaders\frameBufferVertex.glsl"))
{
string text = rd.ReadToEnd();
GL.ShaderSource(vertexShader, text);
}
GL.CompileShader(vertexShader);
GL.AttachShader(programId, vertexShader);
int statusCode;
GL.GetShader(vertexShader, ShaderParameter.CompileStatus, out statusCode);
if (statusCode != 1)
{
string info;
GL.GetShaderInfoLog(vertexShader, out info);
throw new Exception("vertex shader" + info);
}
var fragmentShader = GL.CreateShader(ShaderType.FragmentShader);
using (var rd = new StreamReader(@"Assets\Shaders\farameBufferFragment.glsl"))
{
string text = rd.ReadToEnd();
GL.ShaderSource(fragmentShader, text);
}
GL.CompileShader(fragmentShader);
GL.AttachShader(programId, fragmentShader);
GL.GetShader(fragmentShader, ShaderParameter.CompileStatus, out statusCode);
if (statusCode != 1)
{
string info;
GL.GetShaderInfoLog(fragmentShader, out info);
throw new Exception("fragment shader: " + info);
}
GL.LinkProgram(programId);
FrameBufferProgramId = programId;
}
private Vector2[] GetFrameBufferVertices()
{
return quadVertices;
}
private Vector2[] GetFrameBufferTextureCoords()
{
return textQuadIndices;
}
private readonly Vector2[] textQuadIndices = new[] {
new Vector2(0.0f, 1.0f),
new Vector2(0.0f, 0.0f),
new Vector2(1.0f, 0.0f),
new Vector2(0.0f, 1.0f),
new Vector2(1.0f, 0.0f),
new Vector2(1.0f, 1.0f)
};
private readonly Vector2[] quadVertices = new[] {
// Positions
new Vector2(-1.0f, 1.0f),
new Vector2(-1.0f, -1.0f),
new Vector2(1.0f, -1.0f),
new Vector2(-1.0f, 1.0f),
new Vector2( 1.0f, -1.0f),
new Vector2(1.0f, 1.0f),
};
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using W3ChampionsStatisticService.Ports;
namespace W3ChampionsStatisticService.Clans
{
[ApiController]
[Route("api/memberships")]
public class MembershipController : ControllerBase
{
private readonly IClanRepository _clanRepository;
public MembershipController(
IClanRepository clanRepository)
{
_clanRepository = clanRepository;
}
[HttpGet("{membershipId}")]
public async Task<IActionResult> GetMembership(string membershipId)
{
var memberShip = await _clanRepository.LoadMemberShip(membershipId);
return Ok(memberShip);
}
}
} |
//////////////////////////////////////////////////////////////////////////
///This software is provided to you as-is and with not warranties!!!
///Use this software at your own risk.
///This software is Copyright by Scott Smith 2006
///You are free to use this software as you see fit.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
namespace MAX.USPS
{
public class Package
{
public Package()
{
_LabelType = LabelType.FullLabel;
_LabelImageType = LabelImageType.TIF;
_ServiceType = ServiceType.First_Class;
}
private LabelType _LabelType;
public LabelType LabelType
{
get { return _LabelType; }
set { _LabelType = value; }
}
private Address _FromAddress = new Address();
public Address FromAddress
{
get { return _FromAddress; }
set { _FromAddress = value; }
}
private Address _ToAddress = new Address();
public Address ToAddress
{
get { return _ToAddress; }
set { _ToAddress = value; }
}
private int _WeightInOunces = 0;
public int WeightInOunces
{
get { return _WeightInOunces; }
set { _WeightInOunces = value; }
}
private ServiceType _ServiceType;
public ServiceType ServiceType
{
get { return _ServiceType; }
set { _ServiceType = value; }
}
private bool _SeparateReceiptPage = false;
public bool SeparateReceiptPage
{
get { return _SeparateReceiptPage; }
set { _SeparateReceiptPage = value; }
}
private string _OriginZipcode = "";
public string OriginZipcode
{
get { return _OriginZipcode; }
set { _OriginZipcode = value; }
}
private LabelImageType _LabelImageType = LabelImageType.TIF;
public LabelImageType LabelImageType
{
get { return _LabelImageType; }
set { _LabelImageType = value; }
}
private DateTime _ShipDate = DateTime.Now;
public DateTime ShipDate
{
get { return _ShipDate; }
set { _ShipDate = value; }
}
private string _ReferenceNumber = "";
public string ReferenceNumber
{
get { return _ReferenceNumber; }
set { _ReferenceNumber = value; }
}
private bool _AddressServiceRequested = false;
public bool AddressServiceRequested
{
get { return _AddressServiceRequested; }
set { _AddressServiceRequested = value; }
}
private byte[] _ShippingLabel;
public byte[] ShippingLabel
{
get { return _ShippingLabel; }
set { _ShippingLabel = value; }
}
private PackageType _PackageType;
public PackageType PackageType
{
get { return _PackageType; }
set { _PackageType = value; }
}
private PackageSize _PackageSize;
public PackageSize PackageSize
{
get { return _PackageSize; }
set { _PackageSize = value; }
}
}
public enum PackageType {None, Flat_Rate_Envelope, Flat_Rate_Box};
public enum PackageSize { None, Regular, Large, Oversize};
public enum LabelImageType{TIF, PDF, None};
public enum ServiceType{Priority, First_Class, Parcel_Post, Bound_Printed_Matter, Media_Mail, Library_Mail};
public enum LabelType{FullLabel = 1, DeliveryConfirmationBarcode = 2};
}
|
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Persistence;
namespace Infrastructure.Security
{
public class IsHostRequirement : IAuthorizationRequirement
{
}
public class IsHostRequirementHandler : AuthorizationHandler<IsHostRequirement>
{
private readonly DataContext _dataContext;
private readonly IHttpContextAccessor _httpContextAccessor;
public IsHostRequirementHandler(DataContext dataContext, IHttpContextAccessor httpContextAccessor)
{
this._dataContext = dataContext;
this._httpContextAccessor = httpContextAccessor;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, IsHostRequirement isHostRequirement)
{
var userId = authorizationHandlerContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId == null) return Task.CompletedTask;
var activityId = Guid.Parse(this._httpContextAccessor.HttpContext?.Request.RouteValues
.SingleOrDefault(keyValuePair => keyValuePair.Key == "id").Value?.ToString());
var attendee = this._dataContext.ActivityAttendees.AsNoTracking()
.SingleOrDefaultAsync(activityAttendee => activityAttendee.AppUserId == userId && activityAttendee.ActivityId == activityId).Result;
if (attendee != null && attendee.IsHost)
{
authorizationHandlerContext.Succeed(isHostRequirement);
}
return Task.CompletedTask;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Main : MonoBehaviour
{
public static bool dead;
public static GUIText scoreGT;
public static PrawnWaves prawnWaves;
public static ShrimpWaves shrimpWaves;
public int[] prawnWaveCount = new int[7];
public int[] shrimpWaveCount = new int[6];
public static int pacuCount;
public static int jellyFishCount;
public static int[] prawnKillCount = new int[7];
public static int[] shrimpKillCount = new int[6];
// [0] = Shrimp
// [1] = Prawn
// [2] = Jelly Fish
// [3] = Pacu
public GameObject[] enemies = new GameObject[4];
// Audio
//public AudioSource[] sounds = new AudioSource[6];
public AudioSource bgm;
void Awake()
{
Cursor.visible = false;
}
// Use this for initialization
void Start()
{
Time.timeScale = 1;
/////////////////////////////////
prawnKillCount[0] = 0;
prawnKillCount[1] = 0;
prawnKillCount[2] = 0;
prawnKillCount[3] = 0;
prawnKillCount[4] = 0;
prawnKillCount[5] = 0;
prawnKillCount[6] = 0;
/////////////////////////////////
shrimpKillCount[0] = 0;
shrimpKillCount[1] = 0;
shrimpKillCount[2] = 0;
shrimpKillCount[3] = 0;
shrimpKillCount[4] = 0;
shrimpKillCount[5] = 0;
/////////////////////////////////
/////////////////////////////////
/////////////////////////////////
pacuCount = 0;
jellyFishCount = 0;
/////////////////////////////////
prawnWaveCount[0] = 0;
prawnWaveCount[1] = 0;
prawnWaveCount[2] = 0;
prawnWaveCount[3] = 0;
prawnWaveCount[4] = 0;
prawnWaveCount[5] = 0;
prawnWaveCount[6] = 0;
/////////////////////////////////
shrimpWaveCount[0] = 0;
shrimpWaveCount[1] = 0;
shrimpWaveCount[2] = 0;
shrimpWaveCount[3] = 0;
shrimpWaveCount[4] = 0;
shrimpWaveCount[5] = 0;
// Find a reference to the ScoreCounter GameObject
GameObject scoreGO = GameObject.Find("ScoreCounter");
// Get the GUIText Component of that GameObject
scoreGT = scoreGO.GetComponent<GUIText>();
scoreGT.text = "0";
//sounds[0].Play();
bgm.Play();
StartCoroutine(Shrimp_1());
}
IEnumerator RestartGame()
{
dead = false;
//sounds[0].Stop();
bgm.Stop();
yield return new WaitForSeconds(2.5f);
Application.LoadLevel(Application.loadedLevel);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}
/////////////////////////////////
if (dead)
{
StartCoroutine(RestartGame());
}
else
{
dead = false;
}
//////////SHRIMP_WAVE_1//////////
if (shrimpWaveCount[0] == 6)
{
shrimpWaveCount[0]++;
StopCoroutine(Shrimp_1());
CancelInvoke("ShrimpSpawn_1");
StartCoroutine(Shrimp_2());
}
if (shrimpWaveCount[1] == 6)
{
shrimpWaveCount[1]++;
StopCoroutine(Shrimp_2());
CancelInvoke("ShrimpSpawn_2");
StartCoroutine(Shrimp_3());
}
if (shrimpWaveCount[2] == 6)
{
shrimpWaveCount[2]++;
StopCoroutine(Shrimp_2());
CancelInvoke("ShrimpSpawn_3");
StartCoroutine(Prawn_1());
}
//////////SHRIMP_WAVE_1//////////
/////////////////////////////////
//////////PRAWN_WAVE_2//////////
if (prawnWaveCount[0] == 6)
{
prawnWaveCount[0]++;
StopCoroutine(Prawn_1());
CancelInvoke("PrawnSpawn_1");
StartCoroutine(Prawn_2());
}
if (prawnWaveCount [1] == 6)
{
prawnWaveCount[1]++;
StopCoroutine(Prawn_2());
CancelInvoke("PrawnSpawn_2");
StartCoroutine(Prawn_3());
}
if (prawnWaveCount[2] == 6)
{
prawnWaveCount[2]++;
StopCoroutine(Prawn_3());
CancelInvoke("PrawnSpawn_3");
StartCoroutine(Prawn_4());
}
//////////PRAWN_WAVE_2//////////
/////////////////////////////////
//////////PRAWN_WAVE_3//////////
if (prawnWaveCount[3] == 6)
{
prawnWaveCount[3]++;
StopCoroutine(Prawn_4());
CancelInvoke("PrawnSpawn_4");
StartCoroutine(Prawn_5());
}
if (prawnWaveCount[4] == 6)
{
prawnWaveCount[4]++;
StopCoroutine(Prawn_5());
CancelInvoke("PrawnSpawn_5");
StartCoroutine(JellyFish());
StartCoroutine(Shrimp_4());
}
//////////PRAWN_WAVE_3//////////
/////////////////////////////////
//////////SHRIMP_PRAWN_JELLYFISH_WAVE_4//////////
if (shrimpWaveCount[3] == 6)
{
shrimpWaveCount[3]++;
StopCoroutine(Shrimp_4());
CancelInvoke("ShrimpSpawn_4");
StartCoroutine(Prawn_6());
StartCoroutine(Shrimp_5());
}
if (shrimpWaveCount[4] == 6)
{
shrimpWaveCount[4]++;
StopCoroutine(Prawn_6());
StopCoroutine(Shrimp_5());
CancelInvoke("PrawnSpawn_6");
CancelInvoke("ShrimpSpawn_5");
StartCoroutine(JellyFish());
StartCoroutine(Prawn_7());
StartCoroutine(Shrimp_6());
}
if (shrimpWaveCount[5] == 6)
{
shrimpWaveCount[5]++;
StopCoroutine(Prawn_7());
StopCoroutine(Shrimp_6());
CancelInvoke("PrawnSpawn_7");
CancelInvoke("ShrimpSpawn_6");
StartCoroutine(Pacu());
}
//////////SHRIMP_PRAWN_JELLYFISH_WAVE_4//////////
/////////////////////////////////
//////////PACU_WAVE_5//////////
if (pacuCount == 1)
{
pacuCount++;
StopCoroutine(Pacu());
}
//////////PACU_WAVE_5//////////
}
//////////SHRIMP_SPAWNING//////////
IEnumerator Shrimp_1()
{
// Increase this later to 3
yield return new WaitForSeconds(1);
shrimpWaves = ShrimpWaves.wave_1;
InvokeRepeating("ShrimpSpawn_1", 1, 0.5f);
}
IEnumerator Shrimp_2()
{
yield return new WaitForSeconds(2);
shrimpWaves = ShrimpWaves.wave_2;
InvokeRepeating("ShrimpSpawn_2", 1, 0.5f);
}
IEnumerator Shrimp_3()
{
yield return new WaitForSeconds(2);
shrimpWaves = ShrimpWaves.wave_3;
InvokeRepeating("ShrimpSpawn_3", 1, 0.5f);
}
IEnumerator Shrimp_4()
{
yield return new WaitForSeconds(2);
shrimpWaves = ShrimpWaves.wave_1;
InvokeRepeating("ShrimpSpawn_4", 1, 0.5f);
}
IEnumerator Shrimp_5()
{
yield return new WaitForSeconds(2);
shrimpWaves = ShrimpWaves.wave_2;
InvokeRepeating("ShrimpSpawn_5", 1, 0.5f);
}
IEnumerator Shrimp_6()
{
yield return new WaitForSeconds(2);
shrimpWaves = ShrimpWaves.wave_3;
InvokeRepeating("ShrimpSpawn_6", 1, 0.5f);
}
/////////////////////////////////
void ShrimpSpawn_1()
{
GameObject shrimp1 = Instantiate(enemies[0], new Vector3(15, 5, 0), Quaternion.identity);
shrimp1.tag = "Shrimp_1";
shrimpWaveCount[0]++;
}
void ShrimpSpawn_2()
{
GameObject shrimp2 = Instantiate(enemies[0], new Vector3(15, 5, 0), Quaternion.identity);
shrimp2.tag = "Shrimp_2";
shrimpWaveCount[1]++;
}
void ShrimpSpawn_3()
{
GameObject shrimp3 = Instantiate(enemies[0], new Vector3(15, 5, 0), Quaternion.identity);
shrimp3.tag = "Shrimp_3";
shrimpWaveCount[2]++;
}
void ShrimpSpawn_4()
{
GameObject shrimp4 = Instantiate(enemies[0], new Vector3(15, 5, 0), Quaternion.identity);
shrimp4.tag = "Shrimp_4";
shrimpWaveCount[3]++;
}
void ShrimpSpawn_5()
{
GameObject shrimp5 = Instantiate(enemies[0], new Vector3(15, 5, 0), Quaternion.identity);
shrimp5.tag = "Shrimp_5";
shrimpWaveCount[4]++;
}
void ShrimpSpawn_6()
{
GameObject shrimp6 = Instantiate(enemies[0], new Vector3(15, 5, 0), Quaternion.identity);
shrimp6.tag = "Shrimp_6";
shrimpWaveCount[5]++;
}
//////////SHRIMP_SPAWNING//////////
/////////////////////////////////
//////////PRAWNS_SPAWNING//////////
IEnumerator Prawn_1()
{
yield return new WaitForSeconds(3);
prawnWaves = PrawnWaves.wave_1;
InvokeRepeating("PrawnSpawn_1", 1, 0.5f);
}
IEnumerator Prawn_2()
{
yield return new WaitForSeconds(1);
prawnWaves = PrawnWaves.wave_2;
InvokeRepeating("PrawnSpawn_2", 1, 0.5f);
}
IEnumerator Prawn_3()
{
yield return new WaitForSeconds(1);
prawnWaves = PrawnWaves.wave_3;
InvokeRepeating("PrawnSpawn_3", 1, 0.5f);
}
IEnumerator Prawn_4()
{
yield return new WaitForSeconds(5);
prawnWaves = PrawnWaves.wave_4;
InvokeRepeating("PrawnSpawn_4", 1, 0.5f);
}
IEnumerator Prawn_5()
{
yield return new WaitForSeconds(0);
prawnWaves = PrawnWaves.wave_5;
InvokeRepeating("PrawnSpawn_5", 1, 0.5f);
}
IEnumerator Prawn_6()
{
yield return new WaitForSeconds(0);
prawnWaves = PrawnWaves.wave_4;
InvokeRepeating("PrawnSpawn_6", 1, 0.5f);
}
IEnumerator Prawn_7()
{
yield return new WaitForSeconds(0);
prawnWaves = PrawnWaves.wave_5;
InvokeRepeating("PrawnSpawn_7", 1, 0.5f);
}
/////////////////////////////////
void PrawnSpawn_1()
{
GameObject prawn1 = Instantiate(enemies[1], new Vector3(-12, 9, 0), Quaternion.identity);
prawn1.tag = "Prawn_1";
prawnWaveCount[0]++;
}
void PrawnSpawn_2()
{
GameObject prawn2 = Instantiate(enemies[1], new Vector3(15, 0, 0), Quaternion.identity);
prawn2.tag = "Prawn_2";
prawnWaveCount[1]++;
}
void PrawnSpawn_3()
{
GameObject prawn3 = Instantiate(enemies[1], new Vector3(-12, -9, 0), Quaternion.identity);
prawn3.tag = "Prawn_3";
prawnWaveCount[2]++;
}
void PrawnSpawn_4()
{
GameObject prawn4 = Instantiate(enemies[1], new Vector3(15, 10, 0), Quaternion.identity);
prawn4.tag = "Prawn_4";
prawnWaveCount[3]++;
}
void PrawnSpawn_5()
{
GameObject prawn5 = Instantiate(enemies[1], new Vector3(15, -10, 0), Quaternion.identity);
prawn5.tag = "Prawn_5";
prawnWaveCount[4]++;
}
void PrawnSpawn_6()
{
GameObject prawn6 = Instantiate(enemies[1], new Vector3(15, -10, 0), Quaternion.identity);
prawn6.tag = "Prawn_6";
prawnWaveCount[5]++;
}
void PrawnSpawn_7()
{
GameObject prawn7 = Instantiate(enemies[1], new Vector3(15, -10, 0), Quaternion.identity);
prawn7.tag = "Prawn_7";
prawnWaveCount[6]++;
}
//////////PRAWNS_SPAWNING//////////
//////////JELLYFISH_SPAWNING//////////
IEnumerator JellyFish()
{
yield return new WaitForSeconds(2);
InvokeRepeating("SpawnJellyFish", 1, 5);
InvokeRepeating("SpawnJellyFish2", 2, 5);
InvokeRepeating("SpawnJellyFish3", 4, 5);
InvokeRepeating("SpawnJellyFish4", 2, 5);
InvokeRepeating("SpawnJellyFish5", 3, 5);
yield return new WaitForSeconds(20);
CancelInvoke("SpawnJellyFish");
CancelInvoke("SpawnJellyFish2");
CancelInvoke("SpawnJellyFish3");
CancelInvoke("SpawnJellyFish4");
CancelInvoke("SpawnJellyFish5");
}
/////////////////////////////////
void SpawnJellyFish()
{
GameObject jFish = Instantiate(enemies[2], new Vector3(1.5f, -9, 0), Quaternion.identity);
jFish.GetComponent<Animator>().SetTrigger("JellyFish");
}
void SpawnJellyFish2()
{
GameObject jFish2 = Instantiate(enemies[2], new Vector3(-6, -9, 0), Quaternion.identity);
jFish2.GetComponent<Animator>().SetTrigger("JellyFish2");
}
void SpawnJellyFish3()
{
GameObject jFish3 = Instantiate(enemies[2], new Vector3(8,-9,0), Quaternion.identity);
jFish3.GetComponent<Animator>().SetTrigger("JellyFish3");
}
void SpawnJellyFish4()
{
GameObject jFish4 = Instantiate(enemies[2], new Vector3(2, -9, 0), Quaternion.identity);
jFish4.GetComponent<Animator>().SetTrigger("JellyFish4");
}
void SpawnJellyFish5()
{
GameObject jFish5 = Instantiate(enemies[2], new Vector3(4, -9, 0), Quaternion.identity);
jFish5.GetComponent<Animator>().SetTrigger("JellyFish5");
}
//////////JELLYFISH_SPAWNING//////////
/////////////////////////////////
//////////PACU_SPAWNING//////////
IEnumerator Pacu()
{
yield return new WaitForSeconds(12);
SpawnPacu();
}
/////////////////////////////////
void SpawnPacu()
{
GameObject pacu = Instantiate(enemies[3], new Vector3(17, 4, 0), Quaternion.identity);
}
//////////PACU_SPAWNING//////////
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.WebHost.ContainerManagement;
using Microsoft.Azure.WebJobs.Script.WebHost.Management;
using Microsoft.Azure.WebJobs.Script.WebHost.Models;
using Microsoft.Azure.WebJobs.Script.WebHost.Security;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.WebJobs.Script.Tests;
using Moq;
using Newtonsoft.Json;
using Xunit;
using static Microsoft.Azure.WebJobs.Script.EnvironmentSettingNames;
namespace Microsoft.Azure.WebJobs.Script.Tests.Integration.ContainerManagement
{
[Trait(TestTraits.Category, TestTraits.EndToEnd)]
[Trait(TestTraits.Group, TestTraits.ContainerInstanceTests)]
public class LinuxContainerInitializationHostServiceTests : IDisposable
{
private const string ContainerStartContextUri = "https://containerstartcontexturi";
private readonly Mock<IInstanceManager> _instanceManagerMock;
public LinuxContainerInitializationHostServiceTests()
{
_instanceManagerMock = new Mock<IInstanceManager>(MockBehavior.Strict);
}
[Fact]
public async Task Runs_In_Linux_Container_Mode_Only()
{
// These settings being null will cause IsLinuxContainerEnvironment to return false.
var environmentMock = new Mock<IEnvironment>(MockBehavior.Strict);
environmentMock.Setup(env => env.GetEnvironmentVariable(ContainerName)).Returns<string>(null);
environmentMock.Setup(env => env.GetEnvironmentVariable(AzureWebsiteInstanceId)).Returns<string>(null);
var initializationHostService = new LinuxContainerInitializationHostService(environmentMock.Object, _instanceManagerMock.Object, NullLogger<LinuxContainerInitializationHostService>.Instance);
await initializationHostService.StartAsync(CancellationToken.None);
// Make sure no other environment variables were checked
environmentMock.Verify(env => env.GetEnvironmentVariable(It.Is<string>(p => p != ContainerName && p != AzureWebsiteInstanceId)), Times.Never);
}
[Fact]
public async Task Assigns_Context_From_CONTAINER_START_CONTEXT()
{
var containerEncryptionKey = TestHelpers.GenerateKeyHexString();
var hostAssignmentContext = GetHostAssignmentContext();
var encryptedHostAssignmentContext = GetEncryptedHostAssignmentContext(hostAssignmentContext, containerEncryptionKey);
var serializedContext = JsonConvert.SerializeObject(new { encryptedContext = encryptedHostAssignmentContext });
var vars = new Dictionary<string, string>
{
{ ContainerStartContext, serializedContext },
{ ContainerEncryptionKey, containerEncryptionKey },
};
// Enable Linux Container
AddLinuxContainerSettings(vars);
_instanceManagerMock.Setup(manager => manager.StartAssignment(It.Is<HostAssignmentContext>(context => hostAssignmentContext.Equals(context)), It.Is<bool>(w => !w))).Returns(true);
var environment = new TestEnvironment(vars);
var initializationHostService = new LinuxContainerInitializationHostService(environment, _instanceManagerMock.Object, NullLogger<LinuxContainerInitializationHostService>.Instance);
await initializationHostService.StartAsync(CancellationToken.None);
_instanceManagerMock.Verify(manager => manager.StartAssignment(It.Is<HostAssignmentContext>(context => hostAssignmentContext.Equals(context)), It.Is<bool>(w => !w)), Times.Once);
}
[Fact]
public async Task Assigns_Context_From_CONTAINER_START_CONTEXT_SAS_URI_If_CONTAINER_START_CONTEXT_Absent()
{
var containerEncryptionKey = TestHelpers.GenerateKeyHexString();
var hostAssignmentContext = GetHostAssignmentContext();
var encryptedHostAssignmentContext = GetEncryptedHostAssignmentContext(hostAssignmentContext, containerEncryptionKey);
var serializedContext = JsonConvert.SerializeObject(new { encryptedContext = encryptedHostAssignmentContext });
var vars = new Dictionary<string, string>
{
{ ContainerStartContextSasUri, ContainerStartContextUri },
{ ContainerEncryptionKey, containerEncryptionKey },
};
AddLinuxContainerSettings(vars);
var environment = new TestEnvironment(vars);
var initializationHostService = new Mock<LinuxContainerInitializationHostService>(MockBehavior.Strict, environment, _instanceManagerMock.Object, NullLogger<LinuxContainerInitializationHostService>.Instance);
initializationHostService.Setup(service => service.Read(ContainerStartContextUri))
.Returns(Task.FromResult(serializedContext));
_instanceManagerMock.Setup(manager => manager.StartAssignment(It.Is<HostAssignmentContext>(context => hostAssignmentContext.Equals(context)), It.Is<bool>(w => !w))).Returns(true);
using (var env = new TestScopedEnvironmentVariable(vars))
{
await initializationHostService.Object.StartAsync(CancellationToken.None);
}
_instanceManagerMock.Verify(manager => manager.StartAssignment(It.Is<HostAssignmentContext>(context => hostAssignmentContext.Equals(context)), It.Is<bool>(w => !w)), Times.Once);
}
[Fact]
public async Task Does_Not_Assign_If_Context_Not_Available()
{
var vars = new Dictionary<string, string>();
AddLinuxContainerSettings(vars);
var environment = new TestEnvironment(vars);
var initializationHostService = new LinuxContainerInitializationHostService(environment, _instanceManagerMock.Object, NullLogger<LinuxContainerInitializationHostService>.Instance);
await initializationHostService.StartAsync(CancellationToken.None);
_instanceManagerMock.Verify(manager => manager.StartAssignment(It.IsAny<HostAssignmentContext>(), It.Is<bool>(w => !w)), Times.Never);
}
private static string GetEncryptedHostAssignmentContext(HostAssignmentContext hostAssignmentContext, string containerEncryptionKey)
{
using (var env = new TestScopedEnvironmentVariable(WebSiteAuthEncryptionKey, containerEncryptionKey))
{
var serializeObject = JsonConvert.SerializeObject(hostAssignmentContext);
return SimpleWebTokenHelper.Encrypt(serializeObject);
}
}
private static HostAssignmentContext GetHostAssignmentContext()
{
var hostAssignmentContext = new HostAssignmentContext();
hostAssignmentContext.SiteId = 1;
hostAssignmentContext.SiteName = "sitename";
hostAssignmentContext.LastModifiedTime = DateTime.UtcNow.Add(TimeSpan.FromMinutes(new Random().Next()));
hostAssignmentContext.Environment = new Dictionary<string, string>();
hostAssignmentContext.Environment.Add(AzureWebsiteAltZipDeployment, "https://zipurl.zip");
return hostAssignmentContext;
}
private static void AddLinuxContainerSettings(IDictionary<string, string> existing)
{
existing[AzureWebsiteInstanceId] = string.Empty;
existing[ContainerName] = "ContainerName";
}
public void Dispose()
{
_instanceManagerMock.Reset();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class halfPoint : MonoBehaviour {
[Header("Asign Objects")]
public GameObject player1;
public GameObject player2;
public Transform startPosiiton;
[Header("Ajustable Variables")]
[Space(10)]
[Range(0, 1)]
public float amount;
public Vector2 adusjtableHeight;
CameraMouvement cameraMouvement;
Vector3 pos1;
Vector3 pos2;
Vector3 posStart;
Vector3 midPointPosPlayer;
Camera cam;
public GameObject midPointObject;
private void Start()
{
cameraMouvement = FindObjectOfType<CameraMouvement>();
cam = Camera.main;
posStart = startPosiiton.position;
}
void Update () {
if(player1 != null || player2 != null || midPointObject != null)
{
if (midPointObject)
{
pos2 = player2.transform.position;
pos1 = player1.transform.position;
midPointPosPlayer = ((pos1 + pos2) / 2);
Vector3 midPointPosPlayerWithHeightChange = new Vector3 (midPointPosPlayer.x, midPointPosPlayer.y, midPointPosPlayer.z);
Vector3 newPos = new Vector3(startPosiiton.position.x, startPosiiton.position.y, startPosiiton.position.z);
Vector2 posToGo = new Vector3(adusjtableHeight.x + posStart.y, adusjtableHeight.y + posStart.y);
if (cameraMouvement.direction)
{
newPos.y = posToGo.x;
}
else
{
newPos.y = posToGo.y;
}
startPosiiton.position = newPos;
Vector3 finalPosition = ((midPointPosPlayer * amount) / 2) + startPosiiton.position;
midPointObject.transform.position = Vector3.Lerp(midPointObject.transform.position, finalPosition, Time.deltaTime * 5);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using NewParser.classes;
using NewParser.Models;
namespace NewParser
{
public class Parser
{
private readonly BookInfoEntities _dbContext= new BookInfoEntities();
private double _currectItem = 1;
private double _maxItem = 1;
private bool CurrentStepCompleted;
private List<string> contentList;
private IEnumerable<string> urlList;
//public IEnumerable<Book> AllWorker(List<string> contentList)
//{
// var books = new List<Book>();
// var bookUrls = new List<string>();
// foreach (var content in contentList)
// {
// bookUrls.AddRange(SelecrUrl(content));
// }
// contentList.Clear();
// foreach (var bookUrl in bookUrls)
// {
// string urlContents = GetURLContents (bookUrl);
// contentList.Add(urlContents);
// }
// foreach (var content in contentList)
// {
// books.Add(Parse(content));
// }
// return books;
//}
private string GetURLContents (string url)
{
var webReq = (HttpWebRequest)WebRequest.Create(url);
using (WebResponse response = webReq.GetResponse ())
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
var responseJson = sr.ReadToEnd();
return responseJson;
}
}
}
public async Task<Book> Parse(string content, string url, int id)
{
lock (this)
{
try
{
var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.OptionFixNestedTags = true;
htmlDoc.LoadHtml(content);
if (htmlDoc.DocumentNode != null)
{
var mainNode = htmlDoc.DocumentNode.SelectSingleNode("//div[@class='singlecolumnminwidth']");
if (mainNode != null)
{
var _image = "";
var _Name = "";
var _Author = "";
var _Comments = new int();
var _Price = new double();
var _BestSellersRank = new int();
var _Categories = "";
var _PublicationDate = new DateTime();
HtmlNode workNode = null;
//Image
workNode = mainNode.SelectSingleNode("//img[@id='main-image']");
if (workNode != null) _image = workNode.Attributes["src"].Value;
// Name
workNode = mainNode.SelectSingleNode("//span[@id='btAsinTitle']");
if (workNode != null) _Name = workNode.ChildNodes[0].InnerText;
// Author
workNode = mainNode.SelectSingleNode("//div[@class='buying']/span");
if (workNode != null) _Author = workNode.InnerHtml.ParseAuthor();
// Comments
workNode = mainNode.SelectSingleNode("//div[@class='fl gl5 mt3 txtnormal acrCount']/a");
if (workNode != null) _Comments = workNode.ChildNodes[0].InnerText.ParseCount();
// Price
workNode = mainNode.SelectSingleNode("//b[@class='priceLarge']");
if (workNode != null) _Price = workNode.InnerText.ParsePrice();
// Amazon Best Sellers Rank
workNode = mainNode.SelectSingleNode("//li[@id='SalesRank']");
if (workNode != null) _BestSellersRank = workNode.InnerText.ParseRank();
// Categories
// select ul with categories
workNode = mainNode.SelectSingleNode("//ul[@class='zg_hrsr']");
IEnumerable<Category> cont = null;
if (workNode != null)
cont = from li in workNode.Descendants("li")
from span in li.Descendants("span")
from a in span.Descendants("a")
select new Category { Name = a.InnerText };
// list for cont (context)
var categories = new List<string>();
// adding items from cont to list
if (cont != null)
foreach (var item in cont.Where(item => !categories.Contains(item.Name)))
{
categories.Add(item.Name);
}
// Publication Data
workNode = mainNode.SelectSingleNode("//input[@id='pubdate']");
if (workNode != null) _PublicationDate = workNode.OuterHtml.ParseDate();
//new book
var book = new Book()
{
Image = _image,
Name = _Name,
Author = _Author,
BestSellersRank = _BestSellersRank,
Comments = _Comments,
Price = _Price,
PublicationDate = _PublicationDate,
Category_Id = id,
Url = url
};
// return book
return book;
}
}
}
catch (Exception e)
{
}
}
return null;
}
public async Task<List<string>> SelecrUrl(string content)
{
var htmlDoc = new HtmlDocument { OptionFixNestedTags = true };
htmlDoc.LoadHtml(content);
if (htmlDoc.DocumentNode != null)
{
HtmlNode mainNode = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='zg_centerListWrapper']");
if (mainNode != null)
{
var nodes = mainNode.SelectNodes("//div[@class='zg_title']");
var cont = from a in nodes.Descendants("a") select a.Attributes["href"].Value.Replace("\n", "");
var bookURLs = new List<string>();
// adding items from cont to list
foreach (var item in cont.Where(item => !bookURLs.Contains(item)))
{
bookURLs.Add(item);
}
return bookURLs;
}
}
return new List<string>();
}
public List<string> LoadData (IEnumerable<string> urlList)
{
var contentList = new List<string>();
try
{
foreach (var url in urlList)
{
var urlContents = GetURLContents (url);
contentList.Add(urlContents);
urlContents = string.Empty;
urlContents = GetURLContents (url + "#2");
contentList.Add(urlContents);
urlContents = string.Empty;
urlContents = GetURLContents (url + "#3");
contentList.Add(urlContents);
urlContents = string.Empty;
urlContents = GetURLContents (url + "#4");
contentList.Add(urlContents);
urlContents = string.Empty;
urlContents = GetURLContents (url + "#5");
contentList.Add(urlContents);
urlContents = string.Empty;
}
}
catch{}
return contentList;
}
}
}
|
using NTShop.Data.Infrastructure;
using NTShop.Model.Models;
namespace NTShop.Data.Reponsitories
{
public interface ITagRepository : IReponsitory<Tag> { }
public class TagRepository : RepositoryBase<Tag>, ITagRepository
{
public TagRepository(IDbFactory dbFactory) : base(dbFactory)
{
}
}
} |
using System;
using System.IO;
namespace TweetLib.Core.Utils{
public static class UrlUtils{
private const string TwitterTrackingUrl = "t.co";
public enum CheckResult{
Invalid, Tracking, Fine
}
public static CheckResult Check(string url){
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)){
string scheme = uri.Scheme;
if (scheme == Uri.UriSchemeHttps || scheme == Uri.UriSchemeHttp || scheme == Uri.UriSchemeFtp || scheme == Uri.UriSchemeMailto){
return uri.Host == TwitterTrackingUrl ? CheckResult.Tracking : CheckResult.Fine;
}
}
return CheckResult.Invalid;
}
public static string? GetFileNameFromUrl(string url){
string file = Path.GetFileName(new Uri(url).AbsolutePath);
return string.IsNullOrEmpty(file) ? null : file;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using EntityFramework.Extensions;
using SO.Urba.Models.ValueObjects;
using SO.Urba.DbContexts;
using SO.Urba.Managers.Base;
using SO.Utility.Classes;
using SO.Utility.Models.ViewModels;
using SO.Utility;
using SO.Utility.Helpers;
using SO.Utility.Extensions;
using System.Data.Entity.SqlServer;
namespace SO.Urba.Managers
{
public class ClientManager : ClientManagerBase
{
public ClientManager()
{
}
/// <summary>
/// Find Client Full name - need for client drop down
/// </summary>
public string getContactName(int? id = null)
{
using (var db = new MainDb())
{
var query = db.clients
.Include(i => i.contactInfo)
.FirstOrDefault(p => p.clientId == id);
var fullName = query.contactInfo.fullname;
if (id == null)
return "All Clients";
else
return fullName;
}
}
//
public SearchFilterVm clientListExport(SearchFilterVm input)
{
int keywordInt = 0;
int.TryParse(input.keyword, out keywordInt);
using (var db = new MainDb())
{
var query = db.clients
.Include(i => i.contactInfo)
//.Include(o => o.clientOrganizationLookupses)
.Include(a => a.clientOrganizationLookupses.Select(c => c.organization))
.OrderByDescending(b => b.created)
.Where(e => (input.isActive == null || e.isActive == input.isActive)
&&
(e.contactInfo!=null && (
string.IsNullOrEmpty(input.keyword)==true
|| e.contactInfo.firstName.Contains(input.keyword)
|| e.contactInfo.lastName.Contains(input.keyword)
|| e.contactInfo.address.Contains(input.keyword)
|| e.contactInfo.city.Contains(input.keyword)
|| e.contactInfo.state.Contains(input.keyword)
|| e.contactInfo.homePhone.Contains(input.keyword)
|| e.contactInfo.workPhone.Contains(input.keyword)
|| (keywordInt > 0 && e.clientId == keywordInt)
)));
input.result = query.ToList<object>();
if (input.result.Count() != 0)
{
var items = new List<object>();
items.Add(
new
{
h1 = "ID",
h2 = "Client Name",
h3 = "Address",
h4 = "Work Phone",
h5 = "Fee Has Paid",
h6 = "Organization"
});
var item1 = query.Select(i =>
new
{
ID = i.clientId,
Client_Name = i.contactInfo.firstName + " " + i.contactInfo.lastName,
Address = i.contactInfo.address + ", " + i.contactInfo.city
+ " " + i.contactInfo.state + " " + i.contactInfo.zip,
Work_Phone = i.contactInfo.workPhone,
HasPaidFee = (i.hasPaidFee == null ? "N/A" : (i.hasPaidFee == true ? "Yes" : "No")),
Organization = i.clientOrganizationLookupses.Select(c=>c.organization.name).ToList()
}).ToList<dynamic>();
foreach (var j in item1)
{
items.Add((object)
new
{
ID = j.ID,
Client_Name = j.Client_Name,
Address = j.Address,
Work_Phone = j.Work_Phone,
HasPaidFee = j.HasPaidFee,
Organization = string.Join(", ", j.Organization)
});
}
input.result = items;
}
return input;
}
}
}
}
|
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using MouseJumpUI.Drawing.Models;
using MouseJumpUI.NativeMethods.Core;
using MouseJumpUI.NativeWrappers;
namespace MouseJumpUI.Helpers;
internal static class DrawingHelper
{
public static LayoutInfo CalculateLayoutInfo(
LayoutConfig layoutConfig)
{
if (layoutConfig is null)
{
throw new ArgumentNullException(nameof(layoutConfig));
}
var builder = new LayoutInfo.Builder
{
LayoutConfig = layoutConfig,
};
builder.ActivatedScreen = layoutConfig.ScreenBounds[layoutConfig.ActivatedScreen];
// work out the maximum *constrained* form size
// * can't be bigger than the activated screen
// * can't be bigger than the max form size
var maxFormSize = builder.ActivatedScreen.Size
.Intersect(layoutConfig.MaximumFormSize);
// the drawing area for screen images is inside the
// form border and inside the preview border
var maxDrawingSize = maxFormSize
.Shrink(layoutConfig.FormPadding)
.Shrink(layoutConfig.PreviewPadding);
// scale the virtual screen to fit inside the drawing bounds
var scalingRatio = layoutConfig.VirtualScreen.Size
.ScaleToFitRatio(maxDrawingSize);
// position the drawing bounds inside the preview border
var drawingBounds = layoutConfig.VirtualScreen.Size
.ScaleToFit(maxDrawingSize)
.PlaceAt(layoutConfig.PreviewPadding.Left, layoutConfig.PreviewPadding.Top);
// now we know the size of the drawing area we can work out the preview size
builder.PreviewBounds = drawingBounds.Enlarge(layoutConfig.PreviewPadding);
// ... and the form size
// * center the form to the activated position, but nudge it back
// inside the visible area of the activated screen if it falls outside
builder.FormBounds = builder.PreviewBounds.Size
.PlaceAt(0, 0)
.Enlarge(layoutConfig.FormPadding)
.Center(layoutConfig.ActivatedLocation)
.Clamp(builder.ActivatedScreen);
// now calculate the positions of each of the screen images on the preview
builder.ScreenBounds = layoutConfig.ScreenBounds
.Select(
screen => screen
.Offset(layoutConfig.VirtualScreen.Location.Size.Negate())
.Scale(scalingRatio)
.Offset(layoutConfig.PreviewPadding.Left, layoutConfig.PreviewPadding.Top))
.ToList();
return builder.Build();
}
/// <summary>
/// Resize and position the specified form.
/// </summary>
public static void PositionForm(
Form form, RectangleInfo formBounds)
{
// note - do this in two steps rather than "this.Bounds = formBounds" as there
// appears to be an issue in WinForms with dpi scaling even when using PerMonitorV2,
// where the form scaling uses either the *primary* screen scaling or the *previous*
// screen's scaling when the form is moved to a different screen. i've got no idea
// *why*, but the exact sequence of calls below seems to be a workaround...
// see https://github.com/mikeclayton/FancyMouse/issues/2
var bounds = formBounds.ToRectangle();
form.Location = bounds.Location;
_ = form.PointToScreen(Point.Empty);
form.Size = bounds.Size;
}
/// <summary>
/// Draw the preview background.
/// </summary>
public static void DrawPreviewBackground(
Graphics previewGraphics, RectangleInfo previewBounds, IEnumerable<RectangleInfo> screenBounds)
{
using var backgroundBrush = new LinearGradientBrush(
previewBounds.Location.ToPoint(),
previewBounds.Size.ToPoint(),
Color.FromArgb(13, 87, 210), // light blue
Color.FromArgb(3, 68, 192)); // darker blue
// it's faster to build a region with the screen areas excluded
// and fill that than it is to fill the entire bounding rectangle
var backgroundRegion = new Region(previewBounds.ToRectangle());
foreach (var screen in screenBounds)
{
backgroundRegion.Exclude(screen.ToRectangle());
}
previewGraphics.FillRegion(backgroundBrush, backgroundRegion);
}
public static void EnsureDesktopDeviceContext(ref HWND desktopHwnd, ref HDC desktopHdc)
{
if (desktopHwnd.IsNull)
{
desktopHwnd = User32.GetDesktopWindow();
}
if (desktopHdc.IsNull)
{
desktopHdc = User32.GetWindowDC(desktopHwnd);
}
}
public static void FreeDesktopDeviceContext(ref HWND desktopHwnd, ref HDC desktopHdc)
{
if (!desktopHwnd.IsNull && !desktopHdc.IsNull)
{
_ = User32.ReleaseDC(desktopHwnd, desktopHdc);
}
desktopHwnd = HWND.Null;
desktopHdc = HDC.Null;
}
/// <summary>
/// Checks if the device context handle exists, and creates a new one from the
/// Graphics object if not.
/// </summary>
public static void EnsurePreviewDeviceContext(Graphics previewGraphics, ref HDC previewHdc)
{
if (previewHdc.IsNull)
{
previewHdc = new HDC(previewGraphics.GetHdc());
_ = Gdi32.SetStretchBltMode(previewHdc, MouseJumpUI.NativeMethods.Gdi32.STRETCH_BLT_MODE.STRETCH_HALFTONE);
}
}
/// <summary>
/// Free the specified device context handle if it exists.
/// </summary>
public static void FreePreviewDeviceContext(Graphics previewGraphics, ref HDC previewHdc)
{
if ((previewGraphics is not null) && !previewHdc.IsNull)
{
previewGraphics.ReleaseHdc(previewHdc.Value);
previewHdc = HDC.Null;
}
}
/// <summary>
/// Draw placeholder images for any non-activated screens on the preview.
/// Will release the specified device context handle if it needs to draw anything.
/// </summary>
public static void DrawPreviewPlaceholders(
Graphics previewGraphics, IEnumerable<RectangleInfo> screenBounds)
{
// we can exclude the activated screen because we've already draw
// the screen capture image for that one on the preview
if (screenBounds.Any())
{
var brush = Brushes.Black;
previewGraphics.FillRectangles(brush, screenBounds.Select(screen => screen.ToRectangle()).ToArray());
}
}
/// <summary>
/// Draws screen captures from the specified desktop handle onto the target device context.
/// </summary>
public static void DrawPreviewScreen(
HDC sourceHdc,
HDC targetHdc,
RectangleInfo sourceBounds,
RectangleInfo targetBounds)
{
var source = sourceBounds.ToRectangle();
var target = targetBounds.ToRectangle();
_ = Gdi32.StretchBlt(
targetHdc,
target.X,
target.Y,
target.Width,
target.Height,
sourceHdc,
source.X,
source.Y,
source.Width,
source.Height,
MouseJumpUI.NativeMethods.Gdi32.ROP_CODE.SRCCOPY);
}
/// <summary>
/// Draws screen captures from the specified desktop handle onto the target device context.
/// </summary>
public static void DrawPreviewScreens(
HDC sourceHdc,
HDC targetHdc,
IList<RectangleInfo> sourceBounds,
IList<RectangleInfo> targetBounds)
{
for (var i = 0; i < sourceBounds.Count; i++)
{
var source = sourceBounds[i].ToRectangle();
var target = targetBounds[i].ToRectangle();
_ = Gdi32.StretchBlt(
targetHdc,
target.X,
target.Y,
target.Width,
target.Height,
sourceHdc,
source.X,
source.Y,
source.Width,
source.Height,
MouseJumpUI.NativeMethods.Gdi32.ROP_CODE.SRCCOPY);
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Microsoft.DotNet.Interactive.App.Lsp
{
public static class LspSerializer
{
public static readonly JsonSerializerSettings JsonSerializerSettings;
public static JsonSerializer JsonSerializer { get; }
static LspSerializer()
{
JsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Newtonsoft.Json.Formatting.None,
MissingMemberHandling = MissingMemberHandling.Error,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};
JsonSerializerSettings.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy()));
JsonSerializer = JsonSerializer.Create(JsonSerializerSettings);
}
}
}
|
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 sales_management_system
{
public partial class 商品登録_変更 : Form
{
public 商品登録_変更()
{
InitializeComponent();
LoadCMBData();
cmb_publisher.SelectedIndex = -1;
cmb_author.SelectedIndex = -1;
cmb_genre.SelectedIndex = -1;
cmb_category.SelectedIndex = -1;
}
public 商品登録_変更(string productName,
string publisherName,
int stock,
int price,
int genka,
string author,
string genre,
string catagory,
DateTime publicationDate,
bool isActive)
{
InitializeComponent();
LoadCMBData();
txt_product_name.Text = productName;
cmb_publisher.Text = publisherName;
mtb_stock.Text = stock.ToString();
mtb_price.Text = price.ToString();
mtb_genka.Text = genka.ToString();
cmb_author.Text = author;
cmb_genre.Text = genre;
cmb_category.Text = catagory;
mtb_publication_date.Text = publicationDate.ToString("yyyy/MM/dd");
if (isActive)
{
rdo_active.Checked = true;
}
else
{
rdo_no_active.Checked = true;
}
}
private void LoadCMBData()
{
this.ジャンルテーブルTableAdapter.Fill(this._システム開発演習_KT_22DataSet.ジャンルテーブル);
this.カテゴリーテーブルTableAdapter.Fill(this._システム開発演習_KT_22DataSet.カテゴリーテーブル);
this.著者テーブルTableAdapter.Fill(this._システム開発演習_KT_22DataSet.著者テーブル);
this.出版社テーブルTableAdapter.Fill(this._システム開発演習_KT_22DataSet.出版社テーブル);
}
}
}
|
using AutoMapper;
using ImmedisHCM.Data.Infrastructure;
using ImmedisHCM.Services.Core;
using ImmedisHCM.Services.Identity;
using ImmedisHCM.Web.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace ImmedisHCM.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddNHibernateSessionFactory(Configuration.GetConnectionString("ImmedisHCMWebContextConnection"));
services.AddNHibernateIdentity();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Account/Login";
options.LogoutPath = $"/Account/Logout";
options.AccessDeniedPath = $"/Account/AccessDenied";
});
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped(typeof(IRepository<>), typeof(Repository<>))
.AddScoped(typeof(IAccountService), typeof(AccountService))
.AddScoped(typeof(IAccountManageService), typeof(AccountManageService))
.AddScoped(typeof(IManagerService), typeof(ManagerService))
.AddScoped(typeof(IAdminService), typeof(AdminService))
.AddScoped(typeof(IUnitOfWork), typeof(UnitOfWork))
.AddScoped(typeof(IIdentitySeeder), typeof(IdentitySeeder))
.AddScoped(typeof(INomenclatureService), typeof(NomenclatureService))
.AddScoped(typeof(IDatabaseSeeder), typeof(DatabaseSeeder));
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IIdentitySeeder identitySeeder,
IDatabaseSeeder databaseSeeder)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
identitySeeder.Seed();
//Identity seeder needs to be run first so roles and admin are seeded
databaseSeeder.Seed();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using frameWork.view.viewInterface;
namespace frameWork.commonInterface
{
interface IUIManagerDelegate
{
void addPanel(IViewController viewController, String viewType);
void createPanel(IViewController viewController, String viewType);
void removePanel(IViewController viewController, String viewType);
}
}
|
using System.Text.Json.Serialization;
namespace ZenHub.Models
{
public class IssueDependency
{
[JsonPropertyName("blocking")]
public IssueDetails Blocking { get; set; }
[JsonPropertyName("blocked")]
public IssueDetails Blocked { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.