text stringlengths 13 6.01M |
|---|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event of type `BoolPair`. Inherits from `AtomEvent<BoolPair>`.
/// </summary>
[EditorIcon("atom-icon-cherry")]
[CreateAssetMenu(menuName = "Unity Atoms/Events/BoolPair", fileName = "BoolPairEvent")]
public sealed class BoolPairEvent : AtomEvent<BoolPair>
{
}
}
|
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests
{
public class ApimSaveDataRequest
{
public ApimUserInfo UserInfo { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.IO;
using System.Threading;
public partial class _Pregledi : System.Web.UI.Page
{
protected int _mat_kartica_stetje = 0;
protected int _zal_lokacije_stetje = 0;
protected int _mat_kartica_fifo_stetje = 0;
protected string msg = "";
protected void Page_Load(object sender, EventArgs e)
{
try
{
Master.SelectedBox = "Pregledi";
Master.Title = "Pregledi";
if (!Master.Uporabnik.Pravice.Contains("pregled")) throw new Exception("Nimate pravice!");
msg = Request.QueryString["msg"] ?? "";
//_mat_kartica_stetje = Opravila.Get(Master.Uporabnik.StoreID,0,101).Rows.Count;
if (!string.IsNullOrWhiteSpace(msg)) Master.SetMessage(msg);
}
catch (Exception ee)
{
Master.SetMessage(ee);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PlanMGMT.Converter
{
public class StatusToBtnContentConverter : System.Windows.Data.IValueConverter//此接口有以下两个方法
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return "";
switch ((short)value)
{
case 0:
return "开始";
case 1:
return "结束";
default:
return "结束";
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BudgetApp.WebUI.Models;
using System.Text;
namespace BudgetApp.WebUI.HtmlHelpers
{
public static class HtmlLinkHelper
{
public static MvcHtmlString LinkHelper(this HtmlHelper helper, LedgerListModel listModel, Func<int, string> links)
{
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= listModel.NumberOfLinks; i++)
{
TagBuilder tagBuilder = new TagBuilder("a");
tagBuilder.MergeAttribute("href", links(i));
tagBuilder.InnerHtml = "" + i;
builder.Append(tagBuilder.ToString());
builder.Append(" ");
}
return MvcHtmlString.Create(builder.ToString());
}
}
} |
using System.Collections.Generic;
using System.Linq;
using Taggart.Data;
namespace Taggart
{
public static class TrackLibraryDbSaver
{
public static void Save(string fileName, ITrackLibrary library)
{
using (var db = new TrackLibraryContext())
{
var libraryRecord = db.Libraries.Where(x => x.File == fileName).FirstOrDefault();
if (libraryRecord == null)
{
libraryRecord = new Data.Models.Library
{
Name = library.Name,
File = fileName,
Version = library.Version
};
db.Libraries.Add(libraryRecord);
db.SaveChanges();
}
var chunkSize = 100;
var chunkNumber = 0;
var chunkCount = 0;
do
{
var trackChunk = library.Tracks.Skip(chunkSize * chunkNumber++).Take(chunkSize).ToArray();
var trackIds = trackChunk.Select(x => x.TrackId).ToArray();
var newTrackRecords = new List<Data.Models.Track>();
var trackRecords = db.Tracks.Where(x => x.LibraryId == libraryRecord.LibraryId && trackIds.Contains(x.ExternalId)).ToDictionary(x => x.ExternalId);
foreach (var track in trackChunk)
{
if (!trackRecords.ContainsKey(track.TrackId))
{
var trackRecord = new Data.Models.Track
{
LibraryId = libraryRecord.LibraryId,
ExternalId = track.TrackId,
Name = track.Name,
Location = track.FileName,
//Key = track.ke
Artist = track.Artist
};
trackRecord.MetaData = track.Properties.Select(x => new Data.Models.TrackMetaData
{
Name = x.Key,
Value = x.Value
}).ToList();
trackRecord.CuePoints = track.CuePoints?.Select(x => new Data.Models.CuePoint
{
Number = x.Number,
StartTime = x.Time
}).ToList();
newTrackRecords.Add(trackRecord);
}
else
{
// Update track
}
}
db.Tracks.AddRange(newTrackRecords);
db.SaveChanges();
} while (chunkCount == chunkSize);
}
}
}
}
|
using System;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; //this is where JObject comes from. JObject is .NET object that can be treated as JSON
using System.Collections.Generic;
using ConsoleApiCall;
namespace ApiTest
{
class Program
{
static void Main()
{
var apiCallTask = ApiHelper.ApiCall("Ws7xotfERIVKDMORGlCVhlmsfcoy8xKB");
var result = apiCallTask.Result;
JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(result);
List<Article> articleList = JsonConvert.DeserializeObject<List<Article>>(jsonResponse["results"].ToString()); //DeserializeObject used to create list of articles. this method grabs JSON keys in the response that match properties in Article class. Properties names need to match JSON keys.
foreach (Article article in articleList)
{
Console.WriteLine($"Section: {article.Section}");
Console.WriteLine($"Title: {article.Title}");
Console.WriteLine($"Abstract: {article.Abstract}");
Console.WriteLine($"Url: {article.Url}");
Console.WriteLine($"Byline: {article.Byline}");
}
}
//CODE BELOW WAS USED TO SHOW RESULT IN CONSOLE AS API RESULT
// static void Main(string[] args)
// {
// var apiCallTask = ApiHelper.ApiCall("Ws7xotfERIVKDMORGlCVhlmsfcoy8xKB");//this variable takes the returned Task from the async function in the ApiHelper class below. .We than call the ApiCall method and pass our api key in
// //using code below we turn giant string stored as result into JSON data.
// var result = apiCallTask.Result;
// JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(result); //this is where the conversion happens.
// Console.WriteLine(jsonResponse["results"]);
// }
}
class ApiHelper
{
public static async Task<string> ApiCall(string apiKey) //whenever e method is declared as async we need to return a Task type
{
RestClient client = new RestClient("https://api.nytimes.com/svc/topstories/v2"); //we instantiate the RestSharp.RestClient object and in it we store the connection. We call this variable client.
RestRequest request = new RestRequest($"home.json?api-key={apiKey}", Method.GET);
var response = await client.ExecuteTaskAsync(request); //ExecuteTAskAsync is RestClient's method
return response.Content; //returns Content of response variable
}
}
} |
#nullable enable
namespace PluralKit.Core
{
public class GroupPatch: PatchObject
{
public Partial<string> Name { get; set; }
public Partial<string?> DisplayName { get; set; }
public Partial<string?> Description { get; set; }
public Partial<string?> Icon { get; set; }
public Partial<PrivacyLevel> DescriptionPrivacy { get; set; }
public Partial<PrivacyLevel> IconPrivacy { get; set; }
public Partial<PrivacyLevel> ListPrivacy { get; set; }
public Partial<PrivacyLevel> Visibility { get; set; }
public override UpdateQueryBuilder Apply(UpdateQueryBuilder b) => b
.With("name", Name)
.With("display_name", DisplayName)
.With("description", Description)
.With("icon", Icon)
.With("description_privacy", DescriptionPrivacy)
.With("icon_privacy", IconPrivacy)
.With("list_privacy", ListPrivacy)
.With("visibility", Visibility);
}
} |
using System.Collections.Generic;
using System.Linq;
namespace ipScan.Base.IP
{
class ListIPInfo : List<IPInfo>
{
public ListIPInfo() : base()
{
}
public string[] toArray()
{
string[] result = new string[this.Count()];
int i = 0;
foreach (IPInfo element in this)
{
result[i] = element.toString();
i++;
}
return result;
}
public new ListIPInfo GetRange(int index, int count)
{
ListIPInfo result = new ListIPInfo();
result.AddRange(base.GetRange(index, count));
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Admin_Payments_View : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Helper.ValidateAdmin();
if (!IsPostBack)
{
GetPayments(txtSearch.Text);
}
this.Form.DefaultButton = this.btnSearch.UniqueID;
}
private void GetPayments(string txtSearchText)
{
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
if (ddlPaymentStatus.SelectedValue == "All Status")
{
cmd.CommandText = @"SELECT ContactFirstName, ContactLastName,
EventAddress, DownPayment, Balance, Total, Status,
Payments.DateAdded
FROM Payments
INNER JOIN Bookings ON Payments.BookingID = Bookings.BookingID
INNER JOIN Clients ON Bookings.ClientID = Clients.ClientID
WHERE
(ContactFirstName LIKE @keyword OR
ContactLastName LIKE @keyword OR
EventAddress LIKE @keyword) ORDER BY DateAdded DESC";
}
else
{
cmd.CommandText = @"SELECT ContactFirstName, ContactLastName,
EventAddress, DownPayment, Balance, Total, Status,
Payments.DateAdded
FROM Payments
INNER JOIN Bookings ON Payments.BookingID = Bookings.BookingID
INNER JOIN Clients ON Bookings.ClientID = Clients.ClientID
WHERE
(ContactFirstName LIKE @keyword OR
ContactLastName LIKE @keyword OR
EventAddress LIKE @keyword) AND
Payments.Status = @status ORDER BY DateAdded DESC";
}
cmd.Parameters.AddWithValue("@status", ddlPaymentStatus.SelectedValue);
cmd.Parameters.AddWithValue("@keyword", "%" + txtSearchText + "%");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Close();
da.Fill(ds, "Payments");
lvPayments.DataSource = ds;
lvPayments.DataBind();
}
}
protected void ddlPaymentStatus_OnSelectedIndexChanged(object sender, EventArgs e)
{
GetPayments(txtSearch.Text);
}
protected void txtSearch_OnTextChanged(object sender, EventArgs e)
{
GetPayments(txtSearch.Text);
}
protected void btnSearch_OnClick(object sender, EventArgs e)
{
GetPayments(txtSearch.Text);
}
protected void lvPayments_OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
dpPayments.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
GetPayments(txtSearch.Text);
}
protected void lvPayments_OnDataBound(object sender, EventArgs e)
{
dpPayments.Visible = dpPayments.PageSize < dpPayments.TotalRowCount;
}
} |
using Microsoft.EntityFrameworkCore;
using SocialMedia.Infrastructure.Core;
using SocialMedia.Infrastructure.Data.Configurations;
using System.Reflection;
namespace SocialMedia.Infrastructure.Data
{
public partial class SocialMediaContext : DbContext
{
public SocialMediaContext()
{
}
public SocialMediaContext(DbContextOptions<SocialMediaContext> options)
: base(options)
{
}
public virtual DbSet<Comment> Comments { get; set; }
public virtual DbSet<Post> Posts { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<AspnetApplications> AspnetApplication { get; set; }
public virtual DbSet<AspnetMembership> AspnetMembership { get; set; }
public virtual DbSet<AspnetPaths> AspnetPath { get; set; }
public virtual DbSet<AspnetPersonalizationAllUsers> AspnetPersonalizationAllUser { get; set; }
public virtual DbSet<AspnetPersonalizationPerUser> AspnetPersonalizationPerUsers { get; set; }
public virtual DbSet<AspnetProfile> AspnetProfiles { get; set; }
public virtual DbSet<AspnetRoles> AspnetRole { get; set; }
public virtual DbSet<AspnetSchemaVersions> AspnetSchemaVersion { get; set; }
public virtual DbSet<AspnetUsers> AspnetUser { get; set; }
public virtual DbSet<AspnetUsersInRoles> AspnetUsersInRole { get; set; }
public virtual DbSet<AspnetWebEventEvents> AspnetWebEventEvent { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}
}
|
using Alabo.Domains.Dtos;
using Alabo.Domains.Entities;
using Alabo.Domains.UnitOfWork;
using Alabo.Validations.Aspects;
namespace Alabo.Domains.Services.Add {
/// <summary>
/// 创建操作
/// </summary>
public interface IAdd<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> {
/// <summary>
/// 创建
/// </summary>
/// <param name="request">创建参数</param>
[UnitOfWork]
bool Add<TRequest>([Valid] TRequest request) where TRequest : IRequest, new();
/// <summary>
/// 添加单个实体
/// </summary>
/// <param name="model"></param>
bool Add([Valid] TEntity model);
}
} |
using EddiDataDefinitions;
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class DisembarkEvent : Event
{
public const string NAME = "Disembark";
public const string DESCRIPTION = "Triggered when you transition from a ship or SRV to on foot";
public const string SAMPLE = "{ \"timestamp\":\"2021-05-03T21:47:38Z\", \"event\":\"Disembark\", \"SRV\":false, \"Taxi\":false, \"Multicrew\":false, \"ID\":6, \"StarSystem\":\"Firenses\", \"SystemAddress\":2868635379121, \"Body\":\"Roberts Gateway\", \"BodyID\":44, \"OnStation\":true, \"OnPlanet\":false, \"StationName\":\"Roberts Gateway\", \"StationType\":\"Coriolis\", \"MarketID\":3221636096 }";
[PublicAPI("The name of the star system where the commander is disembarking")]
public string systemname { get; }
[PublicAPI("The name of the body where the commander is disembarking (if any)")]
public string bodyname { get; private set; }
[PublicAPI("The name of the station where the commander is disembarking (if any)")]
public string station { get; private set; }
[PublicAPI("The type of station where the commander is disembarking (if any)")]
public string stationtype => (stationModel ?? StationModel.None).localizedName;
[PublicAPI("True if disembarking from another player's ship")]
public bool frommulticrew { get; }
[PublicAPI("True if disembarking from your own ship")]
public bool fromship => fromLocalId != null && !fromsrv && !fromtransport && !frommulticrew;
[PublicAPI("True if disembarking from an SRV")]
public bool fromsrv { get; }
[PublicAPI("True if disembarking from a transport ship (e.g. taxi or dropship)")]
public bool fromtransport { get; }
[PublicAPI("True if disembarking to a station")]
public bool? onstation { get; }
[PublicAPI("True if disembarking to a planet")]
public bool? onplanet { get; }
// Not intended to be user facing
public int? fromLocalId { get; }
public ulong systemAddress { get; }
public int? bodyId { get; }
public long? marketId { get; }
public StationModel stationModel { get; }
public DisembarkEvent(DateTime timestamp, bool fromSRV, bool fromTransport, bool fromMultiCrew, int? fromLocalId, string system, ulong systemAddress, string body, int? bodyId, bool? onStation, bool? onPlanet, string station = null, long? marketId = null, StationModel stationModel = null) : base(timestamp, NAME)
{
this.fromsrv = fromSRV;
this.fromtransport = fromTransport;
this.frommulticrew = fromMultiCrew;
this.fromLocalId = fromLocalId;
this.systemname = system;
this.systemAddress = systemAddress;
this.bodyname = body;
this.bodyId = bodyId;
this.onstation = onStation;
this.onplanet = onPlanet;
this.station = station;
this.marketId = marketId;
this.stationModel = stationModel;
}
}
} |
namespace NFramework.DBTool.Common
{
#region Reference
using System;
#endregion
/// <summary>
/// 主键生成器,用于通用主键生成方法定义
/// </summary>
public class KeyGenerator
{
/// <summary>
/// 生成一个GUID,去除了-,并全部转为小写
/// </summary>
/// <returns>返回一个去除了-并全部转为小写的GUID字符串</returns>
public static string GenNewGuidKey()
{
return Guid.NewGuid().ToString("N");
}
}
}
|
using System.Collections.Generic;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Domain.Prf.Sources;
namespace Profiling2.Domain.Contracts.Tasks
{
public interface IEmailTasks
{
void SendRequestSentForFinalDecisionEmail(string username, int requestId);
void SendRequestSentForValidationEmail(string username, int requestId);
void SendPersonsProposedEmail(string username, int requestId);
void SendRespondedToEmail(string username, int requestId);
void SendProfileRequestEmail(string username, Person person);
void SendRequestCompletedEmail(string username, int requestId);
void SendRequestForwardedToConditionalityParticipantsEmail(string username, int requestId);
void SendRequestRejectedEmail(string username, int requestId, string reason);
void SendFeedingSourceUploadedEmail(FeedingSource fs);
void SendFeedingSourcesUploadedEmail(IList<FeedingSource> sources);
void SendFeedingSourceApprovedEmail(FeedingSource fs);
void SendFeedingSourceRejectedEmail(FeedingSource fs);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollaborativeFilteringUI.Core
{
public class DelegateAsyncCommand<T> : DelegateCommand<T> where T : class
{
public DelegateAsyncCommand(Action<T> execute, EventHandler onStarted, EventHandler onEnded)
: base(execute)
{
Started += onStarted;
Ended += onEnded;
}
public DelegateAsyncCommand(Action<T> execute, Predicate<T> canExecute)
: base(execute, canExecute)
{ }
public DelegateAsyncCommand(Action<T> execute)
: base(execute)
{ }
public bool IsExecuting { get; set; }
public event EventHandler Started;
public event EventHandler Ended;
public override bool CanExecute(object parameter)
{
return (base.CanExecute(parameter)) && (!this.IsExecuting);
}
public override void Execute(object parameter)
{
try
{
this.IsExecuting = true;
if (Started != null)
Started(this, EventArgs.Empty);
Task task = Task.Factory.StartNew(() => _execute((T)parameter));
task.ContinueWith(t => OnRunWorkerCompleted(EventArgs.Empty), TaskScheduler.FromCurrentSynchronizationContext());
}
catch(Exception e)
{
}
}
private void OnRunWorkerCompleted(EventArgs e)
{
IsExecuting = false;
if (Ended != null)
Ended(this, e);
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
using jam;
public class City
{
public static float TotalPopulation = 0;
public Population population;
public int Money;
public Economy economy;
public Culture MyCulture;
public Region Region;
public City(float population, Region region, Culture myCulture)
{
TotalPopulation += population;
this.population = new Population(population, new Queue(), new Queue(), 0);
Money = 500;
MyCulture = myCulture;
Region = region;
economy = new Economy((int)(population / Population.p), Money);
}
public void UpdatePerDay(Virus virus)
{
population.Update(virus, Region);
}
public void UpdatePerWeek()
{
float baby = population.Total * 0.0005f;
population.Susceptible += baby;
TotalPopulation += baby;
}
public static float MigrationIntensity(City from, City to)
{
float d = 0.0000001f;
float deltaDensity = from.population.Density /
(from.population.Density + to.population.Density + d);
float deltaInfectious = from.population.SymptomaticDensity /
(from.population.SymptomaticDensity + to.population.SymptomaticDensity + d);
float deltaMoney = to.economy.CurrentMoney /
(from.economy.CurrentMoney + to.economy.CurrentMoney + d);
return deltaInfectious - 0.5f;
//return (deltaMoney + deltaInfectious + deltaDensity) / 3 - 0.5f;
}
} |
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Solution
{
// Complete the countSwaps function below.
static void CountSwaps(int[] a)
{
var numSwaps = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < a.Length - 1; j++)
{
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1])
{
Swap(a, j);
numSwaps++;
}
}
}
var firstElement = a[0];
var lastElement = a[a.Length - 1];
Console.WriteLine($"Array is sorted in {numSwaps} swaps.");
Console.WriteLine($"First Element: {firstElement}");
Console.WriteLine($"Last Element: {lastElement}");
}
private static void Swap(int[] array, int index)
{
var tmp = array[index];
array[index] = array[index + 1];
array[index + 1] = tmp;
}
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
CountSwaps(a);
}
}
|
using MailKit.Net.Smtp;
using MimeKit;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace EmailSender
{
public class Sender : ISender
{
/// <summary>
/// Sends email containing code.
/// </summary>
/// <param name="type">Code email content type</param>
/// <param name="receiverEmail">Receiver email</param>
/// <param name="code">Code</param>
public async Task SendCodeEmail(ContentType type, string receiverEmail, string code)
{
var content = new HtmlContentProvider(receiverEmail).GetContentWithCode(type, code);
string emailTitle = type == ContentType.ActivateAccount ? "SnowApp - account activation" : "SnowApp - reset password";
await SendEmailAsync(receiverEmail, emailTitle, content);
}
private async Task SendEmailAsync(string email, string subject, string message)
{
var configuration = new ConfigurationProvider().GetCredentials();
var emailMessage = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = message;
emailMessage.From.Add(new MailboxAddress(configuration.DisplayName, configuration.EmailAddress));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
await client.ConnectAsync(configuration.SMTPhost, configuration.SMTPport, false).ConfigureAwait(false);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(configuration.EmailAddress, configuration.Password);
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
//WTF IS THAT http://stackoverflow.com/questions/777607/the-remote-certificate-is-invalid-according-to-the-validation-procedure-using ?
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
else
{
return true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Olive.Data;
using Olive.Data.Uow;
using Olive.Web.MVC.Areas.Administration.ViewModels;
namespace Olive.Web.MVC.Areas.Administration.Controllers
{
public class IngredientsController : AdministrationCRUDController
{
private IUowData db = new UowData();
//
// GET: /Administration/Ingredients/
public ViewResult Index()
{
IngredientsIndexViewModel indexModel = new IngredientsIndexViewModel();
indexModel.AllIngredients = db.Ingredients.All();
indexModel.NewIngredient= new Ingredient();
return View(indexModel);
}
//
// POST: /Administration/Ingredients/Create
[HttpPost]
public ActionResult Create(Ingredient newIngredient)
{
var indexModel = new IngredientsIndexViewModel();
var addIngredient = new Ingredient();
if (ModelState.IsValid)
{
//addSource.SourceID = newSource.SourceID;
addIngredient.Name = newIngredient.Name;
db.Ingredients.Add(addIngredient);
db.SaveChanges();
}
return PartialView("_IngredientPartial", addIngredient);
}
//
// GET: /Administration/Ingredients/Edit/5
public ActionResult Edit(int id)
{
Ingredient ingredient = db.Ingredients.GetById(id);
return PartialView(ingredient);
}
//
// POST: /Administration/Ingredients/Edit/5
[HttpPost]
public ActionResult Edit(Ingredient model, int id)
{
var indexModel = new IngredientsIndexViewModel();
Ingredient ingredient = db.Ingredients.GetById(id);
if (ModelState.IsValid)
{
ingredient.Name = model.Name;
db.Ingredients.Update(ingredient);
db.SaveChanges();
}
//model.SourceID = id;
//return PartialView("_SourcePartial", model);
return Json(new { ingredientID = id, ingredientName = model.Name });
}
//
// GET: /Administration/Ingredients/Delete/5
public ActionResult Delete(int id)
{
Ingredient ingredient = db.Ingredients.GetById(id);
return PartialView(ingredient);
}
//
// POST: /Administration/Ingredients/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Ingredient ingredient = db.Ingredients.GetById(id);
db.Ingredients.Delete(ingredient);
db.SaveChanges();
//return Json(new { id = id });
return Content(id.ToString());
}
}
} |
using UnityEngine;
using UnityEngine.Events;
using System.Collections.Generic;
using System.IO;
namespace Ardunity
{
[AddComponentMenu("ARDUnity/Bridge/Output/RTTTLSong")]
[HelpURL("https://sites.google.com/site/ardunitydoc/references/bridge/rtttlsong")]
public class RTTTLSong : ArdunityBridge, IWireOutput<Trigger>, IWireOutput<int>, IWireOutput<string>
{
private class Note
{
public string name;
public float frequency;
public float time;
}
private class RTTTL
{
public string name;
public List<Note> notes = new List<Note>();
}
public TextAsset songAsset;
public UnityEvent OnEndSong;
private IWireOutput<float> _frequencyOutput;
private bool _playing;
private List<RTTTL> _songs = new List<RTTTL>();
private Trigger _preTrigger;
private int _selection = -1;
private int _index;
private int _noteIndex;
private float _time;
protected override void Awake()
{
base.Awake();
_preTrigger = new Trigger();
_preTrigger.Clear();
LoadRTTTL();
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(_playing)
{
_time -= Time.deltaTime;
if(_time < 0f)
{
_noteIndex++;
if(_noteIndex >= _songs[_index].notes.Count)
{
if(_frequencyOutput != null)
_frequencyOutput.output = 0f;
_playing = false;
OnEndSong.Invoke();
}
else
{
_time = _songs[_index].notes[_noteIndex].time;
if(_frequencyOutput != null)
_frequencyOutput.output = _songs[_index].notes[_noteIndex].frequency;
}
}
}
}
public string[] songs
{
get
{
List<string> list = new List<string>();
for(int i=0; i<_songs.Count; i++)
list.Add(_songs[i].name);
return list.ToArray();
}
}
public void LoadRTTTL()
{
if(songAsset == null)
return;
_selection = -1;
_songs.Clear();
using(StringReader reader = new StringReader(songAsset.text))
{
while(true)
{
string line = reader.ReadLine();
if(line == null)
break;
RTTTL song = new RTTTL();
string[] tokens = line.Split(new char[] { ':' });
if(tokens.Length != 3)
continue;
song.name = tokens[0];
string[] tokens2 = tokens[1].Split(new char[] { ',' });
if(tokens2.Length != 3)
continue;
int duration = 4;
int octave = 6;
int beat = 63;
for(int i=0; i<tokens2.Length; i++)
{
string[] tokens3 = tokens2[i].Split(new char[] { '=' });
if(tokens3.Length == 2)
{
if(tokens3[0].Equals("d") || tokens3[0].Equals("D"))
duration = int.Parse(tokens3[1]);
else if(tokens3[0].Equals("o") || tokens3[0].Equals("O"))
octave = int.Parse(tokens3[1]);
else if(tokens3[0].Equals("b") || tokens3[0].Equals("B"))
beat = int.Parse(tokens3[1]);
}
}
string[] tokens4 = tokens[2].Split(new char[] { ',' });
for(int i=0; i<tokens4.Length; i++)
{
char[] noteSymbol = { 'P', 'p', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'A', 'a', 'B', 'b', 'H', 'h', '#' };
tokens4[i] = tokens4[i].TrimStart(new char[] { ' ' });
tokens4[i] = tokens4[i].TrimEnd(new char[] { ' ' });
bool hasSpecialDuration = false;
int index = tokens4[i].LastIndexOfAny(new char[] { '.' });
if(index >= 0)
{
hasSpecialDuration = true;
tokens4[i] = tokens4[i].Remove(index, 1);
}
int noteDuration = duration;
index = tokens4[i].IndexOfAny(noteSymbol);
if(index < 0)
continue;
if(index > 0)
noteDuration = int.Parse(tokens4[i].Substring(0, index));
int noteOctave = octave;
int index2 = tokens4[i].LastIndexOfAny(noteSymbol);
if(index2 < 0)
continue;
if(index2 < (tokens4[i].Length - 1))
noteOctave = int.Parse(tokens4[i].Substring(index2 + 1));
Note note = new Note();
note.time = 60f / (float)beat * 4f;
note.time /= (float)noteDuration;;
if(hasSpecialDuration)
note.time *= 1.5f;
note.name = tokens4[i].Substring(index, index2 - index + 1);
if(note.name.Equals("P") || note.name.Equals("p"))
note.frequency = 0f;
else if(note.name.Equals("C") || note.name.Equals("c"))
note.frequency = 261.63f;//Hz
else if(note.name.Equals("C#") || note.name.Equals("c#"))
note.frequency = 277.18f;//Hz
else if(note.name.Equals("D") || note.name.Equals("d"))
note.frequency = 293.66f;//Hz
else if(note.name.Equals("D#") || note.name.Equals("d#"))
note.frequency = 311.13f;//Hz
else if(note.name.Equals("E") || note.name.Equals("e"))
note.frequency = 329.63f;//Hz
else if(note.name.Equals("F") || note.name.Equals("f"))
note.frequency = 349.23f;//Hz
else if(note.name.Equals("F#") || note.name.Equals("f#"))
note.frequency = 369.99f;//Hz
else if(note.name.Equals("G") || note.name.Equals("g"))
note.frequency = 392f; //Hz
else if(note.name.Equals("G#") || note.name.Equals("g#"))
note.frequency = 415.3f;//Hz
else if(note.name.Equals("A") || note.name.Equals("a"))
note.frequency = 440f; //Hz
else if(note.name.Equals("A#") || note.name.Equals("a#"))
note.frequency = 466.16f; //Hz
else if(note.name.Equals("B") || note.name.Equals("b"))
note.frequency = 493.88f; //Hz
else
continue;
if(note.frequency != 0)
note.name += noteOctave.ToString();
note.frequency *= Mathf.Pow(2, (noteOctave - 4));
song.notes.Add(note);
}
_songs.Add(song);
}
}
if(_songs.Count > 0)
_selection = 0;
}
public bool isPlaying
{
get
{
return _playing;
}
}
public void SelectSong(int index)
{
if(index >= 0 && index < _songs.Count)
_selection = index;
}
public void SelectSong(string name)
{
for(int i=0; i<_songs.Count; i++)
{
if(_songs[i].name.Equals(name))
{
_selection = i;
return;
}
}
}
public void Play()
{
if(_selection < 0)
return;
_index = _selection;
_noteIndex = 0;
_time = _songs[_index].notes[_noteIndex].time;
if(_frequencyOutput != null)
_frequencyOutput.output = _songs[_index].notes[_noteIndex].frequency;
_playing = true;
}
public void Stop()
{
_playing = false;
if(_frequencyOutput != null)
_frequencyOutput.output = 0f;
}
Trigger IWireOutput<Trigger>.output
{
get
{
return _preTrigger;
}
set
{
if(value.value)
{
if(!_playing)
Play();
else
Stop();
}
_preTrigger = value;
}
}
int IWireOutput<int>.output
{
get
{
return _selection;
}
set
{
SelectSong(value);
}
}
string IWireOutput<string>.output
{
get
{
if(_selection >= 0 && _selection < _songs.Count)
return _songs[_selection].name;
else
return null;
}
set
{
SelectSong(value);
}
}
protected override void AddNode(List<Node> nodes)
{
base.AddNode(nodes);
nodes.Add(new Node("frequency", "Frequency", typeof(IWireOutput<float>), NodeType.WireFrom, "Output<float>"));
nodes.Add(new Node("play", "Play by Trigger", typeof(IWireOutput<Trigger>), NodeType.WireTo, "Output<Trigger>"));
nodes.Add(new Node("selectIndex", "Select by index", typeof(IWireOutput<int>), NodeType.WireTo, "Output<int>"));
nodes.Add(new Node("selectName", "Select by name", typeof(IWireOutput<string>), NodeType.WireTo, "Output<string>"));
}
protected override void UpdateNode(Node node)
{
if(node.name.Equals("frequency"))
{
node.updated = true;
if(node.objectTarget == null && _frequencyOutput == null)
return;
if(node.objectTarget != null)
{
if(node.objectTarget.Equals(_frequencyOutput))
return;
}
_frequencyOutput = node.objectTarget as IWireOutput<float>;;
if(_frequencyOutput == null)
node.objectTarget = null;
return;
}
else if(node.name.Equals("play"))
{
node.updated = true;
return;
}
else if(node.name.Equals("selectIndex"))
{
node.updated = true;
return;
}
else if(node.name.Equals("selectName"))
{
node.updated = true;
return;
}
base.UpdateNode(node);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Utilities;
namespace DotNetNuke.MSBuild.Tasks
{
public class DeleteIISSite : Task
{
private readonly IISManager iisMgr = new IISManager();
public string WebsiteName { get; set; }
public override bool Execute()
{
if (iisMgr.VDirExists(WebsiteName))
{
iisMgr.DeleteVirtualDirectory("localhost", WebsiteName);
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Capa_de_Negocios_ONG_SYS
{
public class VERIFICA_IDENTIFICACION
{
public static bool VerificaIdentificacion(string identificacion)
{
bool estado = false;
char[] valced = new char[13];
int provincia;
if (identificacion.Length >= 10)
{
valced = identificacion.Trim().ToCharArray();
provincia = int.Parse((valced[0].ToString() + valced[1].ToString()));
if (provincia > 0 && provincia < 25)
{
if (int.Parse(valced[2].ToString()) < 6)
{
estado = VerificaCedula(valced);
}
else if (int.Parse(valced[2].ToString()) == 6)
{
estado = VerificaSectorPublico(valced);
}
else if (int.Parse(valced[2].ToString()) == 9)
{
estado = VerificaPersonaJuridica(valced);
}
}
}
return estado;
}
public static bool VerificaSectorPublico(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[9].ToString()) + int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[8] { 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 8; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[8].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static bool VerificaPersonaJuridica(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[9] { 4, 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 9; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[9].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static bool VerificaCedula(char[] validarCedula)
{
int aux = 0, par = 0, impar = 0, verifi;
for (int i = 0; i < 9; i += 2)
{
aux = 2 * int.Parse(validarCedula[i].ToString());
if (aux > 9)
aux -= 9;
par += aux;
}
for (int i = 1; i < 9; i += 2)
{
impar += int.Parse(validarCedula[i].ToString());
}
aux = par + impar;
if (aux % 10 != 0)
{
verifi = 10 - (aux % 10);
}
else
verifi = 0;
if (verifi == int.Parse(validarCedula[9].ToString()))
return true;
else
return false;
}
}
}
|
using EntityLayer.CustomerDetails;
using EntityLayer.Loans;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace EntityLayer.Loans
{
public class RepayLoan
{
public int Id { get; set; }
public DateTime RepaymentDate { get; set; }
[Required]
[Column(TypeName = "decimal(18, 6)")]
public decimal Amount { get; set; }
public string ChequeNumber { get; set; }
public string ChequeBankId { get; set; }
public int TransactionId { get; set; }
public string Notes { get; set; }
public string ReferenceNumber { get; set; }
//Navigation property
public int LoanId { get; set; }
public Loan Loan { get; set; }
public Tenor TenureType { get; set; }
public PaymentMethod PaymentMethod { get; set; }
// Repayloan can be done by a Customer while a
public CustomerProfile CustomerProfile { get; set; }
}
}
|
using Anywhere2Go.Business.Master;
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.Intergration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Anywhere2Go.Business
{
public class PricingLogic
{
public class PricingResponse
{
public float Distance { get; set; }
public float SurveyorPrice { get; set; }
public float InsurerPrice { get; set; }
public string AmphurNameFromGoogle { get; set; }
public string AmphurCode { get; set; }
public string DistrictNameFromGoogle { get; set; }
public string DistrictCode { get; set; }
public string Place { get; set; }
public int ServiceRateId { get; set; }
public int InsurerRateId { get; set; }
public int StatusCode { get; set; }
public ServiceRate ServiceRate { get; set; }
public string ErrorMessage { get; set; }
}
//float _distance;
//ServiceRate _serviceRate;
private MyContext _context = null;
private Task _task = null;
private int TaskProcessStartId = 1003;
private int TaskProcessEndId = 1004;
// 1003 เริ่มงาน/กำลังเดินทาง
// 1004 ถึงที่เกิดเหตุ/ปฏิบัติงาน
public PricingLogic(Task task)
{
_task = task;
}
public PricingLogic()
{
_context = new MyContext();
}
public PricingLogic(MyContext context)
{
_context = context;
}
public PricingResponse Calculation()
{
PricingResponse res = new PricingResponse();
try
{
if (_task != null)
{
res.StatusCode = 200;
RegionLogic region = new RegionLogic();
ServiceRateLogic serviceRate = new ServiceRateLogic();
var processStart = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessStartId && t.accId == _task.assignAccId).FirstOrDefault();
var processEnd = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessEndId && t.accId == _task.assignAccId).FirstOrDefault();
string latStart = processStart.latitude;
string lngStart = processStart.longitude;
string latEnd = processEnd.latitude;
string lngEnd = processEnd.longitude;
var resAmphur = MapGoogleAPI.GetAmphur(new MapGoogleAPI.AmphurRequest { Lat = latEnd, Lng = lngEnd });
string AmphurName = resAmphur.AmphurName.Replace("อำเภอ", "").Replace(" ", "");
string DistrictName = "";
if (!string.IsNullOrEmpty(resAmphur.DistrictName))
{
DistrictName = resAmphur.DistrictName.Replace("ตำบล", "").Replace("แขวง", "").Replace(" ", "");
}
var objTest = new MapGoogleAPI.DistanceRequest
{
OriginLatLng = new MapGoogleAPI.LatLng
{
Lat = latStart,
Lng = lngStart
},
DestinationLatLng = new List<MapGoogleAPI.LatLng>()
};
objTest.DestinationLatLng.Add(new MapGoogleAPI.LatLng
{
Lat = latEnd,
Lng = lngEnd
});
var distanceObj = MapGoogleAPI.GetDistance(objTest);
var amphurObj = region.GetAumphurByName(AmphurName);
List<ServiceRate> serviceRateObj = serviceRate.GetServiceRate(amphurObj.provinceCode, amphurObj.aumphurCode);
if (serviceRateObj.Count == 0)
{
int defaultServiceRateId = -1;
serviceRateObj.Add(serviceRate.GetServiceRateByServiceRateId(defaultServiceRateId));
}
float distance = 0;
try
{
if (distanceObj.Distances[0].text.IndexOf("km") > 0)
{
distance = Single.Parse(distanceObj.Distances[0].text.Replace("km", "").Replace(" ", ""));
}
else
{
distance = (float)(Single.Parse(distanceObj.Distances[0].text.Replace("m", "").Replace(" ", "")) * 0.001);
}
}
catch (Exception)
{
}
var distObj = region.GetDistrictByName(DistrictName);
res.AmphurCode = amphurObj.aumphurCode;
res.AmphurNameFromGoogle = AmphurName;
res.DistrictCode = (distObj != null ? distObj.districtCode : "");
res.DistrictNameFromGoogle = DistrictName;
res.Distance = distance;
if (serviceRateObj.Count > 0)
{
ServiceRate rate;
if (serviceRateObj.Count > 1 && distObj != null)
{
rate = serviceRateObj.Where(t => t.DistrictCode == distObj.districtCode).FirstOrDefault();
if (rate == null)
rate = serviceRateObj.Where(t => t.DistrictCode == null).FirstOrDefault();
}
else if (serviceRateObj.Count > 1 && distObj == null)
{
rate = serviceRateObj.Where(t => string.IsNullOrEmpty(t.DistrictCode)).FirstOrDefault();
}
else
{
rate = serviceRateObj[0];
}
res.InsurerPrice = this.CalculateInsurrerPrice(rate, distance);
res.ServiceRateId = rate.ID;
res.SurveyorPrice = this.CalculateSurveyorPrice(rate, distance);
}
else
{
res.StatusCode = 500;
res.ErrorMessage = "serviceRateObj not found : province_code = " + amphurObj.provinceCode + ", aumphur_code" + amphurObj.aumphurCode;
}
}
}
catch (Exception ex)
{
res.StatusCode = 500;
res.ErrorMessage = ex.Message;
}
return res;
}
public PricingResponse CalculationNewLogic()
{
PricingResponse res = new PricingResponse();
try
{
if (_task != null)
{
res.StatusCode = 200;
RegionLogic region = new RegionLogic();
ServiceRateLogic serviceRateLogic = new ServiceRateLogic();
var processStart = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessStartId && t.accId == _task.assignAccId).FirstOrDefault();
var processEnd = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessEndId && t.accId == _task.assignAccId).FirstOrDefault();
string latStart = processStart.latitude;
string lngStart = processStart.longitude;
string latEnd = processEnd.latitude;
string lngEnd = processEnd.longitude;
var objTest = new MapGoogleAPI.DistanceRequest
{
OriginLatLng = new MapGoogleAPI.LatLng
{
Lat = latStart,
Lng = lngStart
},
DestinationLatLng = new List<MapGoogleAPI.LatLng>()
};
objTest.DestinationLatLng.Add(new MapGoogleAPI.LatLng
{
Lat = latEnd,
Lng = lngEnd
});
var distanceObj = MapGoogleAPI.GetDistance(objTest, "", "th");
string address = distanceObj.DestinationAddress;
var provinceFromGoogle = MapGoogleAPI.GetProvince(new MapGoogleAPI.ProvinceRequest { Lat = latEnd, Lng = lngEnd });
Province province = region.GetProvinceByName(provinceFromGoogle.ProvinceName);
ServiceRate serviceRate = null;
if (province == null)
{
RegionLogic regionLogic = new RegionLogic();
List<Province> provinces = regionLogic.getProvice();
province = provinces.Where(oh => address.Contains(oh.provinceName)).FirstOrDefault();
}
serviceRate = serviceRateLogic.GetServiceRateByProvinceCodeIsActive(province.provinceCode);
if (serviceRate == null)
{
int defaultServiceRateId = -1;
serviceRate = serviceRateLogic.GetServiceRateByServiceRateId(defaultServiceRateId);
}
float distance = 0;
try
{
distance = (float)(distanceObj.Distances[0].value * 0.001);
}
catch (Exception)
{
}
res.Distance = distance;
res.Place = address;
if (serviceRate != null)
{
res.ServiceRate = serviceRate;
res.InsurerPrice = this.CalculateInsurrerPrice(serviceRate, distance);
res.ServiceRateId = serviceRate.ID;
res.SurveyorPrice = this.CalculateSurveyorPrice(serviceRate, distance);
}
else
{
res.StatusCode = 500;
res.ErrorMessage = "serviceRateObj not found : " + address;
}
}
}
catch (Exception ex)
{
res.StatusCode = 500;
res.ErrorMessage = ex.Message;
}
return res;
}
public PricingResponse CalculationForInsurer()
{
PricingResponse res = new PricingResponse();
try
{
if (_task != null)
{
res.StatusCode = 200;
RegionLogic region = new RegionLogic();
ServiceRateLogic serviceRateLogic = new ServiceRateLogic();
InsurerRateLogic insurerRateLogic = new InsurerRateLogic();
var processEnd = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessEndId && t.accId == _task.assignAccId).FirstOrDefault();
if (processEnd == null)
{
return res;
}
string latEnd = processEnd.latitude;
string lngEnd = processEnd.longitude;
var provinceFromGoogle = MapGoogleAPI.GetProvince(new MapGoogleAPI.ProvinceRequest { Lat = latEnd, Lng = lngEnd });
Province province = region.GetProvinceByName(provinceFromGoogle.ProvinceName);
var resAmphur = MapGoogleAPI.GetAmphurByAdministrativeAreaLevel2(new MapGoogleAPI.AmphurRequest { Lat = latEnd, Lng = lngEnd });
string amphurName = resAmphur.AmphurName.Replace("อำเภอ", "").Replace(" ", "");
Aumphur amphur = region.GetAumphurByName(amphurName);
InsurerRateGroup insurerRateGroup = null;
if (_task.Insurers.InsurerRateGroupId.HasValue)
{
int insurerRateGroupId = _task.Insurers.InsurerRateGroupId.Value;
insurerRateGroup = insurerRateLogic.GetInsurerRateGroupByIdAndIsActive(insurerRateGroupId);
}
InsurerRate insurerRate = null;
if (insurerRateGroup != null && province != null && amphur != null)
{
insurerRate = insurerRateLogic.GetInsurerRateByRateGroupIdProvinceCodeAndAmphurCode(insurerRateGroup.InsurerRateGroupId, province.provinceCode, amphur.aumphurCode);
}
if (insurerRate != null)
{
res.InsurerPrice = Convert.ToSingle(insurerRate.InsurerRatePrice.Value);
res.InsurerRateId = insurerRate.InsurerRateId;
}
else
{
res.StatusCode = 500;
res.ErrorMessage = "insurerRate not found : Province = " + provinceFromGoogle.ProvinceName + "| Amphur = " + amphurName;
}
}
}
catch (Exception ex)
{
res.StatusCode = 500;
res.ErrorMessage = ex.Message;
}
return res;
}
public PricingResponse CalculationByDistance(double distance, ServiceRate serviceRate, double total)
{
PricingResponse res = new PricingResponse();
double _distance = Math.Round(distance, 0);
if (serviceRate.ConfigId == 4) // outsource
{
res.InsurerPrice = this.CalculateInsurrerPrice(serviceRate, _distance);
res.ServiceRateId = serviceRate.ID;
res.SurveyorPrice = Convert.ToSingle(total);
res.Distance = Convert.ToSingle(_distance);
}
else
{
res.InsurerPrice = this.CalculateInsurrerPrice(serviceRate, _distance);
res.ServiceRateId = serviceRate.ID;
res.SurveyorPrice = this.CalculateSurveyorPrice(serviceRate, _distance);
res.Distance = Convert.ToSingle(_distance);
}
return res;
}
public double CalculationDistanceBetweenStartAndArrived()
{
var processStart = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessStartId && t.accId == _task.assignAccId).FirstOrDefault();
var processEnd = _task.TaskProcessLogs.Where(t => t.taskProcessId == TaskProcessEndId && t.accId == _task.assignAccId).FirstOrDefault();
if (processStart == null)
{
return 0;
}
if (processEnd == null)
{
return 0;
}
string latStart = processStart.latitude;
string lngStart = processStart.longitude;
string latEnd = processEnd.latitude;
string lngEnd = processEnd.longitude;
var objRequest = new MapGoogleAPI.DistanceRequest
{
OriginLatLng = new MapGoogleAPI.LatLng
{
Lat = latStart,
Lng = lngStart
},
DestinationLatLng = new List<MapGoogleAPI.LatLng>()
};
objRequest.DestinationLatLng.Add(new MapGoogleAPI.LatLng
{
Lat = latEnd,
Lng = lngEnd
});
var distanceObj = MapGoogleAPI.GetDistance(objRequest, "", "th");
double distance = 0;
try
{
distance = (distanceObj.Distances[0].value * 0.001);
}
catch (Exception)
{
}
return distance;
}
private float CalculateSurveyorPrice(ServiceRate serviceRate, double distance)
{
double _distance = Math.Round(distance, 0);
float result = Convert.ToSingle(serviceRate.SurveyorRate);
if (_distance > serviceRate.PriceRateConfig.OverDistance)
{
result += Convert.ToSingle((_distance - serviceRate.PriceRateConfig.OverDistance) * serviceRate.PriceRateConfig.PriceRate);
}
return result;
}
private float CalculateInsurrerPrice(ServiceRate _serviceRate, double _distance)
{
float result = Convert.ToSingle(_serviceRate.InsurerRate);
return result;
}
public List<PriceRateConfig> getPriceRateConfig()
{
var req = new Repository<PriceRateConfig>(_context);
List<PriceRateConfig> result = new List<PriceRateConfig>();
result = req.GetQuery().ToList();
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Docller.Core.Services
{
public enum ProjectServiceStatus
{
Unknown = -1,
Success = 0,
ExistingProject = 104,
}
}
|
using System;
using System.Net;
namespace Hangfire.JobSDK
{
public class ManagementPageAttribute : Attribute
{
public string Title { get; }
public string MenuName { get; }
public string Queue { get; }
public string Category => WebUtility.UrlEncode(MenuName.ToLower().Replace(" ",""));
public ManagementPageAttribute(string menuName, string title, string queue="default")
{
Title = title;
MenuName = menuName;
Queue = queue;
}
}
} |
using System.Windows;
using System.Windows.Media;
namespace Crystal.Plot2D
{
///<summary>
/// Base class for all navigation providers.
///</summary>
public abstract class NavigationBase : ViewportElement2D
{
protected NavigationBase()
{
ManualTranslate = true;
ManualClip = true;
Loaded += NavigationBase_Loaded;
}
private void NavigationBase_Loaded(object sender, RoutedEventArgs e)
{
OnLoaded(e);
}
protected virtual void OnLoaded(RoutedEventArgs e)
{
// this call enables contextMenu to be shown after loading and
// before any changes to Viewport - without this call
// context menu was not shown.
InvalidateVisual();
}
protected override void OnRenderCore(DrawingContext dc, RenderState state)
{
dc.DrawRectangle(Brushes.Transparent, null, state.Output);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeBlog_28_GarbageCollector
{
public class MyClass : IDisposable
{
public MyClass() // Создание конструктора
{
}
~MyClass() // Создание деструктора
{
// Допустим при асинхронности используется для корректного закрытия потока
}
public void Dispose()
{
GC.Collect();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Logear : System.Web.UI.Page
{
webservicio.Webservice2Client conec = new webservicio.Webservice2Client();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string nick = nickname.Text;
string con = contra.Text;
bool aa = conec.Login(nick, con);
if (aa == true)
{
Session["Nickname"] = nickname.Text;
Response.Redirect("Estados.aspx");
}
else
{
Response.Redirect("AgregarUsuario1.aspx");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("AgregarUsuario1.aspx");
}
} |
using SocialWorld.DataAccess.Interfaces;
using SocialWorld.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SocialWorld.DataAccess.Concrete.EntityFrameworkCore.Repositories
{
public class EfAppRoleRepository: EfGenericRepository<AppRole>,IAppRoleDal
{
}
}
|
using System;
namespace Alabo.Domains.Entities.Core {
public class AutoConfigBase : EntityCommon<AutoConfigBase, Guid> {
public AutoConfigBase(Guid id) : base(id) {
}
public AutoConfigBase() : this(Guid.Empty) {
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.Sconit.Web.Models
{
[Serializable]
public class WebOrderDetail
{
public Int32 Sequence { get; set; }
public string Item { get; set; }
public string ItemDescription { get; set; }
public string Uom { get; set; }
public Decimal UnitCount { get; set; }
public string LocationFrom { get; set; }
public string LocationTo { get; set; }
public string Bom { get; set; }
public string Routing { get; set; }
public Decimal MinUnitCount { get; set; }
public string UnitCountDescription { get; set; }
public string Container { get; set; }
public string ContainerDescription { get; set; }
public string ReferenceItemCode { get; set; }
public string ManufactureParty { get; set; }
}
} |
using System;
using System.Collections.Generic;
namespace Big_Bank_Inc
{
class Program
{
private static string mainOption = "";
private static decimal totalInAllAccounts;
private static User currentUser = null;
static void Main(string[] args)
{
do
{
Menu.MainMenuWriter("");
//Create User Option
if (mainOption == "1")
{
string firstName = Validator.ValidateNameGiven("fn");
string lastName = Validator.ValidateNameGiven("ln");
string socialSecurityNumber = Validator.ValidateUserSsn();
currentUser = User.CreateUser(firstName, lastName, socialSecurityNumber);
}
//Create Account Option
if (mainOption == "2")
{
var createAccountOption = "";
//If current user does not exist
if (currentUser == null)
{
Console.WriteLine("Please choose option 1 from the Main Menu and create a new customer account.\n");
}
//Else if current user exists
else
{
Menu.MenuWriter(Menu.createAccountOptionsMenu);
createAccountOption = Console.ReadLine();
System.Console.WriteLine();
//Create Checking Account Option
if (createAccountOption == "1")
{
Account checkingAccount = Account.CreateAccountByType(createAccountOption, currentUser);
Menu.OpenAccountDisplayByType(checkingAccount);
decimal openingAmount = Validator.IsInitialInvestmentDecimal();
checkingAccount.InitialInvestment(openingAmount, new DateTime(2015, 01, 01));
Menu.DisplayInitialAccountInvestment(checkingAccount);
}
//Create Savings Account
if (createAccountOption == "2")
{
Account savingsAccount = Account.CreateAccountByType(createAccountOption, currentUser);
Menu.OpenAccountDisplayByType(savingsAccount);
decimal openingAmount = Validator.IsInitialInvestmentDecimal();
savingsAccount.InitialInvestment(openingAmount, new DateTime(2015, 01, 01));
Menu.DisplayInitialAccountInvestment(savingsAccount);
}
}
}
//Manage Accounts Option
if (mainOption == "3")
{
var manageAccountChoice = "";
Menu.MenuWriter(Menu.manageAccountOptionsMenu);
manageAccountChoice = Console.ReadLine();
System.Console.WriteLine();
//Manage an Individual Checking or Savings Account Option
if (manageAccountChoice == "1")
{
Menu.AccountsMenuHeader();
Menu.AccountsMenuListOfAccounts(currentUser);
string accountLastFourDigits = Menu.LastFourAccountDigits();
Account selectedAccount = Account.FindAccountByLastFourDigits(accountLastFourDigits);
if (selectedAccount != null)
{
ListAsCheckingOrSavings(selectedAccount);
Menu.MenuWriter(Menu.individualAccountOptions);
string withdrawOrDepositChoice = Console.ReadLine();
//Deposit Option for Individual Account
if (withdrawOrDepositChoice == "1")
{
DepositToSelectedAccount(selectedAccount);
}
//Withdraw Option for Individual Account
if (withdrawOrDepositChoice == "2")
{
SubtractFromAccountSelected(selectedAccount);
}
}
}
//Check Balances of all accounts
if (manageAccountChoice == "2")
{
//Header of all accounts with current users name displayed
Menu.ManageAllAccountsUserHeader(currentUser);
//Bools to check if either a savings or checking account exist in the current users list of accounts
var checkingIsInList = currentUser.Accounts.Exists(act => act as CheckingAccount != null);
var savingsIsInList = currentUser.Accounts.Exists(act => act as SavingsAccount != null);
if (checkingIsInList)
{
Menu.ManageAccountsCheckingAccountListHeader();
Menu.ListOfCheckingAccounts(currentUser, totalInAllAccounts);
}
System.Console.WriteLine();
if (savingsIsInList)
{
Menu.ManageAccountsSavingsAccountListHeader();
ListOfSavingsAccounts();
}
Menu.TotalInAllAccounts(totalInAllAccounts);
}
}
//Main Menu Option 4 is to Quit Program
} while (mainOption != "4");
}
/* Private Static Functions for Refactoring
======================================================================================================
*/
#region
private static void ListAsCheckingOrSavings(Account selectedAccount)
{
if (selectedAccount as CheckingAccount != null)
{
Console.WriteLine($"Checking Account: {selectedAccount.AccountNumber}");
}
if (selectedAccount as SavingsAccount != null)
{
Console.WriteLine($"Savings Account: {selectedAccount.AccountNumber}");
}
Console.WriteLine();
}
private static void ListOfSavingsAccounts ()
{
foreach (Account act in currentUser.Accounts)
{
if (act as SavingsAccount != null)
{
Console.WriteLine($"{act.AccountNumber} : ${act.AccountAmountCurrent}");
totalInAllAccounts += act.AccountAmountCurrent;
}
}
}
private static void DepositToSelectedAccount(Account selectedAccount)
{
bool isDepositDecimal;
decimal decimalAmountEntered;
do
{
Console.WriteLine("How much would you like to deposit?");
string depositAmount = Console.ReadLine();
isDepositDecimal = Decimal.TryParse(depositAmount, out decimalAmountEntered);
} while (!isDepositDecimal);
selectedAccount.AddToAccount(decimalAmountEntered);
Console.WriteLine($"Your account now has ${ decimalAmountEntered }");
}
private static void SubtractFromAccountSelected(Account selectedAccount)
{
Console.WriteLine($"How much money would you like to withdraw from your account { selectedAccount.AccountNumber }?");
bool isWithdrawAmountDecimal;
decimal decimalWithdrawAmount;
do
{
var withdrawAmount = Console.ReadLine();
isWithdrawAmountDecimal = Decimal.TryParse(withdrawAmount, out decimalWithdrawAmount);
if (isWithdrawAmountDecimal && decimalWithdrawAmount > selectedAccount.AccountAmountCurrent)
{
Console.WriteLine("You cannot withdraw more funds than are currently in this account. Please enter a new amount.");
}
else if (isWithdrawAmountDecimal && decimalWithdrawAmount < selectedAccount.AccountAmountCurrent)
{
selectedAccount.SubtractFromAccount(decimalWithdrawAmount);
Console.WriteLine($"Your new account balance for account { selectedAccount.AccountNumber } is ${ selectedAccount.AccountAmountCurrent }");
}
} while (decimalWithdrawAmount > selectedAccount.AccountAmountCurrent);
}
#endregion
}
} |
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityAtoms.Editor;
namespace UnityAtoms.BaseAtoms.Editor
{
/// <summary>
/// Base class for a custom editor for Clamp Functions.
/// </summary>
public abstract class ClampBaseEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
IIsValid iIsValid = (IIsValid)target;
if (iIsValid != null && !iIsValid.IsValid())
{
EditorGUILayout.HelpBox("Min value must be less than or equal to Max value.", MessageType.Warning);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Companies.DataEntity;
using Companies.Accessors;
namespace Companies
{
class Program
{
static void Main(string[] args)
{
IEntityAccessor<Company> ca = new XMLFileAccessor<Company>("db.xml");
foreach (var c in ca.GetAll())
WriteCompany(c);
ca.Insert(new Company("ООО РСВ", "sadasd", "123123"));
ca.Insert(new Company("asd asd", "cvb", "345"));
Console.WriteLine();
WriteCompany(ca.GetById(2));
Console.WriteLine();
ca.Insert(new Company(" cvbcvb", "cvbcvb", "cvbcvb"));
Console.WriteLine();
foreach (var c in ca.GetAll())
WriteCompany(c);
ca.DeleteById(3);
Console.WriteLine();
foreach (var c in ca.GetAll())
WriteCompany(c);
Console.ReadKey();
}
static void WriteEmployee(Employee e)
{
Console.WriteLine("Id: {0}, First Name: {1}, Last Name: {2}, Birth Date: {3}\nCompany Id: {4}, Position: {5}, Employment Date: {6}",
e.Id, e.FirstName, e.LastName, e.BirthDate.ToShortDateString(), e.CompanyId, e.Position, e.EmploymentDate.ToShortDateString());
}
static void WriteCompany(Company c)
{
Console.WriteLine("Id: {0}, Name: {1}, Address: {2}, Phone: {3}", c.Id, c.Name, c.Address, c.Phone);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Searcharoo.Common;
using Mono.GetOptions;
#region Mono.GetOptions attributes to drive command line argument parsing
// Instructions to 'set up' Mono.GetOptions
// http://www.talios.com/command_line_processing_with_monogetoptions.htm
// Attributes visible in " -V"
[assembly: Mono.About("Searcharoo Indexer (Spider)")]
[assembly: Mono.Author("Craig.Dunn (at) ConceptDevelopment.net")]
[assembly: Mono.AdditionalInfo("Searcharoo.Indexer.exe spiders and catalogs data for the Searcharoo.Engine")]
// This is text that goes after " [options]" in help output - there is none for this program
[assembly: Mono.UsageComplement("")]
// Attributes visible in " --help"
// are defined in AssemblyInfo.cs (not here)
#endregion
namespace Searcharoo.Indexer
{
class Program
{
private static CommandLinePreferences clip;
static void Main(string[] args)
{
clip = new CommandLinePreferences();
ConsoleWriteLine(1, "Searcharoo.Indexer v0.1");
clip.ProcessArgs(args);
ConsoleWriteLine(1, "=======================");
Spider spider = new Spider();
spider.SpiderProgressEvent += new SpiderProgressEventHandler(OnProgressEvent);
spider.SpiderProgressEvent += new SpiderProgressEventHandler(OnProgressLogEvent);
Catalog catalog = spider.BuildCatalog(new Uri(Preferences.StartPage));
ConsoleWriteLine(1, "=======================");
#if DEBUG
//System.Threading.Thread.Sleep(30 * 1000); // 30 seconds
ConsoleWriteLine(1, "Press <enter> to finish...");
if (clip.Verbosity > 0) Console.Read();
#endif
}
private static void ConsoleWriteLine(int level, string text)
{
if (level <= clip.Verbosity)
{
Console.WriteLine(text);
}
}
/// <summary>
/// Handle events generated by the Spider (mostly reporting on success/fail of page load/index)
/// </summary>
public static void OnProgressEvent(object source, ProgressEventArgs pea)
{
if (pea.Level <= clip.Verbosity)
{
Console.WriteLine(">{0} :: {1}", pea.Level, pea.Message);
}
}
/// <summary>
/// Log to disk events generated by the Spider (mostly reporting on success/fail of page load/index)
/// </summary>
public static void OnProgressLogEvent(object source, ProgressEventArgs pea)
{
//if (pea.Level < 3)
//{
// Console.WriteLine(pea.Message + "<br>");
//}
}
}
}
|
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Juicy.DirtCheapDaemons.Http
{
public class Request : IRequest
{
public Request()
{
Headers = new Dictionary<string, string>();
QueryString = new Dictionary<string, string>();
Form = new Dictionary<string, string>();
}
public string this[string headerName] { get { return Headers[headerName]; } set { Headers[headerName] = value; } }
public MountPoint MountPoint { get; set; }
public string VirtualPath { get; set; }
public string PostBody { get; set; }
public IDictionary<string, string> Headers { get; private set; }
public IDictionary<string, string> QueryString { get; private set; }
public IDictionary<string, string> Form { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Exercise_2
{
class Program
{
static void Main(string[] args)
{
Article article1 = new Article();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
List<string> input = Console.ReadLine().Split(": ").ToList();
string command = input[0];
string newContent = input[1];
if (command == "Edit")
{
article1.Content = article1.Edit(article1.Content, newContent);
}
if (command == "ChangeAuthor")
{
article1.Author = article1.ChangeAuthor(article1.Author, newContent);
}
if (command == "Rename")
{
article1.Title = article1.Rename(article1.Title, newContent);
}
}
Console.WriteLine(article1);
}
}
class Article
{
public string Title { get; set; }
public string Content { get; set; }
public string Author { get; set; }
public Article()
{
List<string> command = Console.ReadLine().Split(", ").ToList();
this.Title = command[0];
this.Content = command[1];
this.Author = command[2];
}
public override string ToString()
{
string one = $"{Title} - {Content}: {Author} ";
return one;
}
public string Edit(string Content, string better)
{
Content = better;
return better;
}
public string ChangeAuthor(string Content, string better)
{
Content = better;
return better;
}
internal string Rename(string title, string newContent)
{
title = newContent;
return newContent;
}
}
}
|
using System;
using Messaging.Resolvers;
using Messaging.Validators;
using Xunit;
namespace Messaging.Validators.Tests
{
public class SchematronValidatorTests
{
private IResourceResolver _fileResolver;
public SchematronValidatorTests()
{
_fileResolver = EmbeddedResourceResolver.Create(AssemblyType.Caller);
}
[Theory]
[InlineData("POCD_EX150001UK06_05.xml", true)]
[InlineData("POCD_EX150001UK06_05Invalid.xml", false)]
public void Validate_IsoDocument_OnStream(string filename, bool result)
{
var res = SchematronValidator.Create(SchematronDocument.GenericCda).Validate(_fileResolver.GetResourceStream(filename));
Assert.Equal(result, res.Status);
}
[Theory]
[InlineData("POCD_EX150001UK06_05.xml", true)]
[InlineData("POCD_EX150001UK06_05Invalid.xml", false)]
public void Validate_IsoDocument_OnText(string filename, bool result)
{
var res = SchematronValidator.Create(SchematronDocument.GenericCda).Validate(_fileResolver.GetResourceStream(filename).GetText());
Assert.Equal(result, res.Status);
}
[Fact]
public void Validate_NonIsoDocument_OnStream()
{
string nonIsoDocument = _fileResolver.GetResourceStream("Generic_CDA_Document_OldSchematron.xml").GetText();
var res = new SchematronValidator(nonIsoDocument, convertToIsoNamespace: true).Validate(_fileResolver.GetResourceStream("POCD_EX150001UK06_05.xml"));
Assert.True(res.Status);
}
[Fact]
public void Validate_NonIsoDocument_OnText()
{
string nonIsoDocument = _fileResolver.GetResourceStream("Generic_CDA_Document_OldSchematron.xml").GetText();
var res = new SchematronValidator(nonIsoDocument, convertToIsoNamespace: true).Validate(_fileResolver.GetResourceStream("POCD_EX150001UK06_05.xml").GetText());
Assert.True(res.Status);
}
}
}
|
using System;
using Microsoft.CQRS;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.UnifiedPlatform.Service.Common.Configuration;
using Microsoft.UnifiedPlatform.Service.Common.AppExceptions;
using Microsoft.UnifiedPlatform.Service.Common.Authentication;
namespace Microsoft.UnifiedPlatform.Service.Application.Commands.Handlers
{
public class AuthenticateClientCommandHandler : CommandHandler<AuthenticateClientCommand, TokenCommandResult>
{
private readonly IAuthenticator _authenticator;
private readonly IClusterConfigurationProvider _clusterConfigurationProvider;
public AuthenticateClientCommandHandler(IAuthenticator authenticator, IClusterConfigurationProvider clusterConfigurationProvider)
{
_authenticator = authenticator;
_clusterConfigurationProvider = clusterConfigurationProvider;
}
protected override async Task<TokenCommandResult> ProcessRequest(AuthenticateClientCommand request)
{
var appDetails = await _clusterConfigurationProvider.GetApplicationDetails(request.ClusterName, request.AppName);
if (appDetails == null)
throw new InvalidAppException(request.ClusterName, request.AppName);
var appSecret = await _clusterConfigurationProvider.GetApplicationSecret(request.ClusterName, request.AppName);
if (!request.AppSecret.Equals(appSecret))
throw new UnauthenticatedAppException(request.ClusterName, request.AppName);
var claims = new Dictionary<string, string>()
{
{ "cluster", request.ClusterName },
{ "app", request.AppName }
};
var authToken = await _authenticator.GenerateToken(request.AppName, claims);
return new TokenCommandResult(authToken, request.AppName, DateTime.UtcNow.AddMinutes(45).Ticks);
}
}
}
|
using ArkSavegameToolkitNet.Types;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArkSavegameToolkitNet.Structs
{
[JsonObject(MemberSerialization.OptIn)]
public class StructUniqueNetIdRepl : StructBase
{
public int Unk { get; set; }
[JsonProperty]
public string NetId { get; set; }
public StructUniqueNetIdRepl(ArkName structType) : base(structType) { }
public StructUniqueNetIdRepl(ArkName structType, int unk, string netId) : base(structType)
{
Unk = unk;
NetId = netId;
}
public StructUniqueNetIdRepl(ArkArchive archive, ArkName structType) : base(structType)
{
Unk = archive.GetInt();
NetId = archive.GetString();
}
//public override int getSize(bool nameTable)
//{
// return Integer.BYTES + ArkArchive.getStringLength(netId);
//}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPrefsX
{
public static void SetBool(string name, bool booleanValue)
{
PlayerPrefs.SetInt(name, booleanValue ? 1 : 0);
}
public static bool GetBool(string name)
{
return PlayerPrefs.GetInt(name) == 1 ? true : false;
}
public static bool GetBool(string name, bool defaultValue)
{
if(PlayerPrefs.HasKey(name))
{
return GetBool(name);
}
return defaultValue;
}
} |
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.Threading;
namespace L2Bot_Dead_Reckoning
{
public partial class Form1 : Form
{
LoCoMoCo mc;
public Form1()
{
InitializeComponent();
mc = new LoCoMoCo("COM7");
}
private void start_stop_btn_Click(object sender, EventArgs e)
{
mc.forward();
Thread.Sleep(5000); // Drive straight for 5 seconds
mc.turnleft();
Thread.Sleep(3000); // Turn left for 3 seconds
mc.forward();
Thread.Sleep(5000); // Drive straight for 5 seconds
mc.stop();
}
protected override void OnClosing(CancelEventArgs e)
{
mc.close();
base.OnClosing(e);
}
}
}
|
using Entity.Component;
using org.ogre;
using PacmanOgre.Utilities;
using SharpEngine;
namespace PacmanOgre.Components
{
class VelocityComponent : IComponent
{
[Description("Velocity")]
public Vector3 Velocity { get; set; } = VectorUtils.Vector3.ZERO;
public VelocityComponent(IContext context, IEntity entity)
{
}
public void OnLoaded()
{
}
public void Setup()
{
}
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
namespace Core
{
public interface IDecoder
{
Task<DecodeResult> DecodeAsync(Speech speech);
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace Askii.Tests
{
[TestFixture ()]
public class LexerFixture
{
Dictionary<string, string> tokens;
[SetUp]
public void Setup()
{
var lexer = new Lexer ();
this.tokens = lexer.Tokenize("" +
"==============================" +
"| Titel |" +
"|============================|" +
"| (i) Check this out! |" +
"| This is a Message =) |" +
"|----------------------------|" +
"| [ Ok ] [ Cancel ] |" +
"=============================="
);
}
[Test ()]
public void Titel ()
{
Assert.That (tokens["Title"], Is.EqualTo ("Titel"));
}
[Test()]
public void Icon()
{
Assert.That (tokens ["Icon"], Is.EqualTo ("(i)"));
}
[Test()]
public void Message()
{
Assert.That(tokens["Message"], Is.EqualTo("Check this out!" + Environment.NewLine + "This is a Message =)"));
}
[Test]
public void Buttons()
{
Assert.That (tokens ["Buttons"], Is.EqualTo ("Ok,Cancel"));
}
}
}
|
using UnityEngine;
public class FindObjectName : MonoBehaviour {
public int TimesToRun;
void Update () {
for(int i = 0; i < TimesToRun; i++)
{
GameObject Player = GameObject.Find("Player(Clone)");//.GetComponent<Player>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exp003_Akka_Server
{
public class SweepFloor
{
public readonly string Room;
public SweepFloor(string inRoom)
{
this.Room = inRoom;
}
}
}
|
using System;
using MonoTouch.UIKit;
namespace iPadPos
{
public class MiniCell : UITableViewCell, ICellSelectable
{
public Action Tapped { get; set; }
public const string Key = "MiniCell";
public MiniCell () : base (UITableViewCellStyle.Value1,Key)
{
Frame = new System.Drawing.RectangleF (0, 0, 320, 30);
TextLabel.Font = UIFont.SystemFontOfSize (UIFont.SmallSystemFontSize + 2);
DetailTextLabel.Font = UIFont.SystemFontOfSize (UIFont.SmallSystemFontSize + 2);
}
#region ICellSelectable implementation
public void OnSelect ()
{
if (Tapped != null)
Tapped ();
}
#endregion
}
}
|
using GerenciadorDespesas.Models;
using GerenciadorDespesas.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GerenciadorDespesas.ViewComponents
{
public class EstatisticasViewComponent : ViewComponent
{
private readonly Contexto _context;
public EstatisticasViewComponent(Contexto context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync()
{
EstatisticasViewModel estatisticas = new EstatisticasViewModel();
estatisticas.MenorDespesa = _context.Despesas.Min(x => x.Valor);
estatisticas.MaiorDespesa = _context.Despesas.Max(x => x.Valor);
estatisticas.QuantidadeDespesas = _context.Despesas.Count();
return View(estatisticas);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Models
{
public class Evacuation: ICloneable<Evacuation>
{
public int Id { get; set; }
public int FineId { get; set; }
public int AutoId { get; set; }
public int ParkingId { get; set; }
/// <summary>
/// Откуда забрали
/// </summary>
public string PlaceEvac { get; set; }
/// <summary>
/// Когда забрали
/// </summary>
public DateTime DateTimeEvac { get; set; }
/// <summary>
/// Стоиомсть эвакуации
/// </summary>
public double EvacCost { get; set; }
/// <summary>
/// Куда забрали
/// </summary>
public virtual Parking Parking { get; set; }
/// <summary>
/// Почему забрали (нарушение)
/// </summary>
public virtual Fine Fine { get; set; }
/// <summary>
/// Что забрали
/// </summary>
public virtual Auto Auto { get; set; }
/// <summary>
/// Где сейчас машина: на стоянке или выдана владельцу
/// </summary>
public CarStatus CarStatus { get; set; }
public ICollection<Declaration> Declarations { get; set; }
public Evacuation Clone()
{
var clone = this.MemberwiseClone() as Evacuation;
return clone;
}
}
}
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using CODE.Framework.Wpf.Layout;
using CODE.Framework.Wpf.Utilities;
namespace CODE.Framework.Wpf.Mvvm
{
/// <summary>
/// Special tab control used to host views (typically normal views in the shell)
/// </summary>
/// <remarks>Designed for internal use only</remarks>
public class ViewHostTabControl : TabControl
{
private int _previousSelectedIndex = -1;
/// <summary>
/// Initializes a new instance of the <see cref="ViewHostTabControl"/> class.
/// </summary>
public ViewHostTabControl()
{
SelectionChanged += (s, e) => { HandleSelectionChanged(); };
}
/// <summary>
/// Updates all properties related to changing view selection
/// </summary>
protected virtual void HandleSelectionChanged()
{
HasVisibleItems = SelectedItem != null;
if (SelectedIndex != _previousSelectedIndex && SelectedIndex > -1 && SelectedIndex > _previousSelectedIndex) RaiseNextViewSelected();
else if (SelectedIndex != _previousSelectedIndex && SelectedIndex > -1 && SelectedIndex < _previousSelectedIndex) RaisePreviousViewSelected();
_previousSelectedIndex = SelectedIndex;
var viewResult = SelectedItem as ViewResult;
if (viewResult != null)
HasVisibleLocalViews = viewResult.SelectedLocalViewIndex > -1;
}
/// <summary>
/// Fires when the next view is selected (either a new view, or a view with a higher index than the previously selected one)
/// </summary>
public static readonly RoutedEvent NextViewSelectedEvent = EventManager.RegisterRoutedEvent("NextViewSelected", RoutingStrategy.Direct, typeof (RoutedEventHandler), typeof (ViewHostTabControl));
/// <summary>
/// Fires when the next view is selected (either a new view, or a view with a higher index than the previously selected one)
/// </summary>
public event RoutedEventHandler NextViewSelected
{
add { AddHandler(NextViewSelectedEvent, value); }
remove { RemoveHandler(NextViewSelectedEvent, value); }
}
/// <summary>
/// Raises the next view selected event.
/// </summary>
protected void RaiseNextViewSelected()
{
var newEventArgs = new RoutedEventArgs(NextViewSelectedEvent);
RaiseEvent(newEventArgs);
}
/// <summary>
/// Fires when the previous view is selected (a view with a lower index than the previously selected one)
/// </summary>
public static readonly RoutedEvent PreviousViewSelectedEvent = EventManager.RegisterRoutedEvent("PreviousViewSelected", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ViewHostTabControl));
/// <summary>
/// Fires when the previous view is selected (a view with a lower index than the previously selected one)
/// </summary>
public event RoutedEventHandler PreviousViewSelected
{
add { AddHandler(PreviousViewSelectedEvent, value); }
remove { RemoveHandler(PreviousViewSelectedEvent, value); }
}
/// <summary>
/// Raises the previous view selected event.
/// </summary>
private void RaisePreviousViewSelected()
{
var newEventArgs = new RoutedEventArgs(PreviousViewSelectedEvent);
RaiseEvent(newEventArgs);
}
/// <summary>Defines whether tab headers shall be displayed</summary>
/// <remarks>It is up to each theme to respect this property</remarks>
public bool ShowHeaders
{
get { return (bool)GetValue(ShowHeadersProperty); }
set { SetValue(ShowHeadersProperty, value); }
}
/// <summary>Defines whether tab headers shall be displayed</summary>
/// <remarks>It is up to each theme to respect this property</remarks>
public static readonly DependencyProperty ShowHeadersProperty = DependencyProperty.Register("ShowHeaders", typeof(bool), typeof(ViewHostTabControl), new PropertyMetadata(true));
/// <summary>Main model (typically the start view model)</summary>
public object MainModel
{
get { return GetValue(MainModelProperty); }
set { SetValue(MainModelProperty, value); }
}
/// <summary>Main model (typically the start view model)</summary>
public static readonly DependencyProperty MainModelProperty = DependencyProperty.Register("MainModel", typeof(object), typeof(ViewHostTabControl), new PropertyMetadata(null));
/// <summary>
/// Desired zoom for the content within the tab control
/// </summary>
public double ContentZoom
{
get { return (double)GetValue(ContentZoomProperty); }
set { SetValue(ContentZoomProperty, value); }
}
/// <summary>
/// Desired zoom for the content within the tab control
/// </summary>
public static readonly DependencyProperty ContentZoomProperty = DependencyProperty.Register("ContentZoom", typeof(double), typeof(ViewHostTabControl), new PropertyMetadata(1d));
/// <summary>
/// Indicates whether the control has visible items
/// </summary>
public bool HasVisibleItems
{
get { return (bool)GetValue(HasVisibleItemsProperty); }
set { SetValue(HasVisibleItemsProperty, value); }
}
/// <summary>
/// Indicates whether the control has visible items
/// </summary>
public static readonly DependencyProperty HasVisibleItemsProperty = DependencyProperty.Register("HasVisibleItems", typeof(bool), typeof(ViewHostTabControl), new PropertyMetadata(false));
/// <summary>
/// Indicates whether local child views are visible
/// </summary>
public bool HasVisibleLocalViews
{
get { return (bool)GetValue(HasVisibleLocalViewsProperty); }
set { SetValue(HasVisibleLocalViewsProperty, value); }
}
/// <summary>
/// Indicates whether local child views are visible
/// </summary>
public static readonly DependencyProperty HasVisibleLocalViewsProperty = DependencyProperty.Register("HasVisibleLocalViews", typeof(bool), typeof(ViewHostTabControl), new PropertyMetadata(false));
}
/// <summary>
/// Specialized version of the view-host tab control class capable of creating hierarchies of tabs
/// </summary>
/// <seealso cref="CODE.Framework.Wpf.Mvvm.ViewHostTabControl" />
public class HierarchicalViewHostTabControl : ViewHostTabControl
{
/// <summary>
/// For internal use only (activates the view of a certain index within the hierarchy)
/// </summary>
/// <value>
/// The index of the activate view.
/// </value>
public int ActivateViewIndex
{
get { return (int) GetValue(ActivateViewIndexProperty); }
set { SetValue(ActivateViewIndexProperty, value); }
}
/// <summary>
/// For internal use only (activates the view of a certain index within the hierarchy)
/// </summary>
public static readonly DependencyProperty ActivateViewIndexProperty = DependencyProperty.Register("ActivateViewIndex", typeof(int), typeof(HierarchicalViewHostTabControl), new PropertyMetadata(-1, OnActivateViewIndexChanged));
/// <summary>
/// Fires when the ActivateViewIndex property changed
/// </summary>
/// <param name="d">The d.</param>
/// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnActivateViewIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tabs = d as HierarchicalViewHostTabControl;
if (tabs == null) return;
if (tabs.ActivateViewIndex == -1) return; // -1 means "don't do anything"
if (tabs.ActivateViewIndex >= tabs.HierarchicalViews.Count)
{
// Nothing we can do here
tabs.ActivateViewIndex = -1; // resetting to -1, so the next time this fires for real, we are guaranteed to get a changed event
return;
}
var groups = tabs.GetGroupedViews(tabs.HierarchicalViews);
var viewToSelect = tabs.HierarchicalViews[tabs.ActivateViewIndex];
foreach (var groupName in groups.Keys)
{
var group = groups[groupName];
var groupCounter = -1;
foreach (var view in group)
{
groupCounter++;
if (view == viewToSelect)
{
var groupTab = tabs.GetNewOrExistingGroupTab(group, groupName);
if (groupTab.Content == null) break;
var subTabs = groupTab.Content as TabControl;
if (subTabs == null) break;
subTabs.SelectedItem = subTabs.Items[groupCounter];
}
}
}
}
/// <summary>
/// Updates all properties related to changing view selection
/// </summary>
protected override void HandleSelectionChanged()
{
if (SelectedIndex < 0)
{
if (SelectedViewResult != null) SelectedViewResult = null;
return;
}
var tab = Items[SelectedIndex] as TabItem;
if (tab == null) return;
var subTabControl = tab.Content as TabControl;
if (subTabControl == null) return;
if (subTabControl.SelectedIndex < 0)
{
if (SelectedViewResult != null) SelectedViewResult = null;
return;
}
var tab2 = subTabControl.Items[subTabControl.SelectedIndex] as TabItem;
if (tab2 == null) return;
var viewResult = tab2.Content as ViewResult;
SelectedViewResult = viewResult;
RaiseNextViewSelected();
}
/// <summary>
/// References the selected view result
/// </summary>
/// <value>The selected view result.</value>
public ViewResult SelectedViewResult
{
get { return (ViewResult)GetValue(SelectedViewResultProperty); }
set { SetValue(SelectedViewResultProperty, value); }
}
/// <summary>
/// References the selected view result
/// </summary>
public static readonly DependencyProperty SelectedViewResultProperty = DependencyProperty.Register("SelectedViewResult", typeof(ViewResult), typeof(HierarchicalViewHostTabControl), new PropertyMetadata(null));
/// <summary>
/// Defines the title/label that is to be used for empty groups
/// </summary>
/// <value>The empty group title.</value>
public string EmptyGroupTitle
{
get { return (string) GetValue(EmptyGroupTitleProperty); }
set { SetValue(EmptyGroupTitleProperty, value); }
}
/// <summary>
/// Defines the title/label that is to be used for empty groups
/// </summary>
public static readonly DependencyProperty EmptyGroupTitleProperty = DependencyProperty.Register("EmptyGroupTitle", typeof (string), typeof (HierarchicalViewHostTabControl), new PropertyMetadata("File"));
/// <summary>
/// If set to true, all views that do not have a group defined will be rolled up into a single category
/// Note: The title of that category is defined through the EmptyGroupTitle property.
/// </summary>
/// <value><c>true</c> if [combine all empty groups]; otherwise, <c>false</c>.</value>
public bool CombineAllEmptyGroups
{
get { return (bool) GetValue(CombineAllEmptyGroupsProperty); }
set { SetValue(CombineAllEmptyGroupsProperty, value); }
}
/// <summary>
/// If set to true, all views that do not have a group defined will be rolled up into a single category
/// Note: The title of that category is defined through the EmptyGroupTitle property.
/// </summary>
public static readonly DependencyProperty CombineAllEmptyGroupsProperty = DependencyProperty.Register("CombineAllEmptyGroups", typeof (bool), typeof (HierarchicalViewHostTabControl), new PropertyMetadata(false, OnCombineAllEmptyGroupsChanged));
private static void OnCombineAllEmptyGroupsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tabs = d as HierarchicalViewHostTabControl;
if (tabs == null) return;
tabs.RepopulateViews();
}
/// <summary>
/// For internal use only
/// </summary>
public static readonly DependencyProperty AssociatedGroupNameProperty = DependencyProperty.RegisterAttached("AssociatedGroupName", typeof(string), typeof(HierarchicalViewHostTabControl), new PropertyMetadata(""));
/// <summary>
/// For internal use only
/// </summary>
/// <param name="dep">The object the property was set on</param>
/// <returns>Associated group name</returns>
public static string GetAssociatedGroupName(DependencyObject dep)
{
return (string)dep.GetValue(AssociatedGroupNameProperty);
}
/// <summary>
/// For internal use only
/// </summary>
/// <param name="dep">The object the property was set on</param>
/// <param name="value">The associated group name.</param>
public static void SetAssociatedGroupName(DependencyObject dep, string value)
{
dep.SetValue(AssociatedGroupNameProperty, value);
}
/// <summary>
/// Collection of open views
/// </summary>
/// <value>The hierarchical views.</value>
public ObservableCollection<ViewResult> HierarchicalViews
{
get { return (ObservableCollection<ViewResult>) GetValue(HierarchicalViewsProperty); }
set { SetValue(HierarchicalViewsProperty, value); }
}
/// <summary>
/// Collection of open views
/// </summary>
public static readonly DependencyProperty HierarchicalViewsProperty = DependencyProperty.Register("HierarchicalViews", typeof (ObservableCollection<ViewResult>), typeof (HierarchicalViewHostTabControl), new PropertyMetadata(null, OnHierarchicalViewsChanged));
/// <summary>
/// Style applied to the hierarchical sub-TabControl
/// </summary>
/// <value>The sub tab control style.</value>
public Style SubTabControlStyle
{
get { return (Style) GetValue(SubTabControlStyleProperty); }
set { SetValue(SubTabControlStyleProperty, value); }
}
/// <summary>
/// Style applied to the hierarchical sub-TabControl
/// </summary>
public static readonly DependencyProperty SubTabControlStyleProperty = DependencyProperty.Register("SubTabControlStyle", typeof (Style), typeof (HierarchicalViewHostTabControl), new PropertyMetadata(null));
/// <summary>
/// Fires when the views collection changes
/// </summary>
/// <param name="d">The d.</param>
/// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnHierarchicalViewsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tabs = d as HierarchicalViewHostTabControl;
if (tabs == null) return;
tabs.RepopulateViews();
var views = e.NewValue as ObservableCollection<ViewResult>;
if (views != null)
views.CollectionChanged += (s, e2) =>
{
if (e2.Action == NotifyCollectionChangedAction.Remove && e2.OldItems != null)
tabs.RemoveViews(e2.OldItems.OfType<ViewResult>().ToList());
else if (e2.Action == NotifyCollectionChangedAction.Add && e2.NewItems != null)
tabs.AddViews(e2.NewItems.OfType<ViewResult>().ToList());
else
tabs.RepopulateViews();
};
}
/// <summary>
/// Closes the specified views
/// </summary>
/// <param name="removedViewResults"></param>
private void RemoveViews(List<ViewResult> removedViewResults)
{
var groupPagesToRemove = new List<TabItem>();
foreach (var groupPage in Items.OfType<TabItem>())
{
var pagesToRemove = new List<TabItem>();
var subTabControl = groupPage.Content as TabControl;
if (subTabControl == null) continue;
foreach (var page in subTabControl.Items.OfType<TabItem>())
{
var viewResultContent = page.Content as ViewResult;
if (viewResultContent == null) continue;
if (removedViewResults.Contains(viewResultContent))
pagesToRemove.Add(page);
}
foreach (var pageToRemove in pagesToRemove)
subTabControl.Items.Remove(pageToRemove);
if (subTabControl.Items.Count < 1)
groupPagesToRemove.Add(groupPage);
}
foreach (var pageToRemove in groupPagesToRemove)
Items.Remove(pageToRemove);
}
/// <summary>
/// Adds new views to the current list of open views
/// </summary>
/// <param name="addedViews">The added views.</param>
/// <exception cref="System.NotImplementedException"></exception>
private void AddViews(List<ViewResult> addedViews)
{
if (addedViews == null) return;
var groups = GetGroupedViews(addedViews);
PopulateNewViews(groups);
}
/// <summary>
/// Repopulates the views from scratch.
/// </summary>
private void RepopulateViews()
{
Items.Clear();
if (HierarchicalViews == null) return;
var groups = GetGroupedViews(HierarchicalViews);
PopulateNewViews(groups);
}
/// <summary>
/// Adds new views into the tabs.
/// </summary>
/// <param name="groups">The groups.</param>
private void PopulateNewViews(Dictionary<string, List<ViewResult>> groups)
{
// Adding new items into the tabs
foreach (var groupName in groups.Keys)
{
var group = groups[groupName];
if (group.Count < 1) continue;
var groupTab = GetNewOrExistingGroupTab(group, groupName);
if (groupTab.Content == null) continue;
var subTabs = groupTab.Content as TabControl;
if (subTabs == null) continue;
foreach (var view in group)
{
var newSubTab = new HierarchicalViewHostTabItem { Content = view};
var foregroundBrush2 = SimpleView.GetTitleColor2(group[0].View);
if (foregroundBrush2 != null) newSubTab.Foreground = foregroundBrush2;
subTabs.Items.Add(newSubTab);
subTabs.SelectedItem = newSubTab;
}
}
}
/// <summary>
/// Creates a new tab, or returns the existing tab for the group
/// </summary>
/// <param name="group">The group.</param>
/// <param name="groupName">Name of the group.</param>
/// <returns>TabItem.</returns>
private TabItem GetNewOrExistingGroupTab(IList<ViewResult> group, string groupName)
{
var tab = Items.OfType<TabItem>().FirstOrDefault(t => GetAssociatedGroupName(t) == groupName);
if (tab != null)
{
SelectedItem = tab;
return tab;
}
var newTab = new TabItem();
SetAssociatedGroupName(newTab, groupName);
var backgroundColor = SimpleView.GetViewThemeColor(group[0].View);
if (backgroundColor != Colors.Transparent) newTab.Background = new SolidColorBrush(backgroundColor);
var foregroundBrush = SimpleView.GetTitleColor(group[0].View);
if (foregroundBrush != null) newTab.Foreground = foregroundBrush;
newTab.DataContext = group; // We assign the whole collection here so we can reference to it later
var subTabs = new TabControl();
if (SubTabControlStyle != null) subTabs.Style = SubTabControlStyle;
newTab.Content = subTabs;
Items.Add(newTab);
SelectedItem = newTab;
return newTab;
}
/// <summary>
/// Returns a list of grouped views.
/// </summary>
/// <param name="views">The views.</param>
/// <returns>Dictionary<System.String, List<ViewResult>>.</returns>
private Dictionary<string, List<ViewResult>> GetGroupedViews(IEnumerable<ViewResult> views)
{
var groups = new Dictionary<string, List<ViewResult>>();
foreach (var view in views.Where(v => v.View != null))
{
var group = SimpleView.GetGroup(view.View).Trim();
if (string.IsNullOrEmpty(group) && !CombineAllEmptyGroups)
group = SimpleView.GetTitle(view.View);
if (!groups.ContainsKey(group))
groups.Add(group, new List<ViewResult> { view });
else
groups[group].Add(view);
}
return groups;
}
}
/// <summary>
/// Specific tab item class used for hierarchical view hosts
/// </summary>
public class HierarchicalViewHostTabItem : TabItem
{
/// <summary>
/// Style used for the window that hosts the undock content
/// </summary>
public Style UndockWindowStyle
{
get { return (Style)GetValue(UndockWindowStyleProperty); }
set { SetValue(UndockWindowStyleProperty, value); }
}
/// <summary>
/// Style used for the window that hosts the undock content
/// </summary>
public static readonly DependencyProperty UndockWindowStyleProperty = DependencyProperty.Register("UndockWindowStyle", typeof(Style), typeof(HierarchicalViewHostTabControl), new PropertyMetadata(null));
/// <summary>
/// Undocks the current content into its own window
/// </summary>
public void UndockContent()
{
var viewResult = Content as ViewResult;
if (viewResult == null) return;
var parentTabControl = ElementHelper.FindParent<TabControl>(this);
if (parentTabControl == null) parentTabControl = ElementHelper.FindVisualTreeParent<TabControl>(this);
if (parentTabControl != null)
{
var oldIndex = parentTabControl.SelectedIndex;
var thisIndex = GetItemIndex(parentTabControl, this);
if (oldIndex == thisIndex)
{
var nextIndex = GetNextVisibleItemIndex(parentTabControl, oldIndex);
if (nextIndex != -1)
parentTabControl.SelectedIndex = nextIndex;
else
{
var previousIndex = GetPreviousVisibleItemIndex(parentTabControl, oldIndex);
if (previousIndex > -1)
parentTabControl.SelectedIndex = previousIndex;
else
{
parentTabControl.Visibility = Visibility.Collapsed;
SetParentTabItemVisibility(parentTabControl, Visibility.Collapsed);
}
}
}
}
Visibility = Visibility.Collapsed;
var window = new UndockedHierarchicalViewWindow(viewResult, this);
window.Show();
window.Activate();
}
/// <summary>
/// Docks the content back into the tab.
/// </summary>
public void DockContent()
{
Visibility = Visibility.Visible;
var parentTabControl = ElementHelper.FindParent<TabControl>(this);
if (parentTabControl == null) parentTabControl = ElementHelper.FindVisualTreeParent<TabControl>(this);
if (parentTabControl != null)
{
if (parentTabControl.Visibility == Visibility.Collapsed) parentTabControl.Visibility = Visibility.Visible;
var thisIndex = GetItemIndex(parentTabControl, this);
if (thisIndex > -1)
{
SetParentTabItemVisibility(parentTabControl, Visibility.Visible);
parentTabControl.SelectedIndex = thisIndex;
}
}
}
/// <summary>
/// Sets the visibility of the parent tab control of the current main tab within the hierarchy
/// </summary>
/// <param name="containedTabControl">The contained tab control.</param>
/// <param name="visibility">The visibility.</param>
private static void SetParentTabItemVisibility(TabControl containedTabControl, Visibility visibility)
{
var parentTab = ElementHelper.FindParent<TabItem>(containedTabControl);
if (parentTab == null) parentTab = ElementHelper.FindVisualTreeParent<TabItem>(containedTabControl);
if (parentTab == null) return;
parentTab.Visibility = visibility;
var parentTabControl = ElementHelper.FindParent<TabControl>(parentTab);
if (parentTabControl == null) ElementHelper.FindVisualTreeParent<TabControl>(parentTab);
if (parentTabControl == null) return;
var parentTabIndex = GetItemIndex(parentTabControl, parentTab);
if (visibility == Visibility.Visible)
parentTabControl.SelectedIndex = parentTabIndex;
else
{
var nextIndex = GetNextVisibleItemIndex(parentTabControl, parentTabIndex);
if (nextIndex > -1)
parentTabControl.SelectedIndex = nextIndex;
else
parentTabControl.SelectedIndex = GetPreviousVisibleItemIndex(parentTabControl, parentTabIndex); // Could be -1, but so be it
}
}
/// <summary>
/// Finds the index of the specified item in the items control
/// </summary>
/// <param name="itemsControl">The items control.</param>
/// <param name="tabToSearch">The tab to search.</param>
/// <returns>System.Int32.</returns>
private static int GetItemIndex(ItemsControl itemsControl, TabItem tabToSearch)
{
var thisIndex = -1;
foreach (var tabItem in itemsControl.Items)
{
thisIndex++;
if (tabItem == tabToSearch) return thisIndex;
}
return -1;
}
/// <summary>
/// Gets the index of the next visible item within an items control, relative to the index passed along.
/// </summary>
/// <param name="itemsControl">The items control.</param>
/// <param name="referenceIndex">Index of the reference item.</param>
/// <returns>System.Int32.</returns>
private static int GetNextVisibleItemIndex(ItemsControl itemsControl, int referenceIndex)
{
for (var counter = referenceIndex + 1; counter < itemsControl.Items.Count; counter++)
{
var element = itemsControl.Items[counter] as FrameworkElement;
if (element == null) continue;
if (element.Visibility == Visibility.Visible)
return counter;
}
return -1;
}
/// <summary>
/// Gets the index of the previous visible item within an items control, relative to the index passed along.
/// </summary>
/// <param name="itemsControl">The items control.</param>
/// <param name="referenceIndex">Index of the reference item.</param>
/// <returns>System.Int32.</returns>
private static int GetPreviousVisibleItemIndex(ItemsControl itemsControl, int referenceIndex)
{
for (var counter = referenceIndex - 1; counter >= 0; counter--)
{
var element = itemsControl.Items[counter] as FrameworkElement;
if (element == null) continue;
if (element.Visibility == Visibility.Visible)
return counter;
}
return -1;
}
}
/// <summary>
/// Special window class used to host undocked views
/// </summary>
/// <seealso cref="System.Windows.Window" />
public class UndockedHierarchicalViewWindow : Window
{
private readonly HierarchicalViewHostTabItem _hierarchicalViewHostTabItem;
/// <summary>
/// Initializes a new instance of the <see cref="UndockedHierarchicalViewWindow"/> class.
/// </summary>
/// <param name="viewResult">The view result.</param>
/// <param name="hierarchicalViewHostTabItem">The hierarchical view host tab item.</param>
public UndockedHierarchicalViewWindow(ViewResult viewResult, HierarchicalViewHostTabItem hierarchicalViewHostTabItem)
{
Closing += (s, e) => { DockContent(); };
DataContext = viewResult;
_hierarchicalViewHostTabItem = hierarchicalViewHostTabItem;
if (hierarchicalViewHostTabItem.UndockWindowStyle != null) Style = hierarchicalViewHostTabItem.UndockWindowStyle;
if (viewResult != null)
{
Title = viewResult.ViewTitle;
if (viewResult.View != null)
{
var viewColor = SimpleView.GetViewThemeColor(viewResult.View);
if (viewColor != Colors.Transparent) Background = new SolidColorBrush(viewColor);
}
}
}
/// <summary>
/// Docks the content back into the parent tab control.
/// </summary>
public void DockContent()
{
_hierarchicalViewHostTabItem.DockContent();
}
}
/// <summary>
/// Special undock icon for undocking the hierarchical tab control
/// </summary>
/// <seealso cref="CODE.Framework.Wpf.Mvvm.ThemeIcon" />
public class UndockIcon : ThemeIcon
{
/// <summary>
/// Initializes a new instance of the <see cref="UndockIcon"/> class.
/// </summary>
public UndockIcon()
{
ToolTip = "Pop-Out";
IsHitTestVisible = true;
Background = Brushes.Transparent;
Loaded += (s, e) => { IconResourceKey = "CODE.Framework-Icon-UnPin"; };
}
/// <summary>
/// Handles the <see cref="E:MouseDown" /> event.
/// </summary>
/// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
var tab = ElementHelper.FindParent<HierarchicalViewHostTabItem>(this);
if (tab == null)
tab = ElementHelper.FindVisualTreeParent<HierarchicalViewHostTabItem>(this);
if (tab != null)
{
tab.UndockContent();
e.Handled = true;
return;
}
}
base.OnMouseDown(e);
}
}
/// <summary>
/// Special class that is able to close the current view (assuming it exposes a CloseViewAction)
/// </summary>
public class CloseViewTabIcon : ThemeIcon
{
/// <summary>
/// Initializes a new instance of the <see cref="CloseViewTabIcon"/> class.
/// </summary>
public CloseViewTabIcon()
{
ToolTip = "Close";
IsHitTestVisible = true;
Background = Brushes.Transparent;
Loaded += (s, e) =>
{
IconResourceKey = "CODE.Framework-Icon-ClosePane";
var actionHost = GetActionsHost();
if (actionHost != null)
{
var closeAction = actionHost.Actions.OfType<CloseCurrentViewAction>().FirstOrDefault();
CanClose = closeAction != null;
}
};
DataContextChanged += (s2, e2) =>
{
var actionHost = GetActionsHost();
if (actionHost != null)
{
var closeAction = actionHost.Actions.OfType<CloseCurrentViewAction>().FirstOrDefault();
CanClose = closeAction != null;
}
};
}
/// <summary>
/// Indicates whether the object is able to close the current view
/// </summary>
public bool CanClose
{
get { return (bool)GetValue(CanCloseProperty); }
set { SetValue(CanCloseProperty, value); }
}
/// <summary>
/// Indicates whether the object is able to close the current view
/// </summary>
public static readonly DependencyProperty CanCloseProperty = DependencyProperty.Register("CanClose", typeof(bool), typeof(CloseViewTabIcon), new PropertyMetadata(false));
/// <summary>
/// Retrieves the model that contains a list of actions (if applicable)
/// </summary>
/// <returns></returns>
private IHaveActions GetActionsHost()
{
var tab = ElementHelper.FindParent<TabItem>(this);
if (tab == null)
tab = ElementHelper.FindVisualTreeParent<TabItem>(this);
if (tab == null) return null;
var viewResult = tab.Content as ViewResult;
if (viewResult == null)
{
var resultList = tab.DataContext as IEnumerable<ViewResult>;
if (resultList != null)
viewResult = resultList.FirstOrDefault();
}
if (viewResult != null)
return viewResult.Model as IHaveActions;
return null;
}
/// <summary>
/// Handles the <see cref="E:MouseDown" /> event.
/// </summary>
/// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
var actionHost = GetActionsHost();
if (actionHost != null)
{
var closeAction = actionHost.Actions.OfType<CloseCurrentViewAction>().FirstOrDefault();
if (closeAction != null && closeAction.CanExecute(null))
{
closeAction.Execute(null);
e.Handled = true;
return;
}
}
}
base.OnMouseDown(e);
}
}
/// <summary>
/// Special tab control class for top-level views
/// </summary>
public class TopLevelViewHostTabControl : ViewHostTabControl
{
/// <summary>Link to a normal view host, which can potentially be disabled whenever top level views are active</summary>
public UIElement NormalViewHost
{
get { return (UIElement)GetValue(NormalViewHostProperty); }
set { SetValue(NormalViewHostProperty, value); }
}
/// <summary>Link to a normal view host, which can potentially be disabled whenever top level views are active</summary>
public static readonly DependencyProperty NormalViewHostProperty = DependencyProperty.Register("NormalViewHost", typeof (UIElement), typeof (TopLevelViewHostTabControl), new FrameworkPropertyMetadata(null) {BindsTwoWayByDefault = false});
/// <summary>Defines whether normal views should be disabled when top level views are active</summary>
public bool DisableNormalViewHostWhenTopLevelIsActive
{
get { return (bool)GetValue(DisableNormalViewHostWhenTopLevelIsActiveProperty); }
set { SetValue(DisableNormalViewHostWhenTopLevelIsActiveProperty, value); }
}
/// <summary>Defines whether normal views should be disabled when top level views are active</summary>
public static readonly DependencyProperty DisableNormalViewHostWhenTopLevelIsActiveProperty = DependencyProperty.Register("DisableNormalViewHostWhenTopLevelIsActive", typeof(bool), typeof(TopLevelViewHostTabControl), new PropertyMetadata(true));
/// <summary>InputBindingsSet</summary>
/// <param name="obj">Object to get value from</param>
/// <returns>True/False</returns>
public static bool GetInputBindingsSet(DependencyObject obj)
{
return (bool)obj.GetValue(InputBindingsSetProperty);
}
/// <summary>InputBindingsSet</summary>
/// <param name="obj">Object to set the value on</param>
/// <param name="value">Value to set</param>
public static void SetInputBindingsSet(DependencyObject obj, bool value)
{
obj.SetValue(InputBindingsSetProperty, value);
}
/// <summary>Indicates whether input bindings have been set on a certain control of interest</summary>
public static readonly DependencyProperty InputBindingsSetProperty = DependencyProperty.RegisterAttached("InputBindingsSet", typeof(bool), typeof(TopLevelViewHostTabControl), new PropertyMetadata(false));
/// <summary>Called to update the current selection when items change.</summary>
/// <param name="e">The event data for the System.Windows.Controls.ItemContainerGenerator.ItemsChanged event</param>
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
if (NormalViewHost != null && DisableNormalViewHostWhenTopLevelIsActive)
NormalViewHost.IsEnabled = Items.Count < 1;
}
/// <summary>Raises the System.Windows.Controls.Primitives.Selector.SelectionChanged routed event</summary>
/// <param name="e">Provides data for System.Windows.Controls.SelectionChangedEventArgs.</param>
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
var result = SelectedContent as ViewResult;
if (result == null || result.View == null) return;
FocusHelper.FocusDelayed(this);
InputBindings.Clear();
foreach (InputBinding binding in result.View.InputBindings)
InputBindings.Add(binding);
}
}
}
|
namespace ApartmentApps.Api.Modules
{
public enum TransactionState
{
Open, Failed, Approved
}
} |
using System;
namespace ScheduleService.Model
{
public interface IClock
{
DateTime Now();
DateTime GetTimeLimit();
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLitePCL;
using Windows.UI.Xaml.Media.Imaging;
namespace uwpMiddleProject.ViewModels
{
class AnswersViewModels
{
private static AnswersViewModels instance;
private ObservableCollection<Models.AnswersModel> allRecords = new ObservableCollection<Models.AnswersModel>();
public ObservableCollection<Models.AnswersModel> AllRecords { get { return this.allRecords; } }
private Models.AnswersModel selectedRecord = null;
public Models.AnswersModel SelectedRecord
{
get
{
return selectedRecord;
}
set
{
this.selectedRecord = value;
}
}
private AnswersViewModels()
{
this.allRecords = Services.DbContext.getAllRecord();
/*
Models.AnswersModel initRecord = new Models.AnswersModel();
initRecord.score = 80;
initRecord.date = DateTimeOffset.Now;
this.allRecords.Add(initRecord);
*/
}
public static AnswersViewModels GetInstance()
{
if (instance == null)
{
instance = new AnswersViewModels();
}
return instance;
}
public void AddRecord(Models.AnswersModel temp)
{
this.allRecords.Add(temp);
Services.DbContext.InsertData(temp.id, temp.score, temp.answerTo1, temp.answerTo2, temp.answerTo3, temp.answerTo4, temp.answerTo5, temp.answerTo6, temp.answerTo7, temp.answerTo8, temp.answerTo9, temp.answerTo10,temp.date,temp.imauri);
}
/*
public void AddRecord(string id, string answerTo1, string answerTo2, string answerTo3, string answerTo4, string answerTo5, string answerTo6, string answerTo7, string answerTo8, string answerTo9, string answerTo10, int score, DateTimeOffset date, BitmapImage coverImage)
{
Models.AnswersModel temp = new Models.AnswersModel(id, score, answerTo1, answerTo2, answerTo3, answerTo4, answerTo5, answerTo6, answerTo7, answerTo8, answerTo9, answerTo10, date, coverImage);
this.allRecords.Add(temp);
}*/
public void RemoveRecord()
{
this.allRecords.Remove(this.selectedRecord);
Services.DbContext.DeleteData(this.selectedRecord.id);
this.selectedRecord = null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
namespace WasaaMP {
public class Interactive : MonoBehaviourPun {
// Start is called before the first frame update
MonoBehaviourPun support = null ;
void Start () {
}
// Update is called once per frame
void Update () {
//Debug.Log("test");
}
void OnTriggerEnter (Collider other) {
//Debug.Log("test");
//print (name + " : OnCollisionEnter") ;
var hit = other.gameObject ;
var cursor = hit.GetComponent<LaserScript> () ;
//if (cursor != null) {
//Renderer renderer = GetComponentInChildren <Renderer> () ;
//renderer.material.color = Color.blue ;
//}
}
void OnTriggerExit (Collider other) {
//print (name + " : OnCollisionExit") ;
var hit = other.gameObject ;
var cursor = hit.GetComponent<LaserScript> () ;
//if (cursor != null) {
//Renderer renderer = GetComponentInChildren <Renderer> () ;
//renderer.material.color = Color.red ;
//}
}
public void SetSupport (MonoBehaviourPun support) {
this.support = support ;
if (support != null)
{
if (GetComponent<Rigidbody>() != null) {
GetComponent<Rigidbody>().isKinematic = true;
print("Picked up");
transform.SetParent(support.transform);
}
} else {
transform.SetParent(null);
}
}
public void RemoveSupport () {
GetComponent<Rigidbody>().isKinematic = false;
transform.SetParent (null) ;
support = null ;
}
public MonoBehaviourPun GetSupport () {
return support ;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.Diagnostics;
using DevExpress.XtraBars.Ribbon;
using System.Windows.Forms;
namespace DevExpress.XtraTabbedMdi
{
public class XtraTabbedMdiManagerEX : DevExpress.XtraTabbedMdi.XtraTabbedMdiManager
{
Image _backImage = null;
Image _BigLogo = null;
public XtraTabbedMdiManagerEX()
: base()
{
}
public XtraTabbedMdiManagerEX(IContainer container)
: base(container)
{
}
[DefaultValue(null)]
public Image BackImage
{
set
{
_backImage = value;
}
get
{
return _backImage;
}
}
[DefaultValue(null)]
public Image BigLogo
{
set
{
_BigLogo = value;
}
get
{
return _BigLogo;
}
}
protected override void OnSelectedPageChanged(object sender, XtraTab.ViewInfo.ViewInfoTabPageChangedEventArgs e)
{
base.OnSelectedPageChanged(sender, e);
if (SelectedPage != null)
{
RibbonForm form = this.SelectedPage.MdiChild as RibbonForm;
RibbonForm formmdi = this.MdiParent as RibbonForm;
if (form != null && formmdi != null && formmdi.Ribbon != null && form.Ribbon.MergedCategories.TotalCategory.GetFirstVisiblePage()!=null )
{
formmdi.Ribbon.SelectedPage = formmdi.Ribbon.MergedCategories.TotalCategory.GetPageByText(form.Ribbon.MergedCategories.TotalCategory.GetFirstVisiblePage().Text);
}
}
}
protected override void DrawNC(DevExpress.Utils.Drawing.DXPaintEventArgs e)
{
if (this.Pages.Count > 0)
{
base.DrawNC(e);
}
else
{
if (_backImage != null)
e.Graphics.DrawImage(_backImage, 0,0,Bounds.Width + 1, Bounds.Height + 1);
//e.Graphics.DrawImage(_backImage, Bounds.Width - _backImage.Width, Bounds.Height - _backImage.Height);
if (_BigLogo != null)
e.Graphics.DrawImage(_BigLogo, 10/PrimaryScreen.ScaleX,Bounds.Height - _BigLogo.Height / PrimaryScreen.ScaleY - 20,_BigLogo.Width / PrimaryScreen.ScaleY, _BigLogo.Height / PrimaryScreen.ScaleY);
}
}
private void InitializeComponent()
{
//
// XtraTabbedMdiManagerEX
//
this.Appearance.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
this.AppearancePage.Header.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
this.AppearancePage.Header.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Default;
this.AppearancePage.Header.TextOptions.HotkeyPrefix = DevExpress.Utils.HKeyPrefix.Default;
this.AppearancePage.Header.TextOptions.Trimming = DevExpress.Utils.Trimming.Default;
this.AppearancePage.Header.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Default;
this.AppearancePage.Header.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Default;
this.AppearancePage.HeaderActive.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
this.AppearancePage.HeaderActive.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Default;
this.AppearancePage.HeaderActive.TextOptions.HotkeyPrefix = DevExpress.Utils.HKeyPrefix.Default;
this.AppearancePage.HeaderActive.TextOptions.Trimming = DevExpress.Utils.Trimming.Default;
this.AppearancePage.HeaderActive.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Default;
this.AppearancePage.HeaderActive.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Default;
this.AppearancePage.HeaderDisabled.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
this.AppearancePage.HeaderDisabled.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Default;
this.AppearancePage.HeaderDisabled.TextOptions.HotkeyPrefix = DevExpress.Utils.HKeyPrefix.Default;
this.AppearancePage.HeaderDisabled.TextOptions.Trimming = DevExpress.Utils.Trimming.Default;
this.AppearancePage.HeaderDisabled.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Default;
this.AppearancePage.HeaderDisabled.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Default;
this.AppearancePage.HeaderHotTracked.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
this.AppearancePage.HeaderHotTracked.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Default;
this.AppearancePage.HeaderHotTracked.TextOptions.HotkeyPrefix = DevExpress.Utils.HKeyPrefix.Default;
this.AppearancePage.HeaderHotTracked.TextOptions.Trimming = DevExpress.Utils.Trimming.Default;
this.AppearancePage.HeaderHotTracked.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Default;
this.AppearancePage.HeaderHotTracked.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Default;
this.AppearancePage.PageClient.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal;
this.AppearancePage.PageClient.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Default;
this.AppearancePage.PageClient.TextOptions.HotkeyPrefix = DevExpress.Utils.HKeyPrefix.Default;
this.AppearancePage.PageClient.TextOptions.Trimming = DevExpress.Utils.Trimming.Default;
this.AppearancePage.PageClient.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Default;
this.AppearancePage.PageClient.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Default;
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Marketplaces.Entityes;
namespace Infra.Mapeamentos
{
class MappingEmailTemplate : EntityTypeConfiguration<EmailTemplate>
{
public MappingEmailTemplate()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
this.Property(t => t.Slug)
.IsRequired()
.HasMaxLength(100);
this.Property(t => t.Subject)
.IsRequired()
.HasMaxLength(100);
this.Property(t => t.Body)
.IsRequired();
// Table & Column Mappings
this.ToTable("EmailTemplates");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.Slug).HasColumnName("Slug");
this.Property(t => t.Subject).HasColumnName("Subject");
this.Property(t => t.Body).HasColumnName("Body");
this.Property(t => t.SendCopy).HasColumnName("SendCopy");
this.Property(t => t.Created).HasColumnName("Created");
this.Property(t => t.LastUpdated).HasColumnName("LastUpdated");
}
}
}
|
// See https://aka.ms/new-console-template for more information
public interface IParentSelectionStrategy
{
Solution SelectParent(Population population);
}
public class TournamentSelectionStrategy : IParentSelectionStrategy
{
private readonly Random _random;
private readonly int _tournamentSize;
private readonly IComparer<Solution> _fitnessComparer;
public TournamentSelectionStrategy(
int tournamentSize, IComparer<Solution> fitnessComparer)
{
_random = new Random();
_tournamentSize = tournamentSize;
_fitnessComparer = fitnessComparer;
}
public Solution SelectParent(Population population)
=> Enumerable.Range(0, _tournamentSize)
.Select(_ => population.Solutions[_random.Next(population.Solutions.Count)])
.Max(_fitnessComparer);
}
public class RouletteWheelSelectionStrategy : IParentSelectionStrategy
{
private readonly Random _random;
public RouletteWheelSelectionStrategy()
{
_random = new Random();
}
public Solution SelectParent(Population population)
{
var totalFitness = population.Solutions
.Select(s => s.TotalValue).Sum();
var roulettValue = (decimal)(_random.NextDouble() * (double)totalFitness);
var partialSum = 0M;
for (int i = 0; i < population.Solutions.Count; i++)
{
partialSum += population.Solutions[i].TotalValue;
if (partialSum >= roulettValue)
return population.Solutions[i];
}
return population.Solutions.Last();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera_beweging : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private float transitionTime = 1;
void Update()
{
if (transform.position.x - target.position.x >= 8)
startmove(-16, 0);
if (transform.position.x - target.position.x <= -8)
startmove(16, 0);
if (transform.position.y - target.position.y >= 5.5f)
startmove(0, -11);
if (transform.position.y - target.position.y <= -5.5f)
startmove(0, 11);
}
private void startmove(float x, float y)
{
StartCoroutine(IMoveCamera(x,y));
}
IEnumerator IMoveCamera(float x, float y)
{
float time = 0;
Vector3 startPos = transform.position;
Vector3 eindPos = transform.position + new Vector3(x, y, 0);
while (time < 1)
{
transform.position = Vector3.Lerp(startPos, eindPos, time);
time += Time.deltaTime / transitionTime;
yield return new WaitForEndOfFrame();
}
transform.position = eindPos;
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using TimeClock.Data.Models;
namespace TimeClock.Web.Models
{
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name="Time")]
public DateTime? LastPunchTime { get; set; }
[Display(Name = "Status")]
public TimePunchStatus CurrentStatus { get; set; }
[Display(Name = "Name")]
public string FullName
{
get { return FirstName + " " + LastName; }
}
public string CurrentStatusClass
{
get
{
return CurrentStatus == TimePunchStatus.PunchedIn ?
"punched-in" : "punched-out";
}
}
}
public class EmployeeCreateViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
public class EmployeeManagerViewModel
{
public int EmployeeId { get; set; }
public string FullName { get; set; }
}
} |
using PhobiaX.Cleanups;
using PhobiaX.Game.GameObjects;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhobiaX.Physics
{
public class CollissionObserver : ICleanable
{
protected IList<IGameObject> gameObjects = new List<IGameObject>();
protected IList<Action<IGameObject, IList<IGameObject>>> callbacks = new List<Action<IGameObject, IList<IGameObject>>>();
public void OnCollissionCallback(Action<IGameObject, IList<IGameObject>> callback)
{
callbacks.Add(callback);
}
public void ObserveCollission(IGameObject gameObject)
{
this.gameObjects.Add(gameObject);
}
public virtual void Cleanup(IGameObject gameObject)
{
this.gameObjects.Remove(gameObject);
}
public virtual void CleanupAll()
{
gameObjects.Clear();
callbacks.Clear();
}
public void Evaluate()
{
var collides = new Dictionary<IGameObject, IList<IGameObject>>();
foreach (var gameObject in gameObjects)
{
var collidingObjects = FindCollidingObjects(gameObject);
collides.Add(gameObject, collidingObjects);
}
foreach (var collide in collides)
{
TriggerCallback(collide.Key, collide.Value);
}
}
public IList<IGameObject> FindCollidingObjects(IGameObject testedObject)
{
var output = new List<IGameObject>();
foreach (var gameObject in gameObjects)
{
if (testedObject == gameObject)
{
continue;
}
if (testedObject.ColladableObject?.IsColliding(gameObject.ColladableObject) ?? false)
{
output.Add(gameObject);
}
}
return output;
}
protected void TriggerCallback(IGameObject testedObject, IList<IGameObject> colliders)
{
foreach (var callback in callbacks)
{
callback(testedObject, colliders);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using TraceWizard.Entities;
using TraceWizard.Notification;
namespace TraceWizard.TwApp {
public partial class SelectionRuler : UserControl {
public Events Events { get; set; }
public bool VisibleRequested;
public bool CollapsedNotHidden;
public SelectionRuler() {
InitializeComponent();
Properties.Settings.Default.PropertyChanged += new PropertyChangedEventHandler(Default_PropertyChanged);
}
public void Events_PropertyChanged(object sender, PropertyChangedEventArgs e) {
switch (e.PropertyName) {
case TwNotificationProperty.OnAddEvent:
Render();
break;
}
}
public void Initialize() {
Events.PropertyChanged += new PropertyChangedEventHandler(Events_PropertyChanged);
SetSettingTopAlignment();
VisibleRequested = Properties.Settings.Default.ShowSelectionRulerByDefault;
CollapsedNotHidden = !Properties.Settings.Default.ShowSelectionRulerByDefault;
SetVisibility();
}
void SetVisibility() {
if (VisibleRequested)
Visibility = Visibility.Visible;
else
Visibility = CollapsedNotHidden ? Visibility.Collapsed : Visibility.Hidden;
}
void Default_PropertyChanged(object sender, PropertyChangedEventArgs e) {
switch (e.PropertyName) {
case "ShowSelectionRulerAboveGraph":
SetTopAlignment();
SetSettingTopAlignment();
break;
case "SelectionTickColor":
break;
}
}
public static readonly DependencyProperty TopAlignmentProperty =
DependencyProperty.Register("TopAlignment", typeof(bool),
typeof(SelectionRuler), new UIPropertyMetadata(true));
public bool TopAlignment {
get { return (bool)GetValue(TopAlignmentProperty); }
set {
SetValue(TopAlignmentProperty, value);
SetTopAlignment();
}
}
void SetTopAlignment() {
var panel = this.Parent as DockPanel;
DockPanel.SetDock((DockPanel)this.Parent, TopAlignment ? Dock.Top : Dock.Bottom);
}
void SetSettingTopAlignment() {
TopAlignment = Properties.Settings.Default.ShowSelectionRulerAboveGraph;
}
public void Clear() {
eventsInRuler.Clear();
Canvas.Children.Clear();
}
double WidthMultiplier = 0.0;
public void Render() {
Render(WidthMultiplier);
}
public void Render(double widthMultiplier) {
WidthMultiplier = widthMultiplier;
SetVisibility();
if (Visibility != Visibility.Visible) {
Clear();
return;
}
if (Canvas.Children.Count == 0)
RenderInitial();
else
RenderUpdate();
}
List<Event> eventsInRuler = new List<Event>();
void Add(Event @event) {
var tick = new SelectionTick();
tick.Event = @event;
tick.OnRemove = Remove;
tick.OnChangePosition = ChangePosition;
tick.Initialize();
const int widthOfTick = 6;
Canvas.SetBottom(tick, 0);
double offset = (@event.StartTime.Subtract(Events.StartTime).TotalSeconds * WidthMultiplier) - widthOfTick / 2;
Canvas.SetLeft(tick, offset);
Canvas.Children.Add(tick);
eventsInRuler.Add(@event);
}
public delegate void OnRemove(SelectionTick tick);
void Remove(SelectionTick tick) {
eventsInRuler.Remove(tick.Event);
Canvas.Children.Remove(tick);
}
public delegate void OnChangePosition(SelectionTick tick);
void ChangePosition(SelectionTick tick) {
double offset = tick.Event.StartTime.Subtract(Events.StartTime).TotalSeconds * WidthMultiplier;
Canvas.SetLeft(tick, offset);
}
void RenderInitial() {
foreach (Event @event in Events)
Add(@event);
}
void RenderUpdate() {
foreach (Event @event in Events) {
if (!eventsInRuler.Contains(@event))
Add(@event);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace telefonszamok
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
betolt();
}
public void betolt()
{
string[] adat = File.ReadAllLines(@"telefonszamok.txt");
foreach ( var szam in adat)
{
if (szam.Length == 13)
{
if (szam.Contains('/'))
{
joSzamok.Items.Add(szam.Substring(3));
}
else
rosszSzamok.Items.Add(szam);
}
else
{
if (szam.Contains('/') && szam.Length == 10)
{
joSzamok.Items.Add(szam);
}
else
rosszSzamok.Items.Add(szam);
}
}
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void egyBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "1";
}
private void kettoBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "2";
}
private void haromBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "3";
}
private void negyBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "4";
}
private void otBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "5";
}
private void hatBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "6";
}
private void hetBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "7";
}
private void nyolcBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "8";
}
private void kilencBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "9";
}
private void perBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "/";
}
private void nullaBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "0";
}
private void pluszBTN_Click(object sender, EventArgs e)
{
szamBOX.Text += "+";
}
private void torolBTN_Click(object sender, EventArgs e)
{
if (szamBOX.Text != "")
{
szamBOX.Text = szamBOX.Text.Remove(szamBOX.Text.Length - 1);
}
}
private void rogzitBTN_Click(object sender, EventArgs e)
{
string telszam = szamBOX.Text;
if(telszam.Length == 13)
{
if (telszam.IndexOf('/') == 5)
{
joSzamok.Items.Add(telszam.Substring(3));
}
else
{
rosszSzamok.Items.Add(telszam);
}
}
else
{
if (telszam.IndexOf('/') == 3 && telszam.Length == 10 && !telszam.Contains("+36"))
{
joSzamok.Items.Add(telszam);
}
else
{
rosszSzamok.Items.Add(telszam);
}
}
}
public void ellenoriz()
{
string szam = szamBOX.Text;
if (szam.Length == 13)
{
if (szam.IndexOf('/') == 5)
{
formazBTN.Enabled = true;
rogzitBTN.Enabled = true;
}
else
{
formazBTN.Enabled = false;
rogzitBTN.Enabled = false;
}
}
else
{
if (szam.IndexOf('/') == 3 && szam.Length == 10 && !szam.Contains("+36"))
{
formazBTN.Enabled = true;
rogzitBTN.Enabled = true;
}
else
{
formazBTN.Enabled = false;
rogzitBTN.Enabled = false;
}
}
}
private void szamBOX_TextChanged(object sender, EventArgs e)
{
ellenoriz();
}
private void formazBTN_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace LibraryManagementSystem
{
public partial class add_student : Form
{
SqlConnection conn = new SqlConnection("Data Source=desktop-uqn5rjf\\sqlexpress12; Initial Catalog=library_management; Integrated Security=true;");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adapt;
string imgLoc = "";
public add_student()
{
InitializeComponent();
}
private void browse_click(object sender, EventArgs e)
{
try {
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files (*.jpg)|*.jpg|BMP Files (*.bmp)|*.bmp|GIF Files (*.gif)|*.gif|All Files(*.*)|*.*";
dlg.Title = "Select student picture.";
if (dlg.ShowDialog() == DialogResult.OK)
{
imgLoc = dlg.FileName.ToString();
pictureBox1.ImageLocation = imgLoc;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
try
{
if(name_text.Text != "" && enrolment_text.Text != "" && department_text.Text != "" && semester_text.Text != "" && contact_text.Text != "" && email_text.Text != "" && imgLoc != "")
{
byte[] img = null;
FileStream fs= new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "addStudent";
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name_text.Text;
cmd.Parameters.Add("@enrolment", SqlDbType.VarChar).Value = enrolment_text.Text;
cmd.Parameters.Add("@department", SqlDbType.VarChar).Value = department_text.Text;
cmd.Parameters.Add("@semester", SqlDbType.VarChar).Value = semester_text.Text;
cmd.Parameters.Add("@contact", SqlDbType.VarChar).Value = contact_text.Text;
cmd.Parameters.Add("@image", SqlDbType.Image).Value = img;
cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = email_text.Text;
// cmd = new SqlCommand("insert into student_info (name, enrolment_no, department, semester, contact_no, email, image) Values('"+ name_text.Text+ "','" + enrolment_text.Text + "','" + department_text.Text + "','" + semester_text.Text + "','" + contact_text.Text + "','" + email_text.Text + "', @img)", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Record added succesfully.");
}
else
{
MessageBox.Show("Please fill all the details.");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
private void add_student_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using alg;
/*
* tags: stack
*/
namespace leetcode
{
public class Lc224_Basic_Calculator
{
// The expression string may contain '+', '-', '(', ')', digits and spaces.
public int Calculate(string s)
{
int ret = 0;
int sign = 1;
var stack = new Stack<int>();
for (int i = 0; i < s.Length; i++)
{
if (char.IsDigit(s[i]))
{
int val = s[i] - '0';
for (; i + 1 < s.Length && char.IsDigit(s[i + 1]); i++)
val = val * 10 + (s[i + 1] - '0');
ret += val * sign;
}
else if (s[i] == '+')
{
sign = 1;
}
else if (s[i] == '-')
{
sign = -1;
}
else if (s[i] == '(')
{
stack.Push(ret);
stack.Push(sign);
ret = 0; // reset
sign = 1;
}
else if (s[i] == ')')
{
ret *= stack.Pop(); // sign
ret += stack.Pop();
}
}
return ret;
}
// Lc227: The expression string may contain '+', '-', '*', '/', digits and spaces.
public int CalculateII(string s)
{
int ret = 0, num = 0;
char op = '+';
for (int i = 0; i < s.Length; i++)
{
if (char.IsDigit(s[i]))
{
i--;
int val = GetNumber(s, ref i);
num = op == '+' ? val : -val;
}
else if (s[i] == '+' || s[i] == '-')
{
ret += num;
op = s[i];
}
else if (s[i] == '*')
{
int val = GetNumber(s, ref i);
num *= val;
}
else if (s[i] == '/')
{
int val = GetNumber(s, ref i);
num /= val;
}
}
return ret + num;
}
// The expression string may contain '+', '-', '*', '/', digits and spaces.
public int Calculate2(string s)
{
s = '+' + s;
var stack = new Stack<int>();
for (int i = 0; i < s.Length; i++)
{
switch (s[i])
{
case '+':
stack.Push(GetNumber(s, ref i));
break;
case '-':
stack.Push(-GetNumber(s, ref i));
break;
case '*':
stack.Push(stack.Pop() * GetNumber(s, ref i));
break;
case '/':
stack.Push(stack.Pop() / GetNumber(s, ref i));
break;
}
}
int ret = 0;
while (stack.Count > 0) ret += stack.Pop();
return ret;
}
int GetNumber(string s, ref int pos)
{
int ret = 0;
pos++;
while (pos < s.Length && s[pos] == ' ') pos++;
while (pos < s.Length && char.IsDigit(s[pos]))
ret = ret * 10 + (s[pos++] - '0');
pos--;
return ret;
}
public void Test()
{
Console.WriteLine(Calculate("1 + 1") == 2);
Console.WriteLine(Calculate(" 2-1 + 2 ") == 3);
Console.WriteLine(Calculate("(1+(4+5+2)-3)+(6+8)") == 23);
Console.WriteLine(CalculateII("3+2*2 ") == 7);
Console.WriteLine(CalculateII("3/2") == 1);
Console.WriteLine(CalculateII(" 3+5 / 2 ") == 5);
Console.WriteLine(Calculate2("3+2*2 ") == 7);
Console.WriteLine(Calculate2("3/2") == 1);
Console.WriteLine(Calculate2(" 3+5 / 2 ") == 5);
}
}
}
|
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels;
using Profiling2.Web.Mvc.Controllers;
using SharpArch.NHibernate.Web.Mvc;
using SharpArch.Web.Mvc.JsonNet;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers
{
[PermissionAuthorize(AdminPermission.CanViewAndChangePersonRestrictedNotes)]
public class PersonRestrictedNotesController : BaseController
{
protected readonly IPersonTasks personTasks;
public PersonRestrictedNotesController(IPersonTasks personTasks)
{
this.personTasks = personTasks;
}
public JsonNetResult Json(int personId)
{
Person person = this.personTasks.GetPerson(personId);
if (person != null)
return JsonNet(new Dictionary<string, object>() { { "Notes", person.PersonRestrictedNotes.Select(x => new PersonRestrictedNoteViewModel(x)) } });
Response.StatusCode = (int)HttpStatusCode.NotFound;
return JsonNet(string.Empty);
}
public ActionResult CreateModal(int personId)
{
Person p = this.personTasks.GetPerson(personId);
if (p != null)
{
PersonRestrictedNoteViewModel vm = new PersonRestrictedNoteViewModel(p);
return View(vm);
}
return new HttpNotFoundResult();
}
[HttpPost]
[Transaction]
public JsonNetResult CreateModal(PersonRestrictedNoteViewModel vm)
{
if (ModelState.IsValid)
{
Person p = this.personTasks.GetPerson(vm.PersonId);
if (p != null)
{
PersonRestrictedNote n = new PersonRestrictedNote();
n.Person = p;
n.Note = vm.Note;
this.personTasks.SavePersonRestrictedNote(n);
return JsonNet(string.Empty);
}
else
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return JsonNet("Person does not exist.");
}
}
else
return JsonNet(this.GetErrorsForJson());
}
public ActionResult EditModal(int personId, int id)
{
Person p = this.personTasks.GetPerson(personId);
PersonRestrictedNote n = this.personTasks.GetPersonRestrictedNote(id);
if (p != null && n != null)
{
PersonRestrictedNoteViewModel vm = new PersonRestrictedNoteViewModel(n);
return View(vm);
}
return new HttpNotFoundResult();
}
[HttpPost]
[Transaction]
public JsonNetResult EditModal(PersonRestrictedNoteViewModel vm)
{
if (ModelState.IsValid)
{
Person p = this.personTasks.GetPerson(vm.PersonId);
PersonRestrictedNote n = this.personTasks.GetPersonRestrictedNote(vm.Id);
if (p != null && n != null)
{
n.Person = p;
n.Note = vm.Note;
this.personTasks.SavePersonRestrictedNote(n);
return JsonNet(string.Empty);
}
else
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return JsonNet("Person or note does not exist.");
}
}
else
return JsonNet(this.GetErrorsForJson());
}
[Transaction]
public JsonNetResult Delete(int id)
{
PersonRestrictedNote n = this.personTasks.GetPersonRestrictedNote(id);
if (n != null)
{
this.personTasks.DeletePersonRestrictedNote(n);
Response.StatusCode = (int)HttpStatusCode.OK;
return JsonNet("Person note successfully deleted.");
}
else
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return JsonNet("Person note not found.");
}
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace App.Web.AsyncApi
{
public class ConfigureAsyncApiGeneratorOptions : IConfigureOptions<AsyncApiGeneratorOptions>
{
protected IServiceProvider ServiceProvider { get; }
protected AsyncApiGenOptions AsyncApiGenOptions { get; }
public ConfigureAsyncApiGeneratorOptions(
IServiceProvider serviceProvider,
IOptions<AsyncApiGenOptions> asyncApiGenOptionsAccessor)
{
ServiceProvider = serviceProvider;
AsyncApiGenOptions = asyncApiGenOptionsAccessor.Value;
}
public void Configure(AsyncApiGeneratorOptions options)
{
DeepCopy(AsyncApiGenOptions.AsyncApiGeneratorOptions, options);
// AsyncApiGenOptions.ParameterFilterDescriptors.ForEach((Action<FilterDescriptor>) (filterDescriptor =>
// options.ParameterFilters.Add(CreateFilter<IParameterFilter>(filterDescriptor))));
// AsyncApiGenOptions.OperationFilterDescriptors.ForEach((Action<FilterDescriptor>) (filterDescriptor =>
// options.OperationFilters.Add(CreateFilter<IOperationFilter>(filterDescriptor))));
// AsyncApiGenOptions.DocumentFilterDescriptors.ForEach((Action<FilterDescriptor>) (filterDescriptor =>
// options.DocumentFilters.Add(CreateFilter<IDocumentFilter>(filterDescriptor))));
}
public void DeepCopy(AsyncApiGeneratorOptions source, AsyncApiGeneratorOptions target)
{
target.AsyncApiDocs = new Dictionary<string, AsyncApiDocInfo>(source.AsyncApiDocs);
// target.ParameterFilters =
// (IList<IParameterFilter>) new List<IParameterFilter>(
// (IEnumerable<IParameterFilter>) source.ParameterFilters);
// target.OperationFilters =
// new List<IOperationFilter>((IEnumerable<IOperationFilter>) source.OperationFilters);
// target.DocumentFilters =
// (IList<IDocumentFilter>) new List<IDocumentFilter>(
// (IEnumerable<IDocumentFilter>) source.DocumentFilters);
}
private TFilter CreateFilter<TFilter>(FilterDescriptor filterDescriptor)
{
return (TFilter) ActivatorUtilities.CreateInstance(ServiceProvider, filterDescriptor.Type,
filterDescriptor.Arguments);
}
}
} |
using System.ComponentModel.DataAnnotations.Schema;
namespace Otiport.API.Data.Entities.ProfileItem
{
[Table("ProfileItems")]
public class ProfileItemEntity : BaseEntity<int>
{
public string Title { get; set; }
public string Description { get; set; }
}
}
|
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.Tools;
using System;
namespace LongerLastingLures
{
class ModEntry : Mod
{
private ModConfig Config;
public override void Entry(IModHelper helper)
{
this.Config = Helper.ReadConfig<ModConfig>();
TimeEvents.AfterDayStarted += updateMaxUses;
GameEvents.FirstUpdateTick += updateMaxUses;
PlayerEvents.LeveledUp += updateMaxUses;
SaveEvents.AfterLoad += updateMaxUses;
}
private void updateMaxUses(object sender, EventArgs e)
{
int maxUses = Math.Max(1, this.Config.DefaultMaxUses);
maxUses += (this.Config.IncreaseMaxUsesWithFishingLevel * Game1.player.FishingLevel);
if (maxUses != FishingRod.maxTackleUses)
{
this.Monitor.Log("Set Max Lure Usage: " + maxUses.ToString());
FishingRod.maxTackleUses = maxUses;
}
}
}
}
|
namespace Serilog.Tests.Core;
public class ChildLoggerDisposalTests
{
[Fact]
public void ByDefaultChildLoggerIsNotDisposedOnOuterDisposal()
{
var child = new DisposableLogger();
var outer = new LoggerConfiguration()
.WriteTo.Logger(child)
.CreateLogger();
outer.Dispose();
Assert.False(child.IsDisposed);
}
[Fact]
public void ViaLegacyOverloadChildLoggerIsNotDisposedOnOuterDisposal()
{
var child = new DisposableLogger();
var outer = new LoggerConfiguration()
.WriteTo.Logger(child, Information)
.CreateLogger();
outer.Dispose();
Assert.False(child.IsDisposed);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WhenExplicitlyConfiguredChildLoggerShouldBeDisposedAccordingToConfiguration(bool attemptDispose)
{
var child = new DisposableLogger();
var outer = new LoggerConfiguration()
.WriteTo.Logger(child, attemptDispose)
.CreateLogger();
outer.Dispose();
Assert.Equal(attemptDispose, child.IsDisposed);
}
#if FEATURE_ASYNCDISPOSABLE
[Fact]
public async Task ByDefaultChildLoggerIsNotAsyncDisposedOnOuterDisposal()
{
var child = new DisposableLogger();
var outer = new LoggerConfiguration()
.WriteTo.Logger(child)
.CreateLogger();
await outer.DisposeAsync();
Assert.False(child.IsDisposedAsync);
}
[Fact]
public async Task ViaLegacyOverloadChildLoggerIsNotAsyncDisposedOnOuterDisposal()
{
var child = new DisposableLogger();
var outer = new LoggerConfiguration()
.WriteTo.Logger(child, Information)
.CreateLogger();
await outer.DisposeAsync();
Assert.False(child.IsDisposedAsync);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task WhenExplicitlyConfiguredChildLoggerShouldBeAsyncDisposedAccordingToConfiguration(bool attemptDispose)
{
var child = new DisposableLogger();
var outer = new LoggerConfiguration()
.WriteTo.Logger(child, attemptDispose)
.CreateLogger();
await outer.DisposeAsync();
Assert.Equal(attemptDispose, child.IsDisposedAsync);
}
#endif
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using Integer.Domain.Paroquia;
using Integer.Web.ViewModels;
namespace Integer.Web.Infra.AutoMapper.Profiles
{
public class GrupoProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Grupo, GrupoViewModel>();
Mapper.CreateMap<Grupo, ItemViewModel>();
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.Content.Handlers;
using DFC.ServiceTaxonomy.Content.Services.Interface;
using FakeItEasy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OrchardCore.Media.Events;
using Xunit;
namespace DFC.ServiceTaxonomy.UnitTests.Content.Handlers
{
public class MediaBlobStoreEventHandlerTests
{
private const string ContentPath = "/media/testImage.png";
private readonly ICdnService _fakeCdnService;
private readonly ILogger<MediaBlobStoreEventHandler> _logger;
public MediaBlobStoreEventHandlerTests()
{
_fakeCdnService = A.Fake<ICdnService>();
_logger = A.Fake<ILogger<MediaBlobStoreEventHandler>>();
}
[Fact]
public async Task MediaDeletedFileAsyncCallsCdnService()
{
//arrange
var mediaDeletedContext = new MediaDeletedContext
{
Path = ContentPath,
Result = true
};
var inMemoryConfigSettings = new Dictionary<string, string> { {"AzureAdSettings", "TestAdSettings"}};
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemoryConfigSettings)
.Build();
A.CallTo(() => _fakeCdnService.PurgeContentAsync(A<IList<string>>.Ignored)).Returns(true);
var mediaBlobStoreEventHandler = new MediaBlobStoreEventHandler(configuration, _fakeCdnService, _logger);
//act
await mediaBlobStoreEventHandler.MediaDeletedFileAsync(mediaDeletedContext);
//assert
A.CallTo(() => _fakeCdnService.PurgeContentAsync(A<IList<string>>.Ignored)).MustHaveHappenedOnceExactly();
}
[Fact]
public async Task MediaDeletedFileAsyncFailedToCallCdnService()
{
//arrange
var mediaDeletedContext = new MediaDeletedContext
{
Path = ContentPath,
Result = true
};
var inMemoryConfigSettings = new Dictionary<string, string> ();
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemoryConfigSettings)
.Build();
A.CallTo(() => _fakeCdnService.PurgeContentAsync(A<IList<string>>.Ignored)).Returns(true);
var mediaBlobStoreEventHandler = new MediaBlobStoreEventHandler(configuration, _fakeCdnService, _logger);
//act
await mediaBlobStoreEventHandler.MediaDeletedFileAsync(mediaDeletedContext);
//assert
A.CallTo(() => _fakeCdnService.PurgeContentAsync(A<IList<string>>.Ignored)).MustNotHaveHappened();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Browsing
{
/// <summary>
///
/// </summary>
public interface IBrowser
{
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
Node GetBrowserNodes(string path, string searchPattern = null);
/// <summary>
///
/// </summary>
/// <param name="fileUpload"></param>
/// <returns></returns>
Task<Node> UploadFilesAsync(FileUpload fileUpload);
/// <summary>
///
/// </summary>
/// <param name="removeNodes"></param>
/// <returns></returns>
void DeleteNodes(RemoveNodes removeNodes);
/// <summary>
///
/// </summary>
/// <param name="moveNodes"></param>
/// <returns></returns>
Node MoveNodes(MoveNodes moveNodes);
/// <summary>
///
/// </summary>
/// <param name="copyNodes"></param>
/// <returns></returns>
Task<Node> CopyNodesAsync(CopyNodes copyNodes);
/// <summary>
///
/// </summary>
/// <param name="createDirectory"></param>
/// <returns></returns>
Node CreateDirectory(CreateDirectory createDirectory);
/// <summary>
///
/// </summary>
/// <param name="search"></param>
/// <returns></returns>
Node Search(Search search);
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
byte[] DownloadFile(string path);
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using EPI.Strings;
using FluentAssertions;
namespace EPI.UnitTests.Strings
{
[TestClass]
public class PhoneMnemonicUnitTest
{
[TestMethod]
public void ComputeMnemonic()
{
PhoneMnemonic.ComputeMnemonic(null).Should().HaveCount(0);
PhoneMnemonic.ComputeMnemonic("0000000000").Should().HaveCount(1).And.Contain("0000000000");
PhoneMnemonic.ComputeMnemonic("5678309").Should().HaveCount(3*3*4*3*3*1*4);
}
[TestMethod]
[ExpectedException(typeof (InvalidOperationException))]
public void ComputeMnemonic_InvalidPhoneNumber()
{
PhoneMnemonic.ComputeMnemonic(" ");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity.Core;
using PagedList;
namespace CNWTT.Models.DAO
{
public class NewsDAO
{
public static IList<news> list = null;
public static news n = null;
//get list news 5
public static IList<news> getListNews5()
{
list = null;
using (var db = new cnwttEntities())
{
string sql = "SELECT TOP 5 * FROM dbo.news ORDER BY id DESC";
try
{
list = db.news.SqlQuery(sql).ToList();
}
catch (EntityCommandExecutionException e)
{
Console.WriteLine("Exception-NewsDAO:getListNews5-" + e.ToString());
}
}
return list;
}
//get news from id
public static news getNewsId(int idN)
{
n = null;
using (var db = new cnwttEntities())
{
try
{
n = db.news.Where(ne => ne.id == idN).Single();
}
catch (EntityCommandExecutionException e)
{
Console.WriteLine("Exception-NewsDAO:getNewsId-" + e.ToString());
}
catch (EntityException e)
{
Console.WriteLine("Exception-NewsDAO:getNewsId-" + e.ToString());
}
}
return n;
}
//get list all
public static IList<news> getAllList()
{
list = null;
using (var db = new cnwttEntities())
{
try
{
list = db.news.ToList();
}
catch (EntityCommandExecutionException e){ }
catch (EntityException e){ }
}
return list;
}
public static IEnumerable<news> getListPage(int page, int pageSize)
{
IEnumerable<news> list = null;
using (var db = new cnwttEntities())
{
try
{
list = db.news
.OrderByDescending(n => n.id)
.ToPagedList(page, pageSize);
}
catch (EntityCommandExecutionException e){ }
catch (EntityException e){ }
}
return list;
}
public static int addNews(news news)
{
int idN = -1;
using (var db = new cnwttEntities())
{
try
{
db.news.Add(news);
db.SaveChanges();
idN = news.id;
}
catch (EntityCommandExecutionException e){ }
catch (EntityException e) { }
}
return idN;
}
//edit news
public static bool editNews(news news)
{
bool b = false;
using (var db = new cnwttEntities())
{
try
{
var n = db.news.Find(news.id);
n.title = news.title;
n.describe = news.describe;
n.content = news.content;
n.picture = news.picture;
db.SaveChanges();
b = true;
}
catch (EntityCommandExecutionException e){ }
catch (EntityException e){ }
}
return b;
}
//delete news
public static bool deleteNews(int idNews)
{
bool b = false;
using (var db = new cnwttEntities())
{
using (var dbTransaction = db.Database.BeginTransaction())
{
try
{
news news = db.news.Find(idNews);
db.news.Remove(news);
db.SaveChanges();
dbTransaction.Commit();
b = true;
}
catch (EntityCommandExecutionException e){ }
catch (EntityException e){ }
}
}
return b;
}
}
} |
using Alabo.Web.Mvc.Attributes;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Domains.Repositories.Model {
[ClassProperty(Name = "表类型")]
public enum TableType {
/// <summary>
/// Sql Server数据库
/// </summary>
[Display(Name = "MsSql数据库")] SqlServer = 1,
/// <summary>
/// Mongodb数据库
/// </summary>
[Display(Name = "Mongo数据库")] Mongodb = 2,
/// <summary>
/// 自动配置类型
/// </summary>
[Display(Name = "配置")] AutoConfig = 3,
/// <summary>
/// 枚举
/// </summary>
[Display(Name = "枚举")] Enum = 4,
/// <summary>
/// 级联分类
/// </summary>
[Display(Name = "级联分类")] ClassRelation = 5,
/// <summary>
/// 级联标签
/// </summary>
[Display(Name = "级联标签")] TagRelation = 6
}
} |
using System;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base;
namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual
{
/// <summary>
/// Clase que representa la entidad Estadio Consulta
/// </summary>
/// <remarks>
/// Creación : GMD 20150511 <br />
/// Modificación : <br />
/// </remarks>
public class ContratoEstadioConsultaEntity : Entity
{
/// <summary>
/// Codigo Contrato Estadio de Consulta
/// </summary>
public Guid CodigoContratoEstadioConsulta { get; set; }
/// <summary>
/// Codigo Contrato de Estadio
/// </summary>
public Guid CodigoContratoEstadio { get; set; }
/// <summary>
/// Descripcion
/// </summary>
public string Descripcion { get; set; }
/// <summary>
/// Fecha de Registro
/// </summary>
public DateTime FechaRegistro { get; set; }
/// <summary>
/// Codigo de Parrafo
/// </summary>
public Guid? CodigoContratoParrafo { get; set; }
/// <summary>
/// Destinatario
/// </summary>
public Guid Destinatario { get; set; }
/// <summary>
/// Respuesta
/// </summary>
public string Respuesta { get; set; }
/// <summary>
/// Fecha de Respuesta
/// </summary>
public DateTime? FechaRespuesta { get; set; }
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using OpenTK;
namespace Aria.Core.Maths
{
[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
// ReSharper disable once InconsistentNaming
public struct Vector2f
{
/// <summary>
/// The x co-ordinate of this vector.
/// </summary>
public float X { get; set; }
/// <summary>
/// The y co-ordinate of this vector.
/// </summary>
public float Y { get; set; }
/// <summary>
/// The length of this vector2f.
/// </summary>
public float Length => (float) Math.Sqrt(X*X + Y*Y);
/// <summary>
/// Short static property for creating a vector2f at 0,0.
/// </summary>
public static readonly Vector2f Zero = new Vector2f(0, 0);
/// <summary>
/// Constructor: Create a new vector2f.
/// </summary>
/// <param name="x">The x co-ordinate.</param>
/// <param name="y">The y co-ordinate.</param>
public Vector2f(float x, float y)
{
X = x;
Y = y;
}
/// <summary>
/// Calculate the dot product for this vector and the passed vector.
/// </summary>
/// <param name="value"></param>
/// <returns>The result of the dot product.</returns>
public float DotProduct(Vector2f value)
{
return X*value.X + Y*value.Y;
}
/// <summary>
/// Normalise this vector2f. Scales the vector to a length of 1.
/// </summary>
/// <returns>This vector2f once normalised.</returns>
public Vector2f Normalise()
{
var length = Length;
X /= length;
Y /= length;
return this;
}
/// <summary>
/// Add two vector2fs together.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the sum of the two passed vector2fs.</returns>
public static Vector2f operator +(Vector2f lhs, Vector2f rhs)
{
return new Vector2f(lhs.X + rhs.X, lhs.Y + rhs.Y);
}
/// <summary>
/// Add a float value to a vector2f.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the sum of the current vector plus the passed value.</returns>
public static Vector2f operator +(Vector2f lhs, float rhs)
{
return new Vector2f(lhs.X + rhs, lhs.Y + rhs);
}
/// <summary>
/// Subtract two vector2fs.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the difference of the two passed vector2fs.</returns>
public static Vector2f operator -(Vector2f lhs, Vector2f rhs)
{
return new Vector2f(lhs.X - rhs.X, lhs.Y - rhs.Y);
}
/// <summary>
/// Subtract a float value to a vector2f.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the difference of the current vector plus the passed value.</returns>
public static Vector2f operator -(Vector2f lhs, float rhs)
{
return new Vector2f(lhs.X - rhs, lhs.Y - rhs);
}
/// <summary>
/// Multiply two vector2fs together.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the product of the two passed vector2fs.</returns>
public static Vector2f operator *(Vector2f lhs, Vector2f rhs)
{
return new Vector2f(lhs.X*rhs.X, lhs.Y*rhs.Y);
}
/// <summary>
/// Multiply a vector2f by a float value.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the product of the current vector plus the passed value.</returns>
public static Vector2f operator *(Vector2f lhs, float rhs)
{
return new Vector2f(lhs.X*rhs, lhs.Y*rhs);
}
/// <summary>
/// Divide two vector2fs.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the quotient of the two passed vector2fs.</returns>
public static Vector2f operator /(Vector2f lhs, Vector2f rhs)
{
if ((rhs.X == 0) || (rhs.Y == 0))
throw new ArgumentOutOfRangeException(nameof(rhs), "Attempting to divide by 0.");
return new Vector2f(lhs.X/rhs.X, lhs.Y/rhs.Y);
}
/// <summary>
/// Divide a vector2f by a float value.
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns>A new vector2f equal to the qoutient of the current vector plus the passed value.</returns>
public static Vector2f operator /(Vector2f lhs, float rhs)
{
if (rhs == 0)
throw new ArgumentOutOfRangeException(nameof(rhs), "Attempting to divide by 0.");
return new Vector2f(lhs.X/rhs, lhs.Y/rhs);
}
/// <summary>
/// Rotate this vector by the passed angle.
/// </summary>
/// <param name="angle"></param>
/// <returns>This vector2f once rotated.</returns>
public Vector2f Rotate(float angle)
{
double rad = MathHelper.DegreesToRadians(angle);
var cos = Math.Cos(rad);
var sin = Math.Sin(rad);
return new Vector2f((float) (X*cos - Y*sin), (float) (X*sin + Y*cos));
}
/// <summary>
/// Rich ToString text.
/// </summary>
/// <returns>Rich formatting for vector2f output.</returns>
public override string ToString()
{
return "(" + X + ", " + Y + ")";
}
}
} |
using System;
using UnityEngine;
namespace OrbisEngine.Utility
{
// VITAL: Not finished at all
public class Timer
{
public static string DefaultMinuteFormatting = "00";
public static string DefaultSecondFormatting = "00.00";
// state monitoring
float m_StartTime;
float m_EndTime;
float m_TotalTime;
bool m_Started = false;
public bool IsStarted { get { return m_Started; } }
public void Start(float elapsedTime = 0f)
{
if (m_Started)
Debug.LogWarning("Timer is already started. This resets the timer");
m_StartTime = Time.time;
m_Started = true;
}
public void Stop()
{
if (m_Started == false)
Debug.Log("Timer is not started");
m_EndTime = Time.time;
m_Started = false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ExscelOpenSQL
{
class ParseTextTable
{
private List<string> _ListDGV2Name = new List<string>();
public List<string> ListDGV2Name { get { return _ListDGV2Name; } }
private List<string> _ListDGV2USD = new List<string>();
public List<string> ListDGV2USD { get { return _ListDGV2USD; } }
private List<string> _ListDGV2BYR = new List<string>();
public List<string> ListDGV2BYR { get { return _ListDGV2BYR; } }
private List<string> _ListDGV2Count = new List<string>();
public List<string> ListDGV2Count { get { return _ListDGV2Count; } }
/// <summary>
/// метод переносит часть названия товара на новую строку в случае переполнения, что бы при печати не возникло сноса столбцов таблицы на нвоый лист
/// </summary>
/// <param name="dataGridView2"></param>
public void parseTextDataGrid(DataGridView dataGridView2)
{
try
{
for (int i = 0; i < dataGridView2.RowCount; i++)
{
string dgv = dataGridView2.Rows[i].Cells[0].Value.ToString(), str = "";
int n = 30;
for (int j = 0; j < dgv.Length; j++)
{
str += dgv[j];
if (j > n && dgv[j] == ' ')
{
n += 45;
ListDGV2Name.Add(str);
ListDGV2USD.Add("---");
ListDGV2BYR.Add("---");
ListDGV2Count.Add("---");
str = "";
}
}
ListDGV2Name.Add(str);
ListDGV2USD.Add(dataGridView2.Rows[i].Cells[1].Value.ToString());
ListDGV2BYR.Add(dataGridView2.Rows[i].Cells[2].Value.ToString());
ListDGV2Count.Add(dataGridView2.Rows[i].Cells[3].Value.ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Blackjack;
using BlackjackViewPresenter;
namespace BlackjackGUI
{
public partial class BlackjackCountView : UserControl, IBlackjackCountView
{
public BlackjackCountView()
{
InitializeComponent();
Label sysHdr = new();
sysHdr.Text = "System";
sysHdr.Font = new ("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
tableLayoutPanel.Controls.Add(sysHdr, 0, 0);
Label cntHdr = new();
cntHdr.Text = "Count";
cntHdr.Font = new("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
tableLayoutPanel.Controls.Add(cntHdr, 1, 0);
foreach (BlackjackCountEnum system in Enum.GetValues(typeof(BlackjackCountEnum)))
{
int row = (int)system + 1;
Label sysLbl = new();
sysLbl.Text = system.ToString();
tableLayoutPanel.Controls.Add(sysLbl, 0, row);
Label cntLbl = new();
cntLbl.Text = "0";
tableLayoutPanel.Controls.Add(cntLbl, 1, row);
}
}
public void SetCount(BlackjackCountEnum system, float count)
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(() => SetCount(system, count)));
return;
}
Label lbl = (Label)tableLayoutPanel.GetControlFromPosition(1, (int)system + 1);
lbl.Text = count.ToString();
}
}
}
|
using Alabo.Cloud.People.UserDigitals.Domain.Entities;
using Alabo.Cloud.People.UserDigitals.Domain.Services;
using Alabo.Framework.Core.WebApis.Controller;
using Alabo.Framework.Core.WebApis.Filter;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace Alabo.Cloud.People.UserDigitals.Controllers
{
[ApiExceptionFilter]
[Route("Api/UserDigitalIndex/[action]")]
public class ApiUserDigitalIndexController : ApiBaseController<UserDigitalIndex, ObjectId>
{
public ApiUserDigitalIndexController()
{
BaseService = Resolve<IUserDigitalIndexService>();
}
}
} |
using System.Collections.Generic;
using Newtonsoft.Json;
using StickFigure.Drawing;
namespace StickFigure
{
public class JointFile
{
[JsonIgnore]
public bool IsLast { get; set; }
public List<ConcreteJoint> ConcreteJoints { get; set; }
public List<Line> Lines { get; set; }
}
}
|
using EmailSender;
using Microsoft.Extensions.Logging;
using Moq;
using SnowBLL.Enums;
using SnowBLL.Models;
using SnowBLL.Models.Auth;
using SnowBLL.Models.Users;
using SnowBLL.Resolvers;
using SnowBLL.Service.Concrete;
using SnowBLL.Service.Interfaces;
using SnowDAL.DBModels;
using SnowDAL.Paging;
using SnowDAL.Repositories.Interfaces;
using SnowDAL.Searching;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Xunit;
namespace SnowTests.Unit
{
public class UserServiceMocker
{
public Mock<IUserRepository> RepoMock { get; set; }
public Mock<IAuthBLService> AuthServiceMock { get; set; }
public Mock<IRouteRepository> RouteRepositoryMock { get; set; }
public Mock<IUserResolver> UserResolverServiceMock { get; set; }
public Mock<ISender> EmailSenderMock { get; set; }
public Mock<ISystemCodeRepository> SystemCodeRepositoryMock { get; set; }
public Mock<ILogger<BLService>> LoggerMock { get; set; }
public UserServiceMocker()
{
RepoMock = new Mock<IUserRepository>();
AuthServiceMock = new Mock<IAuthBLService>();
RouteRepositoryMock = new Mock<IRouteRepository>();
UserResolverServiceMock = new Mock<IUserResolver>();
EmailSenderMock = new Mock<ISender>();
SystemCodeRepositoryMock = new Mock<ISystemCodeRepository>();
LoggerMock = new Mock<ILogger<BLService>>();
}
public IUserBLService GetService()
{
return new UserBLService(LoggerMock.Object, RepoMock.Object, AuthServiceMock.Object, RouteRepositoryMock.Object, UserResolverServiceMock.Object, EmailSenderMock.Object, SystemCodeRepositoryMock.Object);
}
}
public class UserServiceTests
{
[Fact]
public void UpdateWrongId()
{
UserServiceMocker mocker = new UserServiceMocker();
UserEntity entity = new UserEntity();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<int>())).Returns(() => null);
IUserBLService service = mocker.GetService();
var result = service.Update(0, new UserUpdateModel());
Assert.Equal("Id", result.Result.Error.Errors.First().Field);
Assert.Equal(ErrorStatus.ObjectNotFound, result.Result.Error.Status);
}
[Fact]
public void UpdateInvalidUserPermissions()
{
UserServiceMocker mocker = new UserServiceMocker();
UserEntity entity = new UserEntity();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<int>())).Returns(() => new UserEntity()
{
Email = "test@test.com",
ID = 1,
Name = "testowy"
});
mocker.UserResolverServiceMock.Setup(r => r.GetUser())
.Returns(() => Task.FromResult<UserModel>(new UserModel()
{
Email = "test@test.com",
Id = 2,
Name = "testowy"
}));
IUserBLService service = mocker.GetService();
var result = service.Update(0, new UserUpdateModel());
Assert.Equal("Action forbidden", result.Result.Error.Message);
Assert.Equal(ErrorStatus.Forbidden, result.Result.Error.Status);
}
[Fact]
public void UpdateUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<int>())).Returns(() => new UserEntity()
{
Email = "test@test.com",
ID = 2,
Name = "testowy"
});
mocker.UserResolverServiceMock.Setup(r => r.GetUser()).Returns(
() => Task.FromResult<UserModel>(new UserModel()
{
Email = "test@test.com",
Id = 2,
Name = "testowy"
}));
mocker.RepoMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.Update(0, new UserUpdateModel());
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void RemoveWrongId()
{
UserServiceMocker mocker = new UserServiceMocker();
UserEntity entity = new UserEntity();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<int>())).Returns(() => null);
IUserBLService service = mocker.GetService();
var result = service.Remove(new IdModel());
Assert.Equal("Id", result.Result.Error.Errors.First().Field);
Assert.Equal(ErrorStatus.ObjectNotFound, result.Result.Error.Status);
}
[Fact]
public void RemoveUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
UserEntity entity = new UserEntity();
mocker.RepoMock.Setup(r => r.GetSingleWithDependencies(It.IsAny<int>())).Returns(() => Task.FromResult<UserEntity>(new UserEntity()
{
Email = "test@test.com",
ID = 2,
Name = "testowy",
Routes = new List<RouteInfoEntity>()
{
new RouteInfoEntity()
{
ID = 1
}
}
}));
mocker.UserResolverServiceMock.Setup(r => r.GetUser())
.Returns(() => Task.FromResult<UserModel>(new UserModel()
{
Email = "test@test.com",
Id = 2,
Name = "testowy"
}));
mocker.RepoMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.Remove(new IdModel());
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void CreateUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
UserEntity entity = new UserEntity();
mocker.RepoMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.Create(new UserCreateModel());
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void CreateExistingUser()
{
UserServiceMocker mocker = new UserServiceMocker();
UserEntity entity = new UserEntity();
mocker.RepoMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(new UserEntity() { Status = 1 }));
IUserBLService service = mocker.GetService();
var result = service.Create(new UserCreateModel());
Assert.Equal(ErrorStatus.InvalidModel, result.Result.Error.Status);
Assert.Equal("User already exists", result.Result.Error.Message);
}
[Fact]
public void GetAllUsersUnhandledException()
{
var request = new CollectionRequestModel();
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.Search(It.IsAny<SearchQuery<UserEntity>>())).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.GetAllUsers(request);
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void GetAllUsersValidResult()
{
var request = new CollectionRequestModel();
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.Search(It.IsAny<SearchQuery<UserEntity>>()))
.Returns(() => Task.FromResult(new PagingResult<UserEntity>()
{
Count = 2,
HasNext = false,
Results = new List<UserEntity>()
{
new UserEntity()
{
Email = "123@123.com",
ID = 1,
Name = "First",
Routes = new List<RouteInfoEntity>()
{
new RouteInfoEntity()
{
ID = 1,
Name = "a"
}
}
},
new UserEntity()
{
Email = "23@23.com",
ID = 2,
Name = "Second",
Routes = new List<RouteInfoEntity>()
{
new RouteInfoEntity()
{
ID = 2,
Name = "b"
}
}
}
}
}));
IUserBLService service = mocker.GetService();
var result = service.GetAllUsers(request);
Assert.Equal(true, result.Result.IsOk);
Assert.Equal(2, result.Result.Content.Count);
Assert.Equal(false, result.Result.Content.HasNext);
}
[Fact]
public void GetUserByIdUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingleWithDependencies(It.IsAny<int>())).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.GetById(1);
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void GetRouteByIdInvalidId()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingleWithDependencies(It.IsAny<int>())).Returns((() => Task.FromResult((UserEntity)null)));
IUserBLService service = mocker.GetService();
var result = service.GetById(1);
Assert.Equal(ErrorStatus.ObjectNotFound, result.Result.Error.Status);
Assert.Equal("User not found", result.Result.Error.Message);
}
[Fact]
public void SendResetPasswordEmailNullUser()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.SendResetPasswordEmail("test@text.com");
Assert.Equal(ErrorStatus.ObjectNotFound, result.Result.Error.Status);
Assert.Equal("User not found", result.Result.Error.Message);
}
[Fact]
public void SendResetPasswordEmailUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(new UserEntity()));
mocker.SystemCodeRepositoryMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.SendResetPasswordEmail("test@text.com");
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void SendResetPasswordEmailValidResult()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(new UserEntity()));
IUserBLService service = mocker.GetService();
var result = service.SendResetPasswordEmail("test@text.com");
Assert.True(result.Result.IsOk);
Assert.Equal(DateTime.Today.AddDays(30), result.Result.Content.ExpirationDate);
}
[Fact]
public void ResetPasswordlNullUser()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.ResetPassword(new NewPasswordModel());
Assert.Equal(ErrorStatus.ObjectNotFound, result.Result.Error.Status);
Assert.Equal("User not found", result.Result.Error.Message);
}
[Fact]
public void ResetPasswordInvalidCode()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(new UserEntity()));
mocker.SystemCodeRepositoryMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<SystemCodeEntity, bool>>>()))
.Returns(() => Task.FromResult<SystemCodeEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.ResetPassword(new NewPasswordModel());
Assert.Equal(ErrorStatus.ObjectNotFound, result.Result.Error.Status);
Assert.Equal("Invalid code", result.Result.Error.Message);
}
[Fact]
public void ResetPasswordUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(new UserEntity()));
mocker.SystemCodeRepositoryMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<SystemCodeEntity, bool>>>()))
.Returns(() => Task.FromResult<SystemCodeEntity>(new SystemCodeEntity()));
mocker.RepoMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.ResetPassword(new NewPasswordModel());
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void ResetPasswordEmailValidResult()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(new UserEntity()));
mocker.SystemCodeRepositoryMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<SystemCodeEntity, bool>>>()))
.Returns(() => Task.FromResult<SystemCodeEntity>(new SystemCodeEntity()));
IUserBLService service = mocker.GetService();
var result = service.SendResetPasswordEmail("test@text.com");
Assert.True(result.Result.IsOk);
}
[Fact]
public void SendConfirmAccountEmailnullUser()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.SendConfirmAccountEmail();
Assert.Equal(ErrorStatus.Forbidden, result.Result.Error.Status);
Assert.Equal("User is not logged in", result.Result.Error.Message);
}
[Fact]
public void SendConfirmAccountUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.UserResolverServiceMock.Setup(r => r.GetUser()).Returns(() => Task.FromResult<UserModel>(new UserModel()));
mocker.SystemCodeRepositoryMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.SendConfirmAccountEmail();
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void SendConfirmAccountEmailValidResult()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.UserResolverServiceMock.Setup(r => r.GetUser()).Returns(() => Task.FromResult<UserModel>(new UserModel()));
IUserBLService service = mocker.GetService();
var result = service.SendConfirmAccountEmail();
Assert.True(result.Result.IsOk);
Assert.Equal(DateTime.Today.AddDays(30), result.Result.Content.ExpirationDate);
}
[Fact]
public void ConfirmAccountEmailNullUser()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<UserEntity, bool>>>()))
.Returns(() => Task.FromResult<UserEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.ConfirmAccount(new UserAccountConfirmationModel());
Assert.Equal(ErrorStatus.Forbidden, result.Result.Error.Status);
Assert.Equal("User is not logged in", result.Result.Error.Message);
}
[Fact]
public void ConfirmAccountInvalidCode()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.UserResolverServiceMock.Setup(r => r.GetUser()).Returns(() => Task.FromResult<UserModel>(new UserModel()));
mocker.SystemCodeRepositoryMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<SystemCodeEntity, bool>>>()))
.Returns(() => Task.FromResult<SystemCodeEntity>(null));
IUserBLService service = mocker.GetService();
var result = service.ConfirmAccount(new UserAccountConfirmationModel());
Assert.Equal(ErrorStatus.InvalidModel, result.Result.Error.Status);
Assert.Equal("Invalid code", result.Result.Error.Message);
}
[Fact]
public void ConfirmAccountUnhandledException()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.UserResolverServiceMock.Setup(r => r.GetUser()).Returns(() => Task.FromResult<UserModel>(new UserModel()));
mocker.SystemCodeRepositoryMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<SystemCodeEntity, bool>>>()))
.Returns(() => Task.FromResult<SystemCodeEntity>(new SystemCodeEntity()));
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<int>())).Returns(() => new UserEntity());
mocker.RepoMock.Setup(r => r.Commit()).Throws(new Exception("testexception"));
IUserBLService service = mocker.GetService();
var result = service.ConfirmAccount(new UserAccountConfirmationModel());
Assert.Equal(ErrorStatus.InternalServer, result.Result.Error.Status);
Assert.Equal("testexception", result.Result.Error.Message);
}
[Fact]
public void ConfirmAccountEmailValidResult()
{
UserServiceMocker mocker = new UserServiceMocker();
mocker.UserResolverServiceMock.Setup(r => r.GetUser()).Returns(() => Task.FromResult<UserModel>(new UserModel()));
mocker.SystemCodeRepositoryMock.Setup(r => r.GetSingle(It.IsAny<Expression<Func<SystemCodeEntity, bool>>>()))
.Returns(() => Task.FromResult<SystemCodeEntity>(new SystemCodeEntity()));
mocker.RepoMock.Setup(r => r.GetSingle(It.IsAny<int>())).Returns(() => new UserEntity());
IUserBLService service = mocker.GetService();
var result = service.ConfirmAccount(new UserAccountConfirmationModel());
Assert.True(result.Result.IsOk);
}
}
}
|
using System;
namespace CrudIrpf.Domain
{
public class Irpf
{
public int Id { get; set; }
public string Nome { get; set; }
public string CpfCnpj { get; set; }
public string Email { get; set; }
public DateTime DtNascimento { get; set; }
public string TituloEleitoral { get; set; }
public double RendimentosTributaveis { get; set; }
public string Endereco { get; set; }
public string Cidade { get; set; }
public string Bairro { get; set; }
public string Cep { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entities.FVS
{
/// <summary>
/// 生产监控结果
/// </summary>
public class ProductionSurveillance
{
/// <summary>
/// 工厂结构结点标识
/// </summary>
public int T134NodeID { get; set; }
/// <summary>
/// 工厂结构结点名称
/// </summary>
public string T134NodeName { get; set; }
/// <summary>
/// 产线或工作中心树标识(134/211)
/// </summary>
public int TreeID { get; set; }
/// <summary>
/// 产线或工作中心叶标识
/// </summary>
public int LeafID { get; set; }
/// <summary>
/// 产线或工作中心代码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 产线或工作中心名称
/// </summary>
public string NodeName { get; set; }
/// <summary>
/// 自定义遍历序
/// </summary>
public double UDFOrdinal { get; set; }
/// <summary>
/// 事件类型叶标识
/// </summary>
public int T179LeafID { get; set; }
/// <summary>
/// 事件类型实体标识
/// </summary>
public int T179EntityID { get; set; }
/// <summary>
/// 事件类型代码
/// </summary>
public string T179Code { get; set; }
/// <summary>
/// 事件类型名称
/// </summary>
public string T179NodeName { get; set; }
/// <summary>
/// 资源状态(0=未开通 1=正常 2=非停线 3=停线)
/// </summary>
public int ResourceStatus { get; set; }
/// <summary>
/// 已过时间(s)
/// </summary>
public int ElapsedSeconds { get; set; }
/// <summary>
/// 是否已响应
/// </summary>
public bool OnSiteResponded { get; set; }
public ProductionSurveillance Clone()
{
return MemberwiseClone() as ProductionSurveillance;
}
public override string ToString()
{
return NodeName + T179NodeName;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace JustRipeFarmUnitTest
{
class TestAddSQL
{
}
//string sql = "INSERT INTO crop (name, type, quantity_plot, remark) "
// + " Values ('" + crop.Name + "', '" + crop.Type + "', " + crop.Quantity_plot + " , '"
// + crop.Remark + "')";
public class UnitTestAddCrop
{
public void TestAddNewCrop()
{
//MysqlDbc dbC = new MysqlDbc();
//string resp = dbC.connect();
//Assert.AreEqual("Done", resp);
//Crop crop1 = new Crop();
//Labourer labrA = new Labourer();
//labrA.Name = "Bob";
//labrA.Age = 39;
//labrA.Gender = "male";
//LabourerHandler labrHand = new LabourerHandler();
//int resp2 = labrHand.addNewLabourer(dbC.getConn(), labrA);
//Assert.IsNotNull(resp2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Filters
{
class Sepia : Filters
{
protected override Color сonvertPixel(Bitmap sourceMap, int x, int y)
{
Color sourceColor = sourceMap.GetPixel(x, y);
float a = 0.36f, b = 0.56f, c = 0.11f;
int intensity = (int)(a * sourceColor.R + b * sourceColor.G + c * sourceColor.B);
int k = 2;
float r = intensity + 2 * k, g = intensity + 0.5f * k; b = intensity - 1 * k;
r = clamp((int)r, 0, 255);
g = clamp((int)g, 0, 255);
b = clamp((int)b, 0, 255);
Color resultColor = Color.FromArgb((int)r, (int)g, (int)b);
return resultColor;
throw new NotImplementedException();
}
}
}
|
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK.Graphics.OpenGL;
namespace Lux.Graphics
{
internal class Texture
{
private bool IsFinished { get; set; }
public uint TextureID;
private Bitmap TempBitmap;
public Texture(string path)
{
IsFinished = false;
TextureID = 0;
if (!File.Exists(path))
{
return;
throw new FileNotFoundException("Texture " + path + " could not be found!");
}
switch (path.Substring(path.LastIndexOf('.')))
{
case ".tga":
{
TempBitmap = Paloma.TargaImage.LoadTargaImage(path);
break;
}
case ".png":
{
TempBitmap = new Bitmap(path);
break;
}
}
}
static public void FinishTextures(Texture[] textures)
{
foreach(Texture t in textures)
{
int textureID;
GL.GenTextures(1, out textureID);
GL.BindTexture(TextureTarget.Texture2D, textureID);
BitmapData bmpData = t.TempBitmap.LockBits(new Rectangle(0, 0, t.TempBitmap.Width, t.TempBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
t.TempBitmap.UnlockBits(bmpData);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, t.TempBitmap.Width, t.TempBitmap.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
float maxAniso;
GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out maxAniso);
GL.TexParameter(TextureTarget.Texture2D, (TextureParameterName)ExtTextureFilterAnisotropic.TextureMaxAnisotropyExt, maxAniso);
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
t.TextureID = (uint)textureID;
t.TempBitmap.Dispose();
t.TempBitmap = null;
t.IsFinished = true;
}
}
}
}
|
using System;
using System.Threading;
using Framework.Core.Common;
using NUnit.Framework;
using OpenQA.Selenium;
using Tests.Pages.Van.Main.Common;
namespace Tests.Pages.Van.Main.List
{
public class CanvassListPage : BaseListPage
{
#region Elements
public By InternationalDropdownLocator = By.Id("ctl00_ContentPlaceHolderVANPage_VANCanvassFilterPanelInstance_VanInputItemInternationalCode_VanInputItemInternationalCode");
public IWebElement InternationalDropdown { get { return _driver.FindElement(InternationalDropdownLocator); } }
public By CanvassResultsGroupByDropdownLocator = By.Id("ctl00_ContentPlaceHolderVANPage_VANCanvassFilterPanelInstance_VanInputItemFilterGeoView_VanInputItemFilterGeoView");
public IWebElement CanvassResultsGroupByDropdown { get { return _driver.FindElement(CanvassResultsGroupByDropdownLocator); } }
public By CanvassPickerDateFromPickerLocator = By.Id("ctl00_ContentPlaceHolderVANPage_VANCanvassFilterPanelInstance_VanInputItemFilterDateFrom_VanInputItemFilterDateFrom");
public IWebElement CanvassFilterDateFromPicker { get { return _driver.FindElement(CanvassPickerDateFromPickerLocator); } }
public By CanvassPickerDateToPickerLocator = By.Id("ctl00_ContentPlaceHolderVANPage_VANCanvassFilterPanelInstance_VanInputItemFilterDateTo_VanInputItemFilterDateTo");
public IWebElement CanvassFilterDateToPicker { get { return _driver.FindElement(CanvassPickerDateToPickerLocator); } }
public By CanvassResultsTableLocator = By.Id("ctl00_ContentPlaceHolderVANPage_gvList");
public IWebElement CanvassResultsTable { get { return _driver.FindElement(CanvassResultsTableLocator); } }
#endregion
public CanvassListPage(Driver driver) : base(driver) { }
}
}
|
using System;
namespace Vlc.DotNet.Core
{
public class VlcMediaPlayerAudioVolumeEventArgs : EventArgs
{
private float Volume { get; }
public VlcMediaPlayerAudioVolumeEventArgs(float volume)
{
this.Volume = volume;
}
}
} |
namespace PropositionalFormulaProver.Grammar
{
partial class FormulaParser
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DevanshAssociate_API.DAL
{
public class StepsDAL
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Vuforia;
public class Fast : MonoBehaviour
{
public GameObject fast;
Controller controller;
// Start is called before the first frame update
void Start()
{
fast = GameObject.Find("SpeedUpButton");
fast.GetComponent<VirtualButtonBehaviour>().RegisterOnButtonPressed(OnButtonPressed);
fast.gameObject.GetComponent<VirtualButtonBehaviour>().RegisterOnButtonReleased(OnButtonReleased);
controller = GameObject.FindGameObjectWithTag("GameController").GetComponent<Controller>();
}//End Start
public void OnButtonPressed(VirtualButtonBehaviour vb)
{
//Add fast code here
controller.speedUp();
//controller.speedUp();
print("Speeding");
Debug.Log("Speeding");
}//End OnButtonPressed
public void OnButtonReleased(VirtualButtonBehaviour vb)
{
print("Not Speeding");
Debug.Log("Not Speeding");
}//End OnButtonReleased
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace upSight.CartaoCorp.Emissao.ACSOEMIS_R
{
public static class ACSOEMIS_RCabecalhoBD
{
public static IEnumerable<ACSOEMIS_RCabecalhoEN> ConsultaCabecalho(this ACSOEMIS_RCabecalhoEN acsemisRCab)
{
using (SqlConnection cnx = new SqlConnection(upSight.Consulta.Base.BD.Conexao.StringConexaoBDGlobal))
{
try
{
string query =
"crtCabecalhoCartoesEmitidos";
using (SqlCommand cmd = new SqlCommand(query, cnx))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@idProcesso", SqlDbType.Int).Value = acsemisRCab.IdArquivo;
cnx.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
while (dr.Read())
{
acsemisRCab.CodConvenio = dr["codConvenio"].ToString();
yield return acsemisRCab;
}
}
}
}
finally
{
if (cnx.State == ConnectionState.Open)
cnx.Close();
}
}
}
}
}
|
using System;
using System.Xml;
namespace Svenkle.SitecoreSolrOnStartup.Models
{
public class SystemInformation : ISystemInformation
{
public SystemInformation(string document)
{
Document = new XmlDocument();
Document.LoadXml(document);
}
public string Version => Document.SelectSingleNode("/response/lst[@name='lucene']/str[@name='solr-spec-version']")?.InnerXml;
public string Path => Document.SelectSingleNode("/response/str[@name='solr_home']")?.InnerXml;
public Mode Mode => (Mode)Enum.Parse(typeof(Mode), Document.SelectSingleNode("/response/str[@name='mode']")?.InnerXml ?? "Std", true);
public XmlDocument Document { get; }
}
} |
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 Parking_Lot_Project
{
public partial class informationForm : Form
{
public informationForm()
{
InitializeComponent();
}
private void informationForm_Load(object sender, EventArgs e)
{
groupBox_account.Visible = false;
panel_changePass.Visible = false;
}
private void materialButton_exit_Click(object sender, EventArgs e)
{
textBox_newPass.Text = "";
textBox_oldPass.Text = "";
textBox_rePass.Text = "";
panel_changePass.Visible = false;
}
private void materialButton_changePass_Click(object sender, EventArgs e)
{
panel_changePass.Visible = true;
}
private void metroButton_upImg_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Select Image (*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif";
if (opf.ShowDialog() == DialogResult.OK)
{
pictureBox_avatar.Image = Image.FromFile((opf.FileName));
}
}
private void materialButton_ok_Click(object sender, EventArgs e)
{
string oldPass = textBox_oldPass.Text;
string newPass = textBox_newPass.Text;
}
}
}
|
namespace PFRCenterGlobal.ViewModels.Maps
{
public class Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.