text stringlengths 13 6.01M |
|---|
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using RimWorld;
using Verse;
using UnityEngine;
using AlienRace;
namespace SyrThrumkin
{
[DefOf]
public static class ThrumkinDefOf
{
static ThrumkinDefOf()
{
}
public static ThingDef Thrumkin;
public static ThingDef Apparel_PlateArmor;
public static ThingDef Apparel_TribalA;
public static ThingDef DevilstrandCloth;
public static ThingDef WoodLog_GhostAsh;
public static ThingDef RawFrostleaves;
public static ThingDef Plant_Frostleaf;
public static ThingDef MealLavish;
public static TerrainDef GhostAshFloor;
public static BodyDef Thrumkin_Body;
public static BodyPartDef HornThrumkin;
public static BodyPartGroupDef Feet;
public static ThoughtDef MyHornHarvested;
public static ThoughtDef KnowColonistHornHarvested;
public static ThoughtDef KnowOtherHornHarvested;
public static DamageDef SurgicalCutSpecial;
public static FactionDef ThrumkinTribe;
public static BackstoryDef Thrumkin_CBio_Menardy;
public static BackstoryDef Thrumkin_ABio_Menardy;
public static PawnBioDef Thrumkin_Bio_Menardy;
public static PawnKindDef Thrumkin_ElderMelee;
public static HairDef Thrumkin_Hair_0;
public static HairDef Thrumkin_Hair_1;
public static HairDef Thrumkin_Hair_2;
public static HairDef Thrumkin_Hair_3;
public static HairDef Thrumkin_Hair_4;
public static HairDef Thrumkin_Hair_5;
public static HediffDef AteFrostLeaves;
public static HediffDef AteWoodHediff;
public static JobDef ShearThrumkin;
}
}
|
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 Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace ProjectDB2
{
public partial class Sign_In : MaterialSkin.Controls.MaterialForm
{
string constr = "Data source= orcl; User Id=scott;Password=tiger;";
OracleConnection conn;
public static string idd;
public static string mail_to;
public Sign_In()
{
InitializeComponent();
}
private void Sign_In_Load(object sender, EventArgs e)
{
conn = new OracleConnection(constr);
conn.Open();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void materialFlatButton1_Click(object sender, EventArgs e)
{
Inbox inboxform = new Inbox();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from user_account where E_MAIL=:mail and PASSWORD=:pass";
cmd.Parameters.Add("mail", txt_mail.Text);
mail_to = txt_mail.Text;
cmd.Parameters.Add("pass", txt_password.Text);
OracleDataReader dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count = count + 1;
idd = dr["user_id"].ToString();
}
if (count == 1)
{
this.Hide();
inboxform.Show();
this.Dispose();
}
else
{
MessageBox.Show("Incorrect Mail or Password ");
}
dr.Close();
}
private void chkbox_show_CheckedChanged(object sender, EventArgs e)
{
if (chkbox_show.Checked)
{
txt_password.UseSystemPasswordChar = false;
}
else
{
txt_password.UseSystemPasswordChar = true;
}
}
private void Sign_In_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
|
using System.Windows.Controls;
namespace tweetz.core.Controls.SettingsBlock
{
public partial class SettingsInfoBlock : UserControl
{
public SettingsInfoBlock()
{
InitializeComponent();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/*using Lucene.Net.Index;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Search;
using System.Collections;
using Lucene.Net.Store;*/
namespace BLL.DLib
{
public class NormalizeFarsi
{
#region vars
public string path = HttpContext.Current.Request.PhysicalApplicationPath;
public static string DIR = HttpContext.Current.Request.PhysicalApplicationPath + "IndexLucene";
public static string DefaultStopwordFile = HttpContext.Current.Request.PhysicalApplicationPath + "PersianStopWords.txt";
private static string Fathe = ('َ').ToString();
private static string Zamme = ('ُ').ToString();
private static string Kasre = ('ِ').ToString();
private static string TanvinFathe = ('ً').ToString();
private static string TanvinZamme = ('ٌ').ToString();
private static string TanvinKasre = ('ٍ').ToString();
private static string Tashdid = ('ّ').ToString();
private static string Sokun = ('ْ').ToString();
private static string HamzeJoda = ('ء').ToString();
private static string KhateTire = ('ـ').ToString();
public static string YehArabic = "ی";
public static string YehArabic_2 = "ى";
public static string YehPersian = "ي";
public static string KafArabic = "ک";
public static string KafPersian = "ك";
#endregion
public static string NormalizePersian(string txt)
{
txt = txt.Replace(YehArabic, YehPersian);
txt = txt.Replace(KafArabic, KafPersian);
txt = txt.Replace(Fathe, "");
txt = txt.Replace(Zamme, "");
txt = txt.Replace(Kasre, "");
txt = txt.Replace(TanvinFathe, "");
txt = txt.Replace(TanvinZamme, "");
txt = txt.Replace(TanvinKasre, "");
txt = txt.Replace(Tashdid, "");
txt = txt.Replace(Sokun, "");
txt = txt.Replace(HamzeJoda, "");
txt = txt.Replace(KhateTire, "");
txt = txt.Replace(YehArabic_2, YehPersian);
txt = txt.Replace("$", "");
txt = txt.Replace("#", "");
txt = txt.Replace("", " ");
return txt;
}
public static string SimpleNormalizePersian(string txt)
{
txt = txt.Replace(YehArabic_2, YehPersian);
txt = txt.Replace(YehArabic, YehPersian);
txt = txt.Replace(KafArabic, KafPersian);
return txt;
}
public static string RemoveStopWords(string txt)
{
foreach (string STword in general.ReadTextFileLines(DefaultStopwordFile))
txt = txt.Replace(" " + STword + " ", " ");
return txt;
}
public static string PrepaireFarsi(string txt)
{
return txt==null?"":RemoveStopWords(NormalizePersian(txt));
}
//public static void CreateIndex()
//{
// FSDirectory.SetDisableLocks(true);
// IndexWriter indexWriter = new IndexWriter(DIR, new StandardAnalyzer(), true);
// var db = new RPModel.RPEntities();
// var q = db.tbl_Project;
// string title = "";
// foreach (var c in q)
// {
// Document doc = new Document();
// title = c.Title == null ? "" : NormalizePersian(c.Title);
// doc.Add(new Field("ID", "\"" + c.ID.ToString() + "\"", Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.NO));
// doc.Add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
// indexWriter.AddDocument(doc);
// }
// indexWriter.Optimize();
// indexWriter.Close();
//}
//public static void UpdateIndex()
//{
// var db = new RPModel.RPEntities();
// var q = db.tbl_Project;
// foreach (var c in q)
// {
// UpdateDocument(Convert.ToInt16(c.ID), c.Title);
// }
//}
//public static void UpdateDocument(int ID, string title)
//{
// IndexWriter indexWriter = new IndexWriter(DIR, new StandardAnalyzer(), false);
// Document NewDoc = new Document();
// title = title == null ? "" : NormalizePersian(title);
// NewDoc.Add(new Field("ID", "\"" + ID.ToString() + "\"", Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.NO));
// NewDoc.Add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
// indexWriter.UpdateDocument(new Term("ID", "\"" + ID.ToString() + "\""), NewDoc);
// indexWriter.Commit();
// indexWriter.Close();
//}
//public static Hits SearchHits(string txt)
//{
// IndexSearcher searcher = new IndexSearcher(DIR);
// Hits hits = null;
// txt = NormalizePersian(txt);
// if (txt.Contains("*"))
// {
// WildcardQuery query = new WildcardQuery(new Term("title", txt));
// hits = searcher.Search(query);
// }
// else if (txt.Contains(" "))
// {
// MultiPhraseQuery query = new MultiPhraseQuery();
// foreach (string s in txt.Split(' '))
// {
// query.Add(new Term("title", s));
// }
// hits = searcher.Search(query);
// }
// else
// {
// PhraseQuery query = new PhraseQuery();
// query.Add(new Term("title", txt));
// hits = searcher.Search(query);
// }
// return hits;
//}
//public struct Result
//{
// public float Score;
// public string Title;
//}
//public static IList Search(string txt)
//{
// Hits hits = SearchHits(txt);
// List<Result> ResultList = new List<Result>();
// for (int i = 0; i < hits.Length(); i++)
// ResultList.Add(new Result { Score = hits.Score(i), Title = hits.Doc(i).Get("title") });
// var q = (from c in ResultList select new { c.Score, c.Title });
// return q.AsQueryable().ToList();
//}
}
} |
namespace Merchello.UkFest.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using Merchello.Core;
using Merchello.Core.Models;
using Merchello.Core.Sales;
using Merchello.UkFest.Web.Ditto.Contexts;
using Merchello.UkFest.Web.Models.Checkout;
using Merchello.UkFest.Web.Resolvers;
using Merchello.Web;
using Merchello.Web.Pluggable;
using Merchello.Web.Workflow;
using Umbraco.Core.Logging;
using Umbraco.Web.Models;
/// <summary>
/// The checkout controller.
/// </summary>
public class CheckoutController : DitFloController
{
/// <summary>
/// The _customer context.
/// </summary>
private ICustomerContext _customerContext;
/// <summary>
/// The basket.
/// </summary>
private IBasket _basket;
/// <summary>
/// The <see cref="SalePreparationBase"/>.
/// </summary>
private Lazy<IBasketSalePreparation> _preparation;
/// <summary>
/// Initializes a new instance of the <see cref="CheckoutController"/> class.
/// </summary>
public CheckoutController()
{
this.Initialize();
}
/// <summary>
/// Renders the checkout page.
/// </summary>
/// <param name="model">
/// The model.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
public ActionResult Checkout(RenderModel model)
{
if (_customerContext.CurrentCustomer.Basket().IsEmpty)
{
return this.RedirectToUmbracoPage(ContentResolver.Instance.GetRootContent());
}
return this.CurrentView(model);
}
#region ChildActions
/// <summary>
/// Renders the Address Form.
/// </summary>
/// <param name="addressType">
/// The address type.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[ChildActionOnly]
public ActionResult AddressForm(AddressType addressType)
{
var preparation = _preparation.Value;
var model = preparation.GetBillToAddress() != null ? preparation.GetBillToAddress().AsAddressModel() :
new AddressModel();
model.Step = 1;
model.PreviousUrl = ContentResolver.Instance.GetBasketContent().Url;
return this.PartialView(model);
}
/// <summary>
/// Renders the delivery method form.
/// </summary>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[ChildActionOnly]
public ActionResult DeliveryMethod()
{
var preparation = _preparation.Value;
var address = preparation.GetBillToAddress() ?? new AddressModel().AsAddress(AddressType.Shipping);
var shipment = _basket.PackageBasket(address).FirstOrDefault();
if (shipment == null)
{
LogHelper.Error<CheckoutController>("Shipment was null", new NullReferenceException("Package basket returned a null shipment"));
}
var quotes = shipment.ShipmentRateQuotes().ToArray();
if (!quotes.Any())
{
LogHelper.Error<CheckoutController>("No shipping rate quotes where found", new NullReferenceException("No shipping rate quotes"));
}
var deliveryQuotes = quotes.Select(x => x.AsDeliveryQuote()).ToArray();
var shipMethodKey = Guid.Empty;
if (preparation.IsReadyToInvoice())
{
var shipmentLineItem = preparation.PrepareInvoice().ShippingLineItems().FirstOrDefault();
shipMethodKey = shipmentLineItem != null ?
shipmentLineItem.ExtendedData.GetShipment<InvoiceLineItem>().ShipMethodKey.GetValueOrDefault() :
Guid.Empty;
}
shipMethodKey = shipMethodKey.Equals(Guid.Empty) ? deliveryQuotes.First().Key : shipMethodKey;
return this.PartialView(new DeliveryMethod { ShipMethodKey = shipMethodKey, Quotes = deliveryQuotes });
}
/// <summary>
/// Renders the payment method form.
/// </summary>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[ChildActionOnly]
public ActionResult PaymentMethod()
{
var preparation = _preparation.Value;
var paymentMethods = preparation.GetPaymentGatewayMethods().Select(x => x.PaymentMethod).ToArray();
var model = new PaymentMethods
{
Methods = paymentMethods,
PreviousUrl = ContentResolver.Instance.GetBasketContent().Url,
SelectedPaymentMethod = paymentMethods.First().Key
};
return this.PartialView(model);
}
#endregion
/// <summary>
/// Saves an address.
/// </summary>
/// <param name="model">
/// The model.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveAddress(AddressModel model)
{
if (!ModelState.IsValid) return this.CurrentUmbracoPage();
var prepartion = _preparation.Value;
prepartion.SaveBillToAddress(model.AsAddress(AddressType.Billing));
prepartion.SaveShipToAddress(model.AsAddress(AddressType.Shipping));
this.UpdateStage(1);
return this.CurrentUmbracoPage();
}
/// <summary>
/// Saves the delivery method.
/// </summary>
/// <param name="model">
/// The model.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[HttpPost]
public ActionResult SaveDeliverMethod(DeliveryMethod model)
{
var preparation = _preparation.Value;
var address = preparation.GetShipToAddress();
var shipment = _basket.PackageBasket(address).FirstOrDefault();
preparation.ClearShipmentRateQuotes();
var quote = shipment.ShipmentRateQuoteByShipMethod(model.ShipMethodKey, false);
preparation.SaveShipmentRateQuote(quote);
this.UpdateStage(2);
return this.CurrentUmbracoPage();
}
/// <summary>
/// Saves the payment method selection.
/// </summary>
/// <param name="model">
/// The model.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[HttpPost]
public ActionResult SavePaymentMethod(PaymentMethods model)
{
var preparation = _preparation.Value;
var method =
preparation.GetPaymentGatewayMethods()
.FirstOrDefault(x => x.PaymentMethod.Key == model.SelectedPaymentMethod);
if (method != null)
preparation.SavePaymentMethod(method.PaymentMethod);
this.UpdateStage(3);
return this.CurrentUmbracoPage();
}
/// <summary>
/// Confirms the order.
/// </summary>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
/// <remarks>
/// This method is overly simple since we only have the cash provider installed.
/// Normally, we'd post values for processing a payment, but in this case we just need to authorize the
/// transaction.
/// </remarks>
[HttpGet]
public ActionResult ConfirmOrder()
{
var preparation = _preparation.Value;
var result = preparation.AuthorizePayment(preparation.GetPaymentMethod().Key);
var context = new ReceiptValueResolverContext();
context.SetValue(result.Invoice.Key);
return RedirectToUmbracoPage(ContentResolver.Instance.GetReceiptContent());
}
/// <summary>
/// Starts the checkout.
/// </summary>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
[HttpGet]
public ActionResult StartCheckout()
{
var context = new CheckoutStageResolverContext();
context.SetStage(0);
return this.RedirectToUmbracoPage(ContentResolver.Instance.GetCheckoutContent());
}
/// <summary>
/// Updates the stage.
/// </summary>
/// <param name="stage">
/// The stage.
/// </param>
private void UpdateStage(int stage)
{
var context = new CheckoutStageResolverContext();
context.SetStage(stage);
}
/// <summary>
/// Initializes the controller.
/// </summary>
private void Initialize()
{
_customerContext = PluggableObjectHelper.GetInstance<CustomerContextBase>("CustomerContext", UmbracoContext);
_basket = _customerContext.CurrentCustomer.Basket();
_preparation = new Lazy<IBasketSalePreparation>(() => _basket.SalePreparation());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Ionic.Zip;
using System.IO.Compression;
namespace MVArchive
{
class Program
{
static void Main(string[] args)
{
//toSplit(@"C:\github", "Duma_Aleksandr_Bolshoi_kulinarnyi_slovar_Litmir.net_bid177525_original_27179.pdf", 30 * 1024 * 1024);
join(@"C:\github", "Duma_Aleksandr_Bolshoi_kulinarnyi_slovar_Litmir.net_bid177525_original_27179.pdf");
}
static void toSplit(string path, string fileName, int size)
{
byte[] bt = File.ReadAllBytes(path + "\\" + fileName);
// Нахождения индекса элемента с которого начинается расширение
int indxx = 0;
for (int i = 0; i < fileName.Length; i++)
{
if (fileName[i] == '.')
{
indxx = i;
}
}
// Находит расширение
string extension = "";
for (int i = indxx; i < fileName.Length; i++)
{
extension += fileName[i];
}
// Имя файла без расширения
string flname = "";
for (int i = 0; i < fileName.Length-extension.Length; i++)
{
flname += fileName[i];
}
// Определяет количество архивов
int count = (bt.Length + size - 1) / size;
int cnt = 0;
for (int i = 0; i < count; i++)
{
//Создает архив
using (FileStream zipToOpen = new FileStream(path + "\\" +flname+"@"+i + ".zip", FileMode.OpenOrCreate))
{
//Открывает архив
using (ZipArchive zip = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
//Создает файл внутри архива
ZipArchiveEntry readmeEntry = zip.CreateEntry(i + extension);
//Открывает поток
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
long _byte_counter = size;
// Записывает байты в поток
while (_byte_counter > 0 && cnt < bt.Length)
{
_byte_counter--;
writer.BaseStream.WriteByte(bt[cnt]);
cnt++;
}
}
}
}
}
// Создание служебного файла; bt.Length - количество бит; size - размер 1-го тома; extension - расширение; fileName - имя без расширения
//System.IO.File.WriteAllText(path + "\\" +flname+ "_Info.txt", bt.Length.ToString() + "\r\n" + size + "\r\n" + extension);
}
static void join(string path, string fileName)
{
int indxx = 0;
for (int i = 0; i < fileName.Length; i++)
{
if (fileName[i] == '.')
{
indxx = i;
}
}
// Определяет имя файла без расширения
string flname = "";
for (int i = 0; i < indxx; i++)
{
flname += fileName[i];
}
string extension = "";
for (int i = indxx; i < fileName.Length; i++)
{
extension += fileName[i];
}
long bytesCount = 0;
//Нахождение всех файлов с фильтром *@*.zip
string[] allFoundFiles = Directory.GetFiles(path, "*@*.zip", SearchOption.AllDirectories);
long count = 0;
//int size = allFoundFiles.Length;
//int bytesCount = Convert.ToInt32(nbOfByte);
int[,] array = new int[allFoundFiles.Length, 2];
string tm = "";
// Записывает файлы в двумерный массив; 1-й столбец - число после @; 2-й столбец - индекс этого файла
for (int i = 0; i < allFoundFiles.Length; i++)
{
var a = allFoundFiles[i];
var fInd = a.IndexOf('@');
tm = "";
for (int j = fInd+1; j < a.Length - 4; j++)
{
tm += a[j];
}
array[i, 0] = Convert.ToInt32(tm);
array[i, 1] = i;
}
//Сортировка файлов
for (int i = 0; i < allFoundFiles.Length; i++)
{
for (int j = 0; j < allFoundFiles.Length - 1; j++)
{
if (array[j, 0] > array[j + 1,0])
{
int z = array[j,0];
int y = array[j, 1];
array[j,0] = array[j + 1,0];
array[j,1] = array[j + 1,1];
array[j + 1,0] = z;
array[j + 1, 1] = y;
}
}
}
for (int i = 0; i < allFoundFiles.Length; i++)
{
using (FileStream zipToOpen = new FileStream(allFoundFiles[array[i, 1]], FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.GetEntry(i + extension);
bytesCount += readmeEntry.Length;
}
}
}
byte[] byteArray = new byte[bytesCount];
//Читывает биты всех архивов
for (int i = 0; i < allFoundFiles.Length; i++)
{
using (FileStream zipToOpen = new FileStream(allFoundFiles[array[i,1]], FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.GetEntry(i+extension);
//var length = readmeEntry.Length;
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
var _byte_counter = bytesCount;
while (_byte_counter > 0 && count < bytesCount)
{
_byte_counter--;
byteArray[count] = (byte)writer.BaseStream.ReadByte();
count++;
}
}
}
}
}
int o = 0;
// Создание файла из бит
using (FileStream zipToOpen = new FileStream(path+ "\\" + flname + ".zip", FileMode.OpenOrCreate))
{
using (ZipArchive zip = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = zip.CreateEntry(flname + extension);
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
foreach (var item in byteArray)
{
writer.BaseStream.WriteByte(item);
}
}
}
}
}
}
}
|
namespace CheckIt.Syntax
{
public interface IClassMatcher
{
CheckMatch NameSpace();
CheckMatch Name();
}
} |
using DevilDaggersCore.Leaderboards.History.Completions;
using NetBase.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DevilDaggersCore.Leaderboards
{
[JsonObject(MemberSerialization.OptIn)]
public class Leaderboard
{
[JsonProperty]
public DateTime DateTime { get; set; } = DateTime.UtcNow;
[CompletionProperty]
[JsonProperty]
public int Players { get; set; }
[CompletionProperty]
[JsonProperty]
public ulong TimeGlobal { get; set; }
[CompletionProperty]
[JsonProperty]
public ulong KillsGlobal { get; set; }
[CompletionProperty]
[JsonProperty]
public ulong GemsGlobal { get; set; }
[CompletionProperty]
[JsonProperty]
public ulong DeathsGlobal { get; set; }
[CompletionProperty]
[JsonProperty]
public ulong ShotsHitGlobal { get; set; }
[CompletionProperty]
[JsonProperty]
public ulong ShotsFiredGlobal { get; set; }
[JsonProperty]
public List<Entry> Entries { get; set; } = new List<Entry>();
public double AccuracyGlobal => ShotsFiredGlobal == 0 ? 0 : ShotsHitGlobal / (double)ShotsFiredGlobal;
public bool HasBlankName => Entries.Any(e => e.IsBlankName());
public Completion Completion { get; } = new Completion();
public CompletionCombined UserCompletion { get; } = new CompletionCombined();
public Completion GetCompletion()
{
if (Completion.Initialized)
return Completion;
foreach (PropertyInfo info in GetType().GetProperties())
{
object value = info.GetValue(this);
if (value == null)
continue;
string valueString = value.ToString();
if (string.IsNullOrEmpty(valueString))
continue;
if (!Attribute.IsDefined(info, typeof(CompletionPropertyAttribute)))
continue;
if (valueString == ReflectionUtils.GetDefaultValue(value.GetType()).ToString())
Completion.CompletionEntries[info.Name] = CompletionEntry.Missing;
else
Completion.CompletionEntries[info.Name] = CompletionEntry.Complete;
}
int players = Players == 0 ? 100 : Math.Min(Players, 100);
if (Entries.Count != players)
Completion.CompletionEntries[$"{players - Entries.Count} users"] = CompletionEntry.Missing;
Completion.Initialized = true;
return Completion;
}
public CompletionCombined GetUserCompletion()
{
if (UserCompletion.Initialized)
return UserCompletion;
List<Completion> completions = new List<Completion>();
foreach (Entry entry in Entries)
completions.Add(entry.GetCompletion());
int total = HasBlankName ? completions.Count - 1 : completions.Count;
foreach (KeyValuePair<string, CompletionEntry> kvp in completions[0].CompletionEntries)
{
int missing = 0;
for (int i = 0; i < completions.Count; i++)
{
if (Entries[i].IsBlankName())
continue;
if (completions[i].CompletionEntries.TryGetValue(kvp.Key, out CompletionEntry ce) && ce == CompletionEntry.Missing)
missing++;
}
UserCompletion.CompletionEntries[kvp.Key] = missing == 0 ? CompletionEntryCombined.Complete : missing == total ? CompletionEntryCombined.Missing : CompletionEntryCombined.PartiallyMissing;
}
UserCompletion.Initialized = true;
return UserCompletion;
}
public float GetCompletionRate()
{
int total = HasBlankName ? 99 : 100;
int totalEntries = Players == 0 ? total : Math.Min(Players, total);
float globalCompletionRate = GetCompletion().GetCompletionRate();
float userCompletionRate = 0;
foreach (Entry entry in Entries)
{
if (entry.IsBlankName())
continue;
userCompletionRate += entry.GetCompletion().GetCompletionRate() * (1f / totalEntries);
}
return userCompletionRate * 0.99f + globalCompletionRate * 0.01f;
}
public string FormatShotsGlobal(bool history)
{
if (history && (ShotsHitGlobal == 0 || ShotsFiredGlobal == 10000))
return "Exact values not known";
return $"{ShotsHitGlobal.ToString("N0")} / {ShotsFiredGlobal.ToString("N0")}";
}
}
} |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Witsml;
using Witsml.Extensions;
using Witsml.Data;
using Witsml.Data.Curves;
using Witsml.ServiceReference;
using WitsmlExplorer.Api.Jobs;
using WitsmlExplorer.Api.Jobs.Common;
using WitsmlExplorer.Api.Services;
using WitsmlExplorer.Api.Workers;
using Xunit;
using WitsmlExplorer.Api.Query;
namespace WitsmlExplorer.IntegrationTests.Api.Workers
{
[SuppressMessage("ReSharper", "xUnit1004")]
public class CopyLogWorkerTests
{
private readonly CopyLogWorker worker;
private readonly DeleteLogObjectsWorker deleteLogsWorker;
private readonly IWitsmlClient client;
private readonly LogObjectService logObjectService;
public CopyLogWorkerTests()
{
var configuration = ConfigurationReader.GetConfig();
var witsmlClientProvider = new WitsmlClientProvider(configuration);
client = witsmlClientProvider.GetClient();
worker = new CopyLogWorker(witsmlClientProvider);
deleteLogsWorker = new DeleteLogObjectsWorker(witsmlClientProvider);
logObjectService = new LogObjectService(witsmlClientProvider);
}
[Fact(Skip = "Should only be run manually")]
public async Task CopyLog()
{
var job = new CopyLogJob
{
Source = new LogReferences
{
LogReferenceList = new[]
{
new LogReference
{
WellUid = "",
WellboreUid = "",
LogUid = "",
}
}
},
Target = new WellboreReference
{
WellUid = "",
WellboreUid = ""
}
};
await worker.Execute(job);
}
[Fact(Skip = "Should only be run manually")]
public async Task CopyLog_VerifyLogDataIsCopied()
{
const string logUid = "";
var sourceReference = new LogReferences
{
LogReferenceList = new[]
{
new LogReference
{
WellUid = "",
WellboreUid = "",
LogUid = "",
}
}
};
var targetReference = new LogReference
{
WellUid = "",
WellboreUid = "",
LogUid = logUid
};
await deleteLogsWorker.Execute(new DeleteLogObjectsJob { LogReferences = targetReference.AsSingletonList().ToArray() });
var job = new CopyLogJob
{
Source = sourceReference,
Target = new WellboreReference
{
WellUid = targetReference.WellUid,
WellboreUid = targetReference.WellboreUid
}
};
await worker.Execute(job);
var sourceLog = await GetLog(sourceReference.LogReferenceList.First());
var targetLog = await GetLog(targetReference);
var currentIndex = Index.Start(sourceLog);
var endIndex = await GetEndIndex(targetReference);
while (currentIndex != endIndex)
{
var sourceLogData = await logObjectService.ReadLogData(sourceReference.LogReferenceList.FirstOrDefault()?.WellUid,
sourceReference.LogReferenceList.FirstOrDefault()?.WellboreUid, logUid,
new List<string>(sourceLog.LogData.MnemonicList.Split(",")), currentIndex.Equals(Index.Start(sourceLog)),
currentIndex.GetValueAsString(), endIndex.ToString());
var targetLogData = await logObjectService.ReadLogData(targetReference.WellUid, targetReference.WellboreUid, logUid,
new List<string>(targetLog.LogData.MnemonicList.Split(",")), currentIndex.Equals(Index.Start(targetLog)),
currentIndex.GetValueAsString(), endIndex.ToString());
Assert.Equal(sourceLogData.EndIndex, targetLogData.EndIndex);
Assert.Equal(sourceLogData.CurveSpecifications.Count(), targetLogData.CurveSpecifications.Count());
Assert.Equal(sourceLogData.Data.Count(), targetLogData.Data.Count());
currentIndex = Index.End(sourceLog, sourceLogData.EndIndex);
}
}
private async Task<WitsmlLog> GetLog(LogReference logReference)
{
var logQuery = LogQueries.GetWitsmlLogById(logReference.WellUid, logReference.WellboreUid, logReference.LogUid);
var logs = await client.GetFromStoreAsync(logQuery, new OptionsIn(ReturnElements.All));
return !logs.Logs.Any() ? null : logs.Logs.First();
}
private async Task<Index> GetEndIndex(LogReference logReference)
{
var logQuery = LogQueries.GetWitsmlLogById(logReference.WellUid, logReference.WellboreUid, logReference.LogUid);
var logs = await client.GetFromStoreAsync(logQuery, new OptionsIn(ReturnElements.HeaderOnly));
return Index.End(logs.Logs.First());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using TMPro;
using UnityEngine;
public class ShopUI : MonoBehaviour {
public GameObject shipShopUI;
public GameObject trailShopUI;
public RectTransform shipScrollContent;
public RectTransform trailsScrollContent;
public float spacing;
public List<ShopShipUI> shipUIs;
public List<TrailShopUI> trailUIs;
public GameObject shipShop;
public GameObject trailsShop;
public bool isShipShopActive;
public TextMeshProUGUI changeShopButtonText;
void Start () {
int iterator = 0;
foreach (ShipDefinition ship in GameManager.instance.ships) {
var ui = Instantiate (shipShopUI, shipScrollContent).GetComponent<ShopShipUI> ();
shipUIs.Add (ui);
ui.checkmark.SetActive (false);
ui.shipIcon.sprite = ship.shipIcon;
ui.name.text = ship.shipName;
ui.price.text = ship.shipPrice.ToString ("N0") + " Cr";
ui.ship = ship;
ui.GetComponent<RectTransform> ().localPosition = new Vector3 (0, -175 + (-iterator * spacing), 0);
iterator++;
}
shipScrollContent.sizeDelta = new Vector2 (shipScrollContent.sizeDelta.x, iterator * spacing + 25);
shipScrollContent.localPosition = new Vector2 (0, -shipScrollContent.sizeDelta.y / 2);
iterator = 0;
foreach (TrailDefinition trail in GameManager.instance.trails) {
var ui = Instantiate (trailShopUI, trailsScrollContent).GetComponent<TrailShopUI> ();
trailUIs.Add (ui);
ui.checkmark.SetActive (false);
ui.trailIcon.sprite = trail.trailIcon;
ui.name.text = trail.trailName;
ui.price.text = trail.trailPrice.ToString ("N0") + " Cr";
ui.trail = trail;
ui.GetComponent<RectTransform> ().localPosition = new Vector3 (0, -175 + (-iterator * spacing), 0);
iterator++;
}
trailsScrollContent.sizeDelta = new Vector2 (trailsScrollContent.sizeDelta.x, iterator * spacing + 25);
trailsScrollContent.localPosition = new Vector2 (0, -trailsScrollContent.sizeDelta.y / 2);
RebuildShipUI ();
RebuildTrailUI ();
}
public void UseShip () {
foreach (ShopShipUI ship in shipUIs) {
ship.ship.isUsed = false;
if (GameManager.instance.ships[GameManager.instance.currentShip] == ship.ship) {
ship.ship.isUsed = true;
}
}
RebuildShipUI ();
DataManager.SaveData ();
}
public void BuyShip (ShipDefinition ship) {
if (GameManager.instance.credits >= ship.shipPrice) {
GameManager.instance.credits -= ship.shipPrice;
GameManager.instance.currentShip = GameManager.instance.ships.IndexOf (ship);
ship.isBought = true;
FindObjectOfType<MenuUIController> ().creditsText.text = GameManager.instance.credits.ToString ("N0");
UseShip ();
}
DataManager.SaveData ();
}
public void RebuildShipUI () {
foreach (ShopShipUI ship in shipUIs) {
ship.buyButton.SetActive (true);
ship.useButton.SetActive (false);
ship.checkmark.SetActive (false);
if (ship.ship.isBought) {
ship.buyButton.SetActive (false);
ship.useButton.SetActive (true);
}
if (ship.ship.isUsed) {
ship.checkmark.SetActive (true);
ship.useButton.SetActive (false);
}
}
}
public void UseTrail () {
foreach (TrailShopUI trail in trailUIs) {
trail.trail.isUsed = false;
if (GameManager.instance.trails[GameManager.instance.currentTrail] == trail.trail) {
trail.trail.isUsed = true;
}
}
RebuildTrailUI ();
DataManager.SaveData ();
}
public void BuyTrail (TrailDefinition trail) {
if (GameManager.instance.credits >= trail.trailPrice) {
GameManager.instance.credits -= trail.trailPrice;
GameManager.instance.currentTrail = GameManager.instance.trails.IndexOf (trail);
trail.isBought = true;
FindObjectOfType<MenuUIController> ().creditsText.text = GameManager.instance.credits.ToString ("N0");
UseTrail ();
}
DataManager.SaveData ();
}
public void RebuildTrailUI () {
foreach (TrailShopUI trail in trailUIs) {
trail.buyButton.SetActive (true);
trail.useButton.SetActive (false);
trail.checkmark.SetActive (false);
if (trail.trail.isBought) {
trail.buyButton.SetActive (false);
trail.useButton.SetActive (true);
}
if (trail.trail.isUsed) {
trail.checkmark.SetActive (true);
trail.useButton.SetActive (false);
}
}
}
public void ChangeShop () {
if (isShipShopActive) {
trailsShop.GetComponent<RectTransform> ().DOLocalMove (new Vector3 (0, 195, 0), 0.2f);
shipShop.GetComponent<RectTransform> ().DOLocalMove (new Vector3 (-1080, 195, 0), 0.2f);
changeShopButtonText.text = "Ships";
} else {
shipShop.GetComponent<RectTransform> ().DOLocalMove (new Vector3 (0, 195, 0), 0.2f);
trailsShop.GetComponent<RectTransform> ().DOLocalMove (new Vector3 (-1080, 195, 0), 0.2f);
changeShopButtonText.text = "Trails";
}
isShipShopActive = !isShipShopActive;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConFutureNce.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace ConFutureNce.Extensions
{
public class AccountRolesManagement
{
public static async Task CreateRoles(ConFutureNceContext context)
{
var userManager = context.GetService<UserManager<ApplicationUser>>();
var roleManager = context.GetService<RoleManager<IdentityRole>>();
// Add roles to app
string[] roleNames =
{
"Admin",
"Author",
"Organizer",
"ProgrammeCommitteeMember",
"Reviewer"
};
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
var myUser = await userManager.FindByEmailAsync("peciak@gmail.com");
if ( myUser != null && !await userManager.IsInRoleAsync(myUser, "Author"))
{
// Assigne user to role
await userManager.AddToRoleAsync(myUser, "Author");
}
}
}
}
|
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 PPO1
{
public partial class AddPoint : Form
{
Controller control;
RoutePoint currentPoint;
string name;
private double Latitude;
private double Longitude;
private double Elevation;
/*public double Longitude { get; private set; }
public double Latitude { get; private set; }
public double Elevation { get; private set; }*/
public AddPoint()
{
InitializeComponent();
}
public AddPoint(Controller control, string name)
{
InitializeComponent();
this.control = control;
this.name = name;
}
public AddPoint(Controller control, RoutePoint CurrentPoint, string Latitude, string Longitude, string Elevation, string name)
{
InitializeComponent();
this.control = control;
this.name = name;
this.currentPoint = CurrentPoint;
this.LongitudeTextBox.Text = Longitude;
this.LatitudeTextBox.Text = Latitude;
this.ElevationTextBox.Text = Elevation;
this.AddButton.Text = "Edit";
}
public string GetLatitude()
{
return LatitudeTextBox.Text;
}
public string GetLongitude()
{
return LongitudeTextBox.Text;
}
public string GetElevation()
{
return ElevationTextBox.Text;
}
private void CancelButton_Click(object sender, EventArgs e)
{
Hide();
}
private void AddButton_Click(object sender, EventArgs e)
{
// double Latitude;
// double Longitude;
// double Elevation;
if (GetLatitude() != "" && GetLongitude() != "" && GetElevation() != "")
{
Double.TryParse(GetLatitude().Replace('.', ','), out Latitude);
Double.TryParse(GetLongitude().Replace('.', ','), out Longitude);
Double.TryParse(GetElevation().Replace('.', ','), out Elevation);
RoutePoint routePoint = new RoutePoint(Longitude, Latitude, Elevation);
if (AddButton.Text == "Add point")
{
control.AddPointToRoute(name, routePoint);
}
else
{
control.EditPoint(name,currentPoint, Latitude.ToString(), Longitude.ToString(), Elevation.ToString());
}
Hide();
}
else
MessageBox.Show("Поля были неверно введены", "Добавление точки", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
|
using lesson6.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Net;
using System.IO;
using System.Text.Json;
using System.Text;
namespace lesson6.Services
{
public class OpenWeatherService : IWeatherService
{
private readonly OpenWeatherSettings _weatherServiceSettings;
const double kelvin = 273.15;
public OpenWeatherService(IOptions<OpenWeatherSettings> options) => _weatherServiceSettings = options.Value;
public async Task<IWeather> GetWeatherAsync(string region = null)
{
region = region ?? _weatherServiceSettings.Region;
Weather weather = new Weather() {Region = region };
string site = $"https://{_weatherServiceSettings.Host}/{_weatherServiceSettings.Method}?q={region}&apikey={_weatherServiceSettings.Apikey}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
using (Stream stream = response.GetResponseStream())
using (JsonDocument doc = await JsonDocument.ParseAsync(stream))
{
JsonElement el = doc.RootElement.GetProperty("main")
.GetProperty("temp");
if (el.TryGetDouble(out double temp))
weather.Temp = (int)(temp - kelvin);
return weather;
}
}
}
}
|
using System.Xml;
namespace pjank.BossaAPI.Fixml
{
/// <summary>
/// Klasa ułatwiająca tworzenie/wysyłanie własnych komunikatów FIXML,
/// dla których nie zaimplementowano żadnej specjalnej, odrębnej klasy.
/// Ewentualnie do wykorzystania przy testowaniu protokołu komunikacyjnego...
/// </summary>
public class CustomMsg : FixmlMsg
{
public CustomMsg(string name)
{
PrepareXmlMessage(name);
}
new public XmlElement AddElement(string name) { return base.AddElement(name); }
new public XmlElement AddElement(XmlElement parent, string name) { return base.AddElement(parent, name); }
}
}
|
using FamilyAccounting.BL.DTO;
using FamilyAccounting.DAL.Entities;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace FamilyAccounting.Tests.Integration_Tests
{
public class CardsControllerTests : TestClientProvider
{
[Test]
public async Task Test_AddCard_ReturnsOk()
{
// Arrange
var newCard = new CardDTO { WalletId = 1, Description = "for shopping"};
CardRepoMock.Setup(r => r.CreateAsync(It.IsAny<Card>())).ReturnsAsync(new Card());
var newCardJson = JsonConvert.SerializeObject(newCard);
var content = new StringContent(newCardJson, Encoding.UTF8, "application/json");
// Act
var response = await Client.PostAsync("/api/cards/Create", content);
// Assert
response.EnsureSuccessStatusCode();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
CardRepoMock.Verify(r => r.CreateAsync(It.IsAny<Card>()), Times.Once);
}
[Test]
public async Task Test_UpdateCard_ReturnsOk()
{
// Arrange
var walletId = 1;
var card = new CardDTO { WalletId = walletId, Description = "new description"};
CardRepoMock.Setup(r => r.UpdateAsync(walletId, It.IsAny<Card>())).ReturnsAsync(new Card());
var newCardJson = JsonConvert.SerializeObject(card);
var content = new StringContent(newCardJson, Encoding.UTF8, "application/json");
// Act
var response = await Client.PutAsync($"/api/cards/Update/{walletId}", content);
// Assert
response.EnsureSuccessStatusCode();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
CardRepoMock.Verify(r => r.UpdateAsync(walletId, It.IsAny<Card>()), Times.Once);
}
[Test]
public async Task Test_DeleteCard_ReturnsOk()
{
// Arrange
var walletId = 1;
CardRepoMock.Setup(r => r.DeleteAsync(walletId)).ReturnsAsync(0);
// Act
var response = await Client.DeleteAsync($"/api/cards/Delete/{walletId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
CardRepoMock.Verify(r => r.DeleteAsync(walletId), Times.Once);
}
[Test]
public async Task Test_DetailsCard_ReturnsOk()
{
// Arrange
var walletId = 1;
CardRepoMock.Setup(r => r.GetAsync(walletId)).ReturnsAsync(new Card { WalletId = walletId, Description="for shopping", Number = "3566002020360505" });
// Act
var response = await Client.GetAsync($"/api/cards/Details/{walletId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
var card = JsonConvert.DeserializeObject<CardDTO>(content);
Assert.AreEqual(walletId, card.WalletId);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#pragma warning disable 0649 // For serialized fields
using UnityEngine;
public class Lightning : FingerSurface
{
const int maxRandomSamples = 20;
[SerializeField]
private MeshSampler sampler;
[SerializeField]
private SurfaceArc[] surfaceArcs;
[SerializeField]
private FingerArc[] fingerArcs;
[SerializeField]
private Transform[] fingerArcSources;
[SerializeField]
private float randomSurfaceArcChange = 0.05f;
[SerializeField]
private float randomFingerArcChange = 0.05f;
[SerializeField]
private float fingerEngageDistance = 0.15f;
[SerializeField]
private float fingerRandomPosRadius = 0.15f;
[SerializeField]
private float fingerDisengageDistance = 1f;
[SerializeField]
private Gradient glowGradient;
[SerializeField]
private Renderer coreRenderer;
[SerializeField]
private float glowSpeed = 0.5f;
[SerializeField]
private AnimationCurve intensityCurve;
[SerializeField]
private AnimationCurve flickerCurve;
[SerializeField]
private AnimationCurve buzzAudioPitch;
[SerializeField]
private AudioSource buzzAudio;
private int numFingersEngaged = 0;
private float glow = 0;
public override void Initialize(Vector3 surfacePosition)
{
base.Initialize(surfacePosition);
sampler.SampleMesh(true);
for (int i = 0; i < surfaceArcs.Length; i++)
{
MeshSample point1 = sampler.Samples[Random.Range(0, sampler.Samples.Length)];
MeshSample point2 = sampler.Samples[Random.Range(0, sampler.Samples.Length)];
surfaceArcs[i].SetArc(point1, point2, Vector3.zero, SurfaceRadius);
}
buzzAudio.pitch = 0;
}
private void Update()
{
if (!Initialized)
return;
UpdateFingers();
UpdateArcs();
UpdateGlow();
UpdateAudio();
}
private void UpdateArcs()
{
FingerArc.UpdateArcLights();
int maxActiveArcs = surfaceArcs.Length - numFingersEngaged;
for (int i = 0; i < surfaceArcs.Length; i++)
surfaceArcs[i].gameObject.SetActive(i < maxActiveArcs);
if (Random.value < randomSurfaceArcChange)
{
SurfaceArc arc = surfaceArcs[Random.Range(0, surfaceArcs.Length)];
if (Random.value > 0.5f)
{
arc.gameObject.SetActive(true);
MeshSample point1 = sampler.Samples[Random.Range(0, sampler.Samples.Length)];
MeshSample point2 = sampler.Samples[Random.Range(0, sampler.Samples.Length)];
arc.SetArc(point1, point2, transform.position, SurfaceRadius);
}
else
{
arc.gameObject.SetActive(false);
}
}
}
private void UpdateFingers()
{
numFingersEngaged = 0;
for (int i = 0; i < fingers.Length; i++)
{
Transform finger = fingers[i];
FingerArc arc = fingerArcs[i];
if (!finger.gameObject.activeSelf)
{
arc.gameObject.SetActive(false);
continue;
}
if (arc.gameObject.activeSelf)
{
// See if we're too far away
MeshSample sample = sampler.Samples[arc.Point1SampleIndex];
if (Vector3.Distance(sample.Point, finger.position) > fingerDisengageDistance)
{ // If we are, disable the arc and move on
arc.gameObject.SetActive(false);
continue;
}
else
{ // If we aren't, see if it's time to zap to a different position
if (Random.value < randomFingerArcChange)
{ // Get the closest point on the sphere
MeshSample point1 = sampler.ClosestSample(finger.position);
// Then get a random sample somewhere nearby
point1 = sampler.RandomSample(point1.Point, fingerRandomPosRadius);
arc.SetArc(point1, fingerArcSources[i]);
}
numFingersEngaged++;
}
}
else
{ // See if we're close enough to any samples to start
// Get the closest point on the sphere
MeshSample point1 = sampler.ClosestSample(finger.position);
if (Vector3.Distance(point1.Point, finger.position) < fingerEngageDistance)
{ // Then get a random sample somewhere nearby
point1 = sampler.RandomSample(point1.Point, fingerRandomPosRadius);
arc.gameObject.SetActive(true);
arc.SetArc(point1, fingerArcSources[i]);
numFingersEngaged++;
}
}
}
}
private void UpdateGlow()
{
float targetGlow = (float)numFingersEngaged / 10;
glow = Mathf.Lerp(glow, targetGlow, Time.deltaTime * glowSpeed);
float randomValue = flickerCurve.Evaluate(targetGlow) * Random.Range(-1f, 1f);
float intensity = intensityCurve.Evaluate(targetGlow);
coreRenderer.material.SetColor("_EmissiveColor", glowGradient.Evaluate(glow + randomValue) * intensity);
}
private void UpdateAudio()
{
buzzAudio.pitch = buzzAudioPitch.Evaluate(glow);
}
private void OnDrawGizmos()
{
for (int i = 0; i < fingers.Length; i++)
{
Transform finger = fingers[i];
Gizmos.color = Color.red;
Gizmos.DrawSphere(finger.position, 0.01f);
Gizmos.color = Color.Lerp(Color.green, Color.clear, 0.5f);
Gizmos.DrawWireSphere(finger.position, fingerEngageDistance);
if (fingerArcs[i].gameObject.activeSelf)
{
Gizmos.color = Color.Lerp(Color.red, Color.clear, 0.5f);
Gizmos.DrawWireSphere(finger.position, fingerDisengageDistance);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GameOptionEnum
{
public enum eGameOptions
{
COMPUTER = 0,
HUMAN_PLAYER = 1
}
}
|
using UnityEngine;
using System.Collections;
public class Advice : MonoBehaviour {
public static Advice instance;
void Awake () {
instance = this;
ShowAdvice(false);
}
public void ShowAdvice(bool value)
{
if(value)
{
Caapora.GameManager.ShowObjectAPeriodOfTime(gameObject, 5);
}
else
gameObject.SetActive(false);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DealDamage : MonoBehaviour {
//Define Enum
public enum Props_Enum { waterProps, fireProps, forestProps };
//This what you need to show in the inspector.
private Props_Enum Current_props;
private string Current_Plane;
public Slider HealthBar;
public float MaxHealth;
private float CurrentHealth;
// Use this for initialization
void Start () {
CurrentHealth = MaxHealth;
HealthBar.value = CalaulateDamage();
}
// Update is called once per frame
void Update () {
Current_props = (Props_Enum)Drag.CurrentenumIndex;
Deal_Damage(1);
}
public void OnTriggerEnter(Collider other)
{
Current_Plane = other.gameObject.tag;
Debug.Log(other.gameObject.tag);
Deal_Damage(1);
Current_props = (Props_Enum)Drag.CurrentenumIndex;
}
private void Deal_Damage(float DamageValue)
{
if (Current_Plane == "Water")
{
if (Current_props != Props_Enum.waterProps)
{
CurrentHealth -= DamageValue;
HealthBar.value = CalaulateDamage();
}
}
if (Current_Plane == "Fire")
{
if (Current_props != Props_Enum.fireProps)
{
CurrentHealth -= DamageValue;
HealthBar.value = CalaulateDamage();
}
}
if (Current_Plane == "Forest")
{
if (Current_props != Props_Enum.forestProps)
{
CurrentHealth -= DamageValue;
HealthBar.value = CalaulateDamage();
}
}
}
float CalaulateDamage()
{
return CurrentHealth / MaxHealth;
}
}
|
using System.IO;
using System.Text;
using System.Threading.Tasks;
#if NETSTANDARD1_3
namespace System.CodeDom.Compiler
{
public sealed class IndentedTextWriter : TextWriter
{
private readonly TextWriter _BaseWriter;
private bool _LineWritten;
public IndentedTextWriter(TextWriter baseWriter)
{
_BaseWriter = baseWriter;
}
public override Encoding Encoding
=> _BaseWriter.Encoding;
public override IFormatProvider FormatProvider
=> _BaseWriter.FormatProvider;
public override string NewLine
{
get => _BaseWriter.NewLine;
set => _BaseWriter.NewLine = value;
}
public int Indent { get; set; }
#region Flush
public override void Flush()
=> _BaseWriter.Flush();
public override Task FlushAsync()
=> _BaseWriter.FlushAsync();
#endregion Flush
#region Write
public override void Write(bool value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(char value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(char[] buffer)
{
WriteIndentIfNeeded();
_BaseWriter.Write(buffer);
_LineWritten = true;
}
public override void Write(char[] buffer, int index, int count)
{
WriteIndentIfNeeded();
_BaseWriter.Write(buffer, index, count);
_LineWritten = true;
}
public override void Write(decimal value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(double value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(float value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(int value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(long value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(object value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(string format, object arg0)
{
WriteIndentIfNeeded();
_BaseWriter.Write(format, arg0);
_LineWritten = true;
}
public override void Write(string format, object arg0, object arg1)
{
WriteIndentIfNeeded();
_BaseWriter.Write(format, arg0, arg1);
_LineWritten = true;
}
public override void Write(string format, object arg0, object arg1, object arg2)
{
WriteIndentIfNeeded();
_BaseWriter.Write(format, arg0, arg1, arg2);
_LineWritten = true;
}
public override void Write(string format, params object[] arg)
{
WriteIndentIfNeeded();
_BaseWriter.Write(format, arg);
_LineWritten = true;
}
public override void Write(string value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(uint value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
public override void Write(ulong value)
{
WriteIndentIfNeeded();
_BaseWriter.Write(value);
_LineWritten = true;
}
#endregion Write
#region WriteAsync
public override async Task WriteAsync(char value)
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteAsync(value).ConfigureAwait(false);
_LineWritten = true;
}
public override async Task WriteAsync(char[] buffer, int index, int count)
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteAsync(buffer, index, count).ConfigureAwait(false);
_LineWritten = true;
}
public override async Task WriteAsync(string value)
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteAsync(value).ConfigureAwait(false);
_LineWritten = true;
}
#endregion WriteAsync
#region WriteLine
public override void WriteLine()
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine();
_LineWritten = false;
}
public override void WriteLine(bool value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(char value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(char[] buffer)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(buffer);
_LineWritten = false;
}
public override void WriteLine(char[] buffer, int index, int count)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(buffer, index, count);
_LineWritten = false;
}
public override void WriteLine(decimal value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(double value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(float value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(int value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(long value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(object value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(string format, params object[] arg)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(format, arg);
}
public override void WriteLine(string format, object arg0)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(format, arg0);
_LineWritten = false;
}
public override void WriteLine(string format, object arg0, object arg1)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(format, arg0, arg1);
_LineWritten = false;
}
public override void WriteLine(string format, object arg0, object arg1, object arg2)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(format, arg0, arg1, arg2);
_LineWritten = false;
}
public override void WriteLine(string value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(uint value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
public override void WriteLine(ulong value)
{
WriteIndentIfNeeded();
_BaseWriter.WriteLine(value);
_LineWritten = false;
}
#endregion WriteLine
#region WriteLineAsync
public override async Task WriteLineAsync()
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteLineAsync();
_LineWritten = true;
}
public override async Task WriteLineAsync(char value)
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteLineAsync(value);
_LineWritten = true;
}
public override async Task WriteLineAsync(char[] buffer, int index, int count)
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteLineAsync(buffer, index, count);
_LineWritten = true;
}
public override async Task WriteLineAsync(string value)
{
await WriteIndentIfNeededAsync().ConfigureAwait(false);
await _BaseWriter.WriteLineAsync(value);
_LineWritten = true;
}
#endregion WriteLineAsync
private void WriteIndentIfNeeded()
{
if (!_LineWritten)
{
for (var i = 0; i < Indent; i++)
{
for (var j = 0; j < 4; j++)
{
_BaseWriter.Write(' ');
}
}
_LineWritten = true;
}
}
private async Task WriteIndentIfNeededAsync()
{
if (!_LineWritten)
{
await _BaseWriter.WriteAsync(new string(' ', Indent * 4)).ConfigureAwait(false);
_LineWritten = true;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_BaseWriter?.Dispose();
}
base.Dispose(disposing);
}
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PartStore.Services
{
public class StubVansService : IVansService
{
public IEnumerable<Van> GetVans()
{
yield return new Van { Make = "Volkswagen", Model = "Caddy", Registration = "AB56 AAA", LastServiced = DateTime.Now.AddMonths(-3), LastWashed = DateTime.Now.AddDays(-8) };
yield return new Van { Make = "Mercedes", Model = "Sprinter", Registration = "AB56 BBB", LastServiced = DateTime.Now.AddMonths(-3), LastWashed = DateTime.Now.AddDays(-8) };
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace SC.Models
{
[Table("ProductTypes")]
public class ProductType
{
public int Id { get; set; }
public string Type { get; set; }
//public ICollection<Product> Products { get; set; }
}
}
|
namespace BettingSystem.Application.Identity
{
using System.Reflection;
using Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public static class ApplicationConfiguration
{
public static IServiceCollection AddApplication(
this IServiceCollection services,
IConfiguration configuration)
=> services
.AddCommonApplication(
configuration,
Assembly.GetExecutingAssembly());
}
}
|
using Lcn.Cli.CoreBase.Args;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace Lcn.Cli.CoreBase.Commands
{
public class HelpCommand : IConsoleCommand, ITransientDependency
{
public ILogger<HelpCommand> Logger { get; set; }
protected IHybridServiceScopeFactory ServiceScopeFactory { get; }
protected LcnCliCoreBaseOptions LcnCliCoreBaseOptions { get; }
public HelpCommand(IOptions<LcnCliCoreBaseOptions> options, IHybridServiceScopeFactory serviceScopeFactory)
{
ServiceScopeFactory = serviceScopeFactory;
LcnCliCoreBaseOptions = options.Value;
Logger = NullLogger<HelpCommand>.Instance;//默认空日志
}
public Task ExcuteAsync(CommandLineArgs commandLineArgs)
{
if (string.IsNullOrWhiteSpace(commandLineArgs.Target))
{
Logger.LogInformation(GetUsageInfo());
return Task.CompletedTask;
}
if (!LcnCliCoreBaseOptions.Commands.ContainsKey(commandLineArgs.Target))
{
Logger.LogWarning($"找不到命令 {commandLineArgs.Target}.是否输入错误?");
Logger.LogInformation(GetUsageInfo());
return Task.CompletedTask;
}
var commandType = LcnCliCoreBaseOptions.Commands[commandLineArgs.Target];
using (var scope = ServiceScopeFactory.CreateScope())
{
var command = (IConsoleCommand)scope.ServiceProvider.GetRequiredService(commandType);
Logger.LogInformation(command.GetUsageInfo());
}
return Task.CompletedTask;
}
public string GetShortDescription()
{
return $"显示控制台帮助命令. 输入 ` {LcnCliCoreBaseOptions.ToolName} help <command> ` 查看命令帮助!";
}
public string GetUsageInfo()
{
var sb = new StringBuilder();
sb.AppendLine("");
sb.AppendLine("使用例子:");
sb.AppendLine("");
sb.AppendLine($" {LcnCliCoreBaseOptions.ToolName} <command> <target> [options]");
sb.AppendLine("");
sb.AppendLine("命令列表:");
sb.AppendLine("");
foreach (var command in LcnCliCoreBaseOptions.Commands.ToArray())
{
string shortDescription;
using (var scope = ServiceScopeFactory.CreateScope())
{
shortDescription = ((IConsoleCommand)scope.ServiceProvider
.GetRequiredService(command.Value)).GetShortDescription();
}
sb.Append(" > ");
sb.Append(command.Key);
sb.Append(string.IsNullOrWhiteSpace(shortDescription) ? "" : ":");
sb.Append(" ");
sb.AppendLine(shortDescription);
}
sb.AppendLine("");
sb.AppendLine("了解命令的详细使用帮助,使用以下命令:");
sb.AppendLine("");
sb.AppendLine($" {LcnCliCoreBaseOptions.ToolName} help <command>");
sb.AppendLine("");
sb.AppendLine($"查阅详细文档获取更新信息: {LcnCliCoreBaseOptions.ToolDocUrl}");
return sb.ToString();
}
}
}
|
namespace BettingSystem.Domain.Common.Events.Teams
{
public class TeamCreatedEvent : IDomainEvent
{
public TeamCreatedEvent(
string name,
byte[] logoOriginalContent,
byte[] logoThumbnailContent)
{
this.Name = name;
this.LogoOriginalContent = logoOriginalContent;
this.LogoThumbnailContent = logoThumbnailContent;
}
public string Name { get; }
public byte[] LogoOriginalContent { get; }
public byte[] LogoThumbnailContent { get; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CommonScripts
{
public class LightControllScipt : MonoBehaviour
{
public bool InitOnStart = false;
public float Range = 10;
public float Intensity = 0.5f;
public bool IsOn = false;
public float DRange = 5;
public float DIntensity = 5;
[SerializeField]
public Light[] Lights = new Light[0];
[SerializeField]
public Light[] DecorLights = new Light[0];
void Start()
{
foreach (Light l in Lights)
{
if (IsOn)
l.enabled = true;
else
l.enabled = false;
if (!InitOnStart)
continue;
l.intensity = Intensity;
l.range = Range;
}
foreach(Light l in DecorLights)
{
if (IsOn)
l.enabled = true;
else
l.enabled = false;
if (!InitOnStart)
continue;
l.intensity = DIntensity;
l.range = DRange;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace WeatherApp1
{
class SelectCityPage:FakePage
{
ScrollViewer _citySv;
StackPanel _citySp;
ScrollViewer _selectSv;
StackPanel _selectSp;
Grid _addGrid;
TextBox _tb;
Button _search, _locating;
public event EventHandler<CityEventArgs> AddCityEvent;
public event EventHandler<CityEventArgs> RemoveCityEvent;
public event EventHandler<CityEventArgs> ClickCityEvent;
public event EventHandler<CityEventArgs> PinCityEvent;
public event EventHandler LocatingEvent;
public override void SetUI()
{
RootGrid = new Grid();
RootGrid.RowDefinitions.Add(new RowDefinition() { Height=GridLength.Auto });
RootGrid.RowDefinitions.Add(new RowDefinition());
RootGrid.RowDefinitions.Add(new RowDefinition() { Height=GridLength.Auto });
_addGrid = new Grid();
_addGrid.ColumnDefinitions.Add(new ColumnDefinition());
_addGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
RootGrid.Children.Add(_addGrid);
Grid.SetRow(_addGrid, 0);
_tb = new TextBox() { Text="城市名称或缩写" };
_tb.TextChanged += _tb_TextChanged;
_tb.GotFocus += _tb_GotFocus;
_tb.LostFocus += _tb_LostFocus;
_addGrid.Children.Add(_tb);
Grid.SetColumn(_tb, 0);
_search = new Button() { Content = "Search", FontWeight = FontWeights.Bold, FontSize=30 };
_search.Click += _search_Click;
_addGrid.Children.Add(_search);
Grid.SetColumn(_search, 1);
_citySv = new ScrollViewer();
RootGrid.Children.Add(_citySv);
Grid.SetRow(_citySv, 1);
_citySp = new StackPanel();
_citySv.Content = _citySp;
_selectSv = new ScrollViewer() { Height = 300, VerticalAlignment=VerticalAlignment.Top };
RootGrid.Children.Add(_selectSv);
Grid.SetRow(_selectSv, 1);
_selectSp = new StackPanel();
_selectSv.Content = _selectSp;
_selectSv.Visibility = Visibility.Collapsed;
_locating = new Button() { Content = "定位", FontSize=30 };
_locating.Click += _locating_Click;
RootGrid.Children.Add(_locating);
Grid.SetRow(_locating, 2);
}
void _tb_TextChanged(object sender, TextChangedEventArgs e)
{
if (_tb.Text != string.Empty && _tb.Text != "城市名称或缩写")
{
FindCity();
}
}
void _locating_Click(object sender, RoutedEventArgs e)
{
if (LocatingEvent != null)
{
LocatingEvent(this, new EventArgs());
}
}
void _search_Click(object sender, RoutedEventArgs e)
{
FindCity();
_citySv.Visibility = Visibility.Collapsed;
_selectSv.Visibility = Visibility.Visible;
}
private void FindCity()
{
using (CitySqlDataContext db = new CitySqlDataContext(CitySqlDataContext.connectionString))
{
IQueryable<CitySqlItem> q;
bool Chinese = CheckChinese(_tb.Text);
bool Abbreviation = CheckIfAbbreviation(_tb.Text);
_selectSp.Children.Clear();
if (Chinese)
{
q = from c in db.CitySqlItems where c.CityNameCN.StartsWith(_tb.Text) select c;
if (q.Any())
{
AddSelectItems(q);
}
return;
}
if (Abbreviation)
{
q = from c in db.CitySqlItems where c.Abbreviation == _tb.Text select c;
if (q.Any())
{
AddSelectItems(q);
return;
}
}
q = from c in db.CitySqlItems where c.CityNameEN.StartsWith(_tb.Text) select c;
if (q.Any())
{
AddSelectItems(q);
}
}
}
bool CheckIfAbbreviation(string text)
{
if (text.Contains('i'))
{
return false;
}
if (text.Contains('u'))
{
return false;
}
return true;
}
bool CheckChinese(string text)
{
int strLen = text.Length;
int byteLen = System.Text.Encoding.UTF8.GetBytes(text).Length;
if (byteLen > strLen)
{
return true;
}
else
{
return false;
}
}
void AddSelectItems(IQueryable<CitySqlItem> q)
{
foreach (var city in q)
{
TextBlock selectItem = new TextBlock() { Text = city.CityNameCN, FontSize = 40 };
selectItem.Tap+=SelectACity;
_selectSp.Children.Add(selectItem);
}
_citySv.Visibility = Visibility.Collapsed;
_selectSv.Visibility = Visibility.Visible;
}
private void SelectACity(object sender, GestureEventArgs e)
{
TextBlock tb = sender as TextBlock;
using (CitySqlDataContext db = new CitySqlDataContext(CitySqlDataContext.connectionString))
{
IQueryable<CitySqlItem> q = from c in db.CitySqlItems where c.CityNameCN == tb.Text select c;
if (q.Any())
{
CityEventArgs e1 = new CityEventArgs() { CityID = q.First().CityID };
if (AddCityEvent != null)
{
AddCityEvent(this, e1);
}
}
}
_selectSp.Children.Clear();
_selectSv.Visibility = Visibility.Collapsed;
_citySv.Visibility = Visibility.Visible;
}
public void AddCityItem(int cityID)
{
CityItem cityItem = new CityItem(cityID);
_citySp.Children.Add(cityItem);
cityItem.RemoveEvent += cityItem_RemoveEvent;
cityItem.ClickEvent += cityItem_ClickEvent;
cityItem.PinEvent += cityItem_PinEvent;
}
void cityItem_PinEvent(object sender, CityEventArgs e)
{
if (PinCityEvent != null)
{
PinCityEvent(this, e);
}
}
void cityItem_ClickEvent(object sender, CityEventArgs e)
{
if (ClickCityEvent != null)
{
ClickCityEvent(this, e);
}
}
void cityItem_RemoveEvent(object sender, CityEventArgs e)
{
if (RemoveCityEvent != null)
{
RemoveCityEvent(this, e);
}
_citySp.Children.Remove(sender as CityItem);
}
void _tb_LostFocus(object sender, RoutedEventArgs e)
{
if (_tb.Text == String.Empty)
{
_tb.Text = "城市名称或缩写";
}
_selectSv.Visibility = Visibility.Collapsed;
_citySv.Visibility = Visibility.Visible;
}
void _tb_GotFocus(object sender, RoutedEventArgs e)
{
_tb.Text = String.Empty;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sheep : Entity
{
public Animator animator { get; private set; }
public override void Start()
{
base.Start();
animator = GetComponent<Animator>();
}
/**
* Gets converted to a spherical body
*/
public void SwapToSpheric()
{
/* TODO: Añadir animación */
print("Swaping to spheric");
}
/**
* Gets converted back to a normal sheep
*/
public void SwapToNormal()
{
/* TODO: Añadir animación */
print("Swaping to normal");
}
/**
* Starts burning and dies, trying to expand the fire among the rest of the sheep
*/
public void Burn ()
{
this.animator.SetTrigger ("FireFruit");
}
/**
* Gets converted into a wolf
*/
public void MorphIntoWolf()
{
this.animator.SetTrigger ("WolfFruit");
}
/**
* Gets converted into a ball
*/
public void MorphIntoBall ()
{
this.animator.SetTrigger ("BallFruit");
}
/**
* Gets converted into a balloon and starts floating
*/
public void MorphIntoBalloon ()
{
this.animator.SetTrigger ("BalloonFruit");
}
/**
* Removes this sheep from the game
*/
public void Die ()
{
/* We assume that sheep inside of the pen are safe and cannot die */
Instances.GetGameStatus ().sheepRemoved (false);
Destroy (this.gameObject);
}
public void rotatetowardsvel()
{
Quaternion next_rotation = Quaternion.FromToRotation(Vector3.forward, rb.velocity);
// transform.rotation = Quaternion.Slerp(transform.rotation, next_rotation);
}
public override void PlayerInteraction()
{
throw new System.NotImplementedException();
base.PlayerInteraction();
}
public override bool Interact(WorldObject other_object)
{
throw new System.NotImplementedException();
return base.Interact(other_object);
}
}
|
using UnityEngine;
public class PlayerBounds : MonoBehaviour {
//캐릭터가 경계에 도달할 시 적용할 액션을 정의할 BoundsBehavior 선언
public enum BoundsBehavior {
Nothing, //0
Constrain, //1
Kill //2
}
//경계값
public BoxCollider2D Bounds;
public BoundsBehavior Above;
public BoundsBehavior Below;
public BoundsBehavior Left;
public BoundsBehavior Right;
private Vector2 colliderSize;
private Player _player;
private BoxCollider2D _playerBoxCollider2D;
public void Start()
{
Bounds = GameObject.FindWithTag("Player Bounds").GetComponent<BoxCollider2D>();
_player = GetComponent<Player>();
_playerBoxCollider2D = GetComponent<BoxCollider2D>();
colliderSize = new Vector2(
(_playerBoxCollider2D.size.x * Mathf.Abs(transform.localScale.x)/2),
_playerBoxCollider2D.size.y * Mathf.Abs(transform.localScale.y));
}
public void Update() {
if (_player.IsDead)
return;
//var pos = _player.transform.position;
//pos.x = Mathf.Clamp(pos.x, -12.8f+colliderSize.x, 12.8f-colliderSize.x);
//pos.y = Mathf.Clamp(pos.y, -7.2f, 7.2f-colliderSize.y);
//경계값 가장 위보다 높이 있을 시 경계값 아래로 캐릭터를 내려줌.
//if (Above != BoundsBehavior.Nothing && transform.position.y + colliderSize.y > Bounds.bounds.max.y)
if (Above == BoundsBehavior.Constrain)
ApplyBoundsBehavior(Above, new Vector2(transform.position.x, Bounds.bounds.max.y - colliderSize.y));
//경계값 가장 아래 이하로 떨어질 경우 캐릭터를 죽임.
if (Below != BoundsBehavior.Nothing && transform.position.y < Bounds.bounds.min.y)
ApplyBoundsBehavior(Below, new Vector2(transform.position.x, Bounds.bounds.min.y + colliderSize.y));
//경계값 가장 오른쪽보다 더 오른쪽으로 넘어갈 시 경계값보다 왼쪽으로 캐릭터를 옮겨줌.
//if (Right != BoundsBehavior.Nothing && transform.position.x + colliderSize.x > Bounds.bounds.max.x)
// ApplyBoundsBehavior(Right, new Vector2(Bounds.bounds.max.x - colliderSize.x, transform.position.y));
//경계값 가장 왼쪽보다 더 왼쪽으로 넘어갈 시 경계값보다 오른쪽으로 캐릭터를 옮겨줌.
//if (Left != BoundsBehavior.Nothing && transform.position.x - colliderSize.x < Bounds.bounds.min.x)
// ApplyBoundsBehavior(Left, new Vector2(Bounds.bounds.min.x + colliderSize.x, transform.position.y));
}
private void ApplyBoundsBehavior(BoundsBehavior behavior, Vector2 constrainedPosition)
{
if (behavior == BoundsBehavior.Kill)
{
LevelManager.Instance.KillPlayer();
return;
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ModLoader;
using Terraria.GameContent.UI.Elements;
using Terraria.UI;
using System;
using Terraria.ID;
using System.Linq;
using StarlightRiver.Abilities;
using StarlightRiver.Food;
namespace StarlightRiver.GUI
{
public class Cooking : UIState
{
public UIPanel back;
public UIPanel statback;
public IngredientSlot mainSlot;
public IngredientSlot side1Slot;
public IngredientSlot side2Slot;
public IngredientSlot seasoningSlot;
public UIImageButton cookButton;
public static bool visible = false;
public override void OnInitialize()
{
back = new UIPanel();
statback = new UIPanel();
mainSlot = new IngredientSlot();
side1Slot = new IngredientSlot();
side2Slot = new IngredientSlot();
seasoningSlot = new IngredientSlot();
cookButton = new UIImageButton(ModContent.GetTexture("StarlightRiver/GUI/Cook"));
back.Left.Set(-172, 0.5f);
back.Top.Set(-100, 0.5f);
back.Width.Set(144, 0);
back.Height.Set(250, 0);
base.Append(back);
statback.Left.Set(149 - 172, 0.5f);
statback.Top.Set(-100, 0.5f);
statback.Width.Set(166, 0);
statback.Height.Set(100, 0);
base.Append(statback);
mainSlot.Left.Set(34, 0);
mainSlot.Top.Set(31, 0);
mainSlot.Width.Set(64, 0);
mainSlot.Height.Set(64, 0);
mainSlot.OnClick += new MouseEvent(mainSlot.CheckInsertMains);
back.Append(mainSlot);
side1Slot.Left.Set(0, 0);
side1Slot.Top.Set(105, 0);
side1Slot.Width.Set(64, 0);
side1Slot.Height.Set(64, 0);
side1Slot.OnClick += new MouseEvent(side1Slot.CheckInsertSide);
back.Append(side1Slot);
side2Slot.Left.Set(69, 0);
side2Slot.Top.Set(105, 0);
side2Slot.Width.Set(64, 0);
side2Slot.Height.Set(64, 0);
side2Slot.OnClick += new MouseEvent(side2Slot.CheckInsertSide);
back.Append(side2Slot);
seasoningSlot.Left.Set(34, 0);
seasoningSlot.Top.Set(179, 0);
seasoningSlot.Width.Set(64, 0);
seasoningSlot.Height.Set(64, 0);
seasoningSlot.OnClick += new MouseEvent(seasoningSlot.CheckInsertSeasoning);
back.Append(seasoningSlot);
cookButton.Left.Set(149 - 172, 0.5f);
cookButton.Top.Set(5, 0.5f);
cookButton.Width.Set(166, 0);
cookButton.Height.Set(32, 0);
cookButton.OnClick += new MouseEvent(Cook);
base.Append(cookButton);
}
protected override void DrawSelf(SpriteBatch spriteBatch)
{
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
Vector2 origin = back.GetDimensions().Position();
Utils.DrawBorderString(spriteBatch, "Main Course", origin + new Vector2(20, 21), Color.White);
Utils.DrawBorderString(spriteBatch, "Side Courses", origin + new Vector2(18, 95), Color.White);
Utils.DrawBorderString(spriteBatch, "Seasoning", origin + new Vector2(32, 169), Color.White);
float strmod = (seasoningSlot.Item != null) ? (seasoningSlot.Item.modItem as Seasoning).StrengthMod : 1;
string boost1 = (mainSlot.Item != null) ? "+ " + (int)((mainSlot.Item.modItem as MainCourse).Strength * strmod) + (mainSlot.Item.modItem as MainCourse).ITooltip : "";
string boost2 = (side1Slot.Item != null) ? "+ " + (int)((side1Slot.Item.modItem as SideCourse).Strength * strmod) + (side1Slot.Item.modItem as SideCourse).ITooltip : "";
string boost3 = (side2Slot.Item != null) ? "+ " + (int)((side2Slot.Item.modItem as SideCourse).Strength * strmod) + (side2Slot.Item.modItem as SideCourse).ITooltip : "";
string durboost = "Duration: " + (300 + ((seasoningSlot.Item != null) ? (seasoningSlot.Item.modItem as Seasoning).Modifier / 60 : 0)) + " Seconds";
string fill = (mainSlot.Item != null) ? ("Fullness: " + (((mainSlot.Item.modItem as MainCourse).Fill) +
((side1Slot.Item != null) ? (side1Slot.Item.modItem as SideCourse).Fill : 0) +
((side2Slot.Item != null) ? (side2Slot.Item.modItem as SideCourse).Fill : 0) +
((seasoningSlot.Item != null) ? (seasoningSlot.Item.modItem as Seasoning).Fill : 0)
)/60) + " Seconds" : "";
if (mainSlot.Item != null)
{
Utils.DrawBorderString(spriteBatch, boost1, origin + new Vector2(155, 10), new Color(255, 220, 140), 0.75f);
Utils.DrawBorderString(spriteBatch, boost2, origin + new Vector2(155, 25), new Color(140, 255, 140), 0.75f);
Utils.DrawBorderString(spriteBatch, boost3, origin + new Vector2(155, 40), new Color(140, 255, 140), 0.75f);
Utils.DrawBorderString(spriteBatch, durboost, origin + new Vector2(155, 65), (seasoningSlot.Item != null) ? new Color(140, 200, 255) : Color.White, 0.75f);
Utils.DrawBorderString(spriteBatch, fill, origin + new Vector2(155, 80), new Color(255, 163, 153), 0.75f);
}
spriteBatch.Draw(ModContent.GetTexture("StarlightRiver/GUI/Line"), new Rectangle((int)origin.X + 154, (int)origin.Y + 60, 156, 4), Color.White * 0.25f);
Utils.DrawBorderString(spriteBatch, "Prepare", origin + new Vector2(190, 106), Color.White, 1.1f);
Recalculate();
}
public void Cook(UIMouseEvent evt, UIElement listeningElement)
{
if (mainSlot.Item != null)
{
Player player = Main.LocalPlayer;
int item = Item.NewItem(player.Center, ModContent.ItemType<Meal>());
Meal meal = Main.item[item].modItem as Meal;
meal.mains = mainSlot.Item.modItem as MainCourse; mainSlot.Item = null;
if (side1Slot.Item != null) { meal.side1 = side1Slot.Item.modItem as SideCourse; side1Slot.Item = null; }
if (side2Slot.Item != null) { meal.side2 = side2Slot.Item.modItem as SideCourse; side2Slot.Item = null; }
if (seasoningSlot.Item != null) { meal.seasoning = seasoningSlot.Item.modItem as Seasoning; seasoningSlot.Item = null; }
}
}
}
public class IngredientSlot : UIElement
{
public Item Item;
protected override void DrawSelf(SpriteBatch spriteBatch)
{
CalculatedStyle dimensions = GetDimensions();
spriteBatch.Draw(Main.inventoryBackTexture, dimensions.Position(), Color.White * 0.6f);
if (Item != null && Item.modItem != null)
{
Texture2D tex = ModContent.GetTexture(Item.modItem.Texture);
spriteBatch.Draw(tex, dimensions.Center() - (tex.Size() * 0.75f), Color.White);
}
}
public void CheckInsertMains(UIMouseEvent evt, UIElement listeningElement)
{
Player player = Main.LocalPlayer;
if (player.HeldItem.modItem != null && player.HeldItem.modItem is MainCourse && Item == null)
{
Item = player.HeldItem.Clone();
Item.stack = 1;
if (player.HeldItem.stack > 1) { player.HeldItem.stack--; } else { player.HeldItem.TurnToAir(); }
}
else if (Item != null)
{
for (int i = 0; i < 400; i++)
{
if (!Main.item[i].active)
{
Main.item[i] = Item;
Main.item[i].position = player.Center;
break;
}
}
Item = null;
}
}
public void CheckInsertSide(UIMouseEvent evt, UIElement listeningElement)
{
Player player = Main.LocalPlayer;
if (player.HeldItem.modItem != null && player.HeldItem.modItem is SideCourse && Item == null)
{
Item = player.HeldItem.Clone();
Item.stack = 1;
if (player.HeldItem.stack > 1) { player.HeldItem.stack--; } else { player.HeldItem.TurnToAir(); }
}
else if (Item != null)
{
for (int i = 0; i < 400; i++)
{
if (!Main.item[i].active)
{
Main.item[i] = Item;
Main.item[i].position = player.Center;
break;
}
}
Item = null;
}
}
public void CheckInsertSeasoning(UIMouseEvent evt, UIElement listeningElement)
{
Player player = Main.LocalPlayer;
if (player.HeldItem.modItem != null && player.HeldItem.modItem is Seasoning && Item == null)
{
Item = player.HeldItem.Clone();
Item.stack = 1;
if (player.HeldItem.stack > 1) { player.HeldItem.stack--; } else { player.HeldItem.TurnToAir(); }
}
else if (Item != null)
{
for (int i = 0; i < 400; i++)
{
if (!Main.item[i].active)
{
Main.item[i] = Item;
Main.item[i].position = player.Center;
break;
}
}
Item = null;
}
}
}
}
|
/**
* Author: János de Vries
* Date: Sep. 2014
* Student Number: 208418
**/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
namespace ThreadCollor
{
/// <summary>
/// The MainForm class which extends the basic Form
/// </summary>
public partial class MainForm : Form
{
/**
* The Variable declarations for this class.
**/
#region Variable declarations
//The thread manager which has control over all the ColorCalculators (workers)
ThreadManager threadManager;
//The file manager which has control over all the (image) files
FileManager fileManager;
//The current time when the threads are activated
DateTime startingTime;
//A flag which keeps track remembers if ListView column width changes should be saved
private bool widthChangeFlag = false;
//The number of tasks when starting
double imagesWaitingBefore = -1;
#endregion
/// <summary>
/// The constructor from the MainForm class
/// </summary>
public MainForm()
{
//Initialize the FileManager
fileManager = new FileManager();
//Initialize the ThreadManager
threadManager = new ThreadManager();
//Add a AllThreadsDone listener to the ThreadManager
threadManager.allThreadsDone += new ThreadManager.AllThreadsDone(threadsDone);
//Initialize the form
InitializeComponent();
////Prioritize the WinForm thread above the worker threads
//Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
}
/// <summary>
/// This method updates the listView_overview with data contained in the FileManager
/// </summary>
private void updateListView()
{
//Signal the listView that the update has launched
listView_overview.BeginUpdate();
//Clear the old data
listView_overview.Items.Clear();
//For every file in the FileManager
for(int i = 0; i < fileManager.Count; i++)
{
//Grab the current entry
FileEntry entry = fileManager[i];
//Create a new ListViewItem (a row)
ListViewItem newEntry = new ListViewItem(new String[listView_overview.Columns.Count]);
//Allow individual cells to apply their own style, This is used for the Color cell
newEntry.UseItemStyleForSubItems = false;
//Fill all known information into the cells
newEntry.SubItems[0].Text = entry.getFileName();
newEntry.SubItems[1].Text = entry.getFilePath();
newEntry.SubItems[2].Text = entry.getFileSize();
newEntry.SubItems[3].Text = entry.getStatus();
newEntry.SubItems[4].Text = entry.getRed();
newEntry.SubItems[5].Text = entry.getGreen();
newEntry.SubItems[6].Text = entry.getBlue();
//Grab the hex value from the entry
string hexValue = entry.getHex();
newEntry.SubItems[7].Text = hexValue;
//If the hexValue is not "-" (representing null)
if(hexValue != "-")
{
//Color in the color cell
newEntry.SubItems[8].BackColor = ColorTranslator.FromHtml("#" + hexValue);
//Remove the placeholder text ("-")
newEntry.SubItems[8].Text = String.Empty;
}
//If the hex value is unknown
else
{
//Fill the cell with placeholder text
newEntry.SubItems[8].Text = "-";
}
//Add the entry to the ListView
listView_overview.Items.Add(newEntry);
//Pass the position in the ListView to the individual entry
entry.setEntryNumber(i);
}
//Signal that all the new data has been added
listView_overview.EndUpdate();
}
/// <summary>
/// Opens a FileDialog in which the user can select their image files
/// </summary>
/// <returns>A list of selected files</returns>
private List<String> askForFiles()
{
//Create an instance of OpenFileDialog
OpenFileDialog openFileDialog = new OpenFileDialog();
//Filter to these file extensions
openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png | All Files (*.*)|*.*";
//Select Image Files on default
openFileDialog.FilterIndex = 1;
//Allows the user to select multiple files
openFileDialog.Multiselect = true;
//Show the OpenFileDialog so the user can select files
openFileDialog.ShowDialog();
//Put the dialog results into a list
//This list will contain the selected file paths
return openFileDialog.FileNames.ToList();
}
/// <summary>
/// This method saves the time at which the threads start running
/// </summary>
private void setStartTime()
{
//Set the time at which the threads start running
startingTime = DateTime.Now;
//Set the number of images waiting at the moment the threads start
this.imagesWaitingBefore = fileManager.FilesWaiting;
}
/// <summary>
/// This method returns the total runtime since setTime has been called
/// If setTime hasn't been called it will return zero
/// </summary>
/// <returns>The total run time of all the threads</returns>
private TimeSpan reportTimeSpent()
{
//If the starting time has been set
if(startingTime != DateTime.MinValue)
{
//Calculate the total run time
TimeSpan total = DateTime.Now - startingTime;
//Return it
return total;
}
//If not return zero
return TimeSpan.Zero;
}
/// <summary>
/// Start the calculations
/// </summary>
private void start()
{
//If there are files waiting to be calculated
if(fileManager.FilesWaiting > 0)
{
//Lock the controls
button_start.Text = "Stop";
button_add.Enabled = false;
button_remove.Enabled = false;
comboBox_cores.Enabled = false;
numericUpDown_threads.Enabled = false;
//Set the time at which the threads have started running
setStartTime();
//Send the threads per image to the file manager
fileManager.setThreadsPerImage((int)numericUpDown_tpi.Value);
//Generate the task list (queue)
fileManager.createQueue();
//Tell the ThreadManager to start the threads
threadManager.startThreads(fileManager, listView_overview,(int)numericUpDown_threads.Value, Convert.ToInt32(comboBox_cores.Text));
}
}
/// <summary>
/// Stop the calculations and report statistics
/// </summary>
private void stop()
{
//If there are still threads running
if(threadManager.ThreadsRunning)
{
//Tell the file manager to stop handing out tasks
fileManager.setStopFlag();
//Disable the start/stop button
button_start.Enabled = false;
}
//Else if there are no threads running
else
{
//Get the run time
double runTime = reportTimeSpent().TotalSeconds;
//Unlock the controls
button_start.Text = "Start";
button_add.Enabled = true;
button_remove.Enabled = true;
comboBox_cores.Enabled = true;
numericUpDown_threads.Enabled = true;
//Allow the FileManager to hand out tasks
fileManager.releaseStopFlag();
//If there are files waiting
if(fileManager.FilesWaiting > 0)
{
//Re-enable the start button
button_start.Enabled = true;
}
else
{
button_start.Enabled = false;
}
//Calculate the number of tasks completed
double tasksCompleted = (imagesWaitingBefore - fileManager.FilesWaiting);
//Calculate the time it used, as strings
string totalTime = Math.Round(runTime, 2).ToString();
string timePerImage = Math.Round(runTime / tasksCompleted , 2).ToString();
//Display a MessageBox which shows the total run time, the time per image, number of pixels and pixels per second
MessageBox.Show(String.Format("Total running time is {0} seconds. \nThat's {1} seconds for each image.\n\nCalculated ~{2} pixels.\n{3} pixels per second.", totalTime, timePerImage, fileManager.getTotalPixelsDone(), (fileManager.getTotalPixelsDone()/totalTime.Length).ToString()), "Run time report");
}
}
/// <summary>
/// A method that is trigged when all the threads have completed their work
/// This method is triggered by an event in ThreadManager
/// </summary>
private void threadsDone()
{
//Call the stop method
stop();
}
/**
* All the click events the Windows form uses are within this region.
**/
#region Click events
/// <summary>
/// This method is bound to a click event on the add button
/// </summary
private void button_add_Click(object sender, EventArgs e)
{
//Ask the user which files to add
List<string> selectedFiles = askForFiles();
//If there are files selected
if(selectedFiles.Count > 0)
{
//Send the files to the FileManager
fileManager.add(selectedFiles);
//Enable the start button
button_start.Enabled = true;
//Update the ListView
updateListView();
}
}
/// <summary>
/// When the remove button has been clicked the highlighted files will be removed
/// </summary>
private void button_remove_Click(object sender, EventArgs e)
{
//For every item in the ListView
for (int i = listView_overview.Items.Count-1; i >= 0; i--)
{
//If the item has been selected
if (listView_overview.Items[i].Selected)
{
//Remove the item at location i in the FileManager
fileManager.removeAt(i);
}
//Re-create the queue
fileManager.createQueue();
}
//Update the ListView to remove the items
updateListView();
//If every item has been deleted
if(fileManager.FilesWaiting < 1)
{
//Disable the start button
button_start.Enabled = false;
}
}
/// <summary>
/// Turn the start button in to a start/stop toggle
/// </summary>
private void button_start_Click(object sender, EventArgs e)
{
if (button_start.Text == "Start")
{
start();
}
else
{
stop();
}
}
/// <summary>
/// When one of the ListView columns is clicked sort it
/// </summary>
private void listView_overview_ColumnClick(object sender, ColumnClickEventArgs e)
{
//Grab the index of the selected column
Int32 colIndex = Convert.ToInt32(e.Column.ToString());
//Call the sort method within the FileManager
fileManager.sort(listView_overview.Columns[colIndex].Text);
//Update the ListView with the sorted information
updateListView();
}
#endregion
/**
* These methods preserve the user settings. For example column width and form size.
**/
#region Preserving user settings
/// <summary>
/// This method is called on load and runs start-up tasks.
/// </summary>
private void MainForm_Load(object sender, EventArgs e)
{
// If the user previously changed the window size
if (Properties.Settings.Default.WindowSize != null)
{
//Restore it to what it used to be
this.Size = Properties.Settings.Default.WindowSize;
}
//If the user previously changed to column widths
if (Properties.Settings.Default.ColumnWidths != null)
{
//retrieve the old settings
int[] columnWidths = Properties.Settings.Default.ColumnWidths.Split(',').Select(s => Int32.Parse(s)).ToArray();
int i = 0;
//and for each column
foreach (ColumnHeader column in listView_overview.Columns)
{
//restore it
column.Width = columnWidths[i];
i++;
}
}
//Set the max number of (logical) processors
comboBox_cores.Items.Clear();
for (int i = 1; i <= Environment.ProcessorCount; i++)
{
//Add an option for each number processors
comboBox_cores.SelectedIndex = comboBox_cores.Items.Add(i);
}
//Restore the number of threads
numericUpDown_threads.Value = Properties.Settings.Default.Threads;
//Only column width changes after the form load event should be saved
this.widthChangeFlag = true;
}
/// <summary>
/// When the form's size changes, save it
/// </summary>
private void MainForm_SizeChanged(object sender, EventArgs e)
{
Properties.Settings.Default.WindowSize = this.Size;
Properties.Settings.Default.Save();
}
/// <summary>
/// When the listView's column with changes, save it
/// </summary>
private void listView_overview_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
{
//If the form has loaded start recording changes in width
if(this.widthChangeFlag)
{
int[] columnWidths = new int[listView_overview.Columns.Count];
int i = 0;
//for each column header
foreach (ColumnHeader column in listView_overview.Columns)
{
//save the width in an int array
columnWidths[i] = column.Width;
i++;
}
//convert the int array into a string
Properties.Settings.Default.ColumnWidths = String.Join(",", columnWidths);
//save it
Properties.Settings.Default.Save();
}
}
/// <summary>
/// Save the number of threads if the user changes it's value.
/// </summary>
private void numericUpDown_threads_ValueChanged(object sender, EventArgs e)
{
numericUpDown_tpi.Maximum = numericUpDown_threads.Value;
Properties.Settings.Default.Threads = (int)numericUpDown_threads.Value;
Properties.Settings.Default.Save();
}
/// <summary>
/// Save the number of cores if the user changes it's value.
/// </summary>
private void comboBox_cores_TextChanged(object sender, EventArgs e)
{
//Properties.Settings.Default.Cores = Convert.ToInt32(comboBox_cores.Items[0]);
//Properties.Settings.Default.Save();
}
#endregion
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;
using MVC.Core.Attributes;
using MVC.Core.Extensions;
using MVC4.Sample.Common.Entities;
using MVC4.Sample.Common.ViewModels.Home;
namespace MVC4.Sample.Web.Controllers.Home
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
var viewModel = new HomeViewModel
{
Welcome = "Welcome to HomePage",
Welcome2 = "Welcome2 to HomePage",
UserListViewModel = new UserListViewModel
{
Users = new List<UserInfo>(),
Text = "dsafasdfasdfsd"
},
};
viewModel.UserListViewModel.Users.Add(new UserInfo
{
UserName = "Gia Le"
});
viewModel.UserListViewModel.Users.Add(new UserInfo
{
UserName = "Khoa Tran"
});
viewModel.UserListViewModel.Users.Add(new UserInfo
{
UserName = "Duy Truong"
});
viewModel.UserListViewModel.Users.Add(new UserInfo
{
UserName = "Hai Nguyen"
});
return View(viewModel);
}
[HttpPost]
[ActionCommand(Name = "SaveWholePage")]
public ActionResult Index(HomeViewModel viewModel)
{
ModelState.Clear();
//Make wrong data
viewModel.Welcome = string.Empty;
viewModel.Welcome2 = string.Empty;
viewModel.UserListViewModel.Text = string.Empty;
viewModel.UserListViewModel.Users[0].UserName = string.Empty;
viewModel.UserListViewModel.Users[1].UserName = string.Empty;
var isValid = ModelState.IsModelValid(viewModel /*Validate All Groups*/);
//ModelState.IsModelValid(viewModel, "Users Welcome") => Validate Groups: Users & Welcome
if (isValid)
{
//TODO: DO BUSINESS HERE
}
return View(viewModel);
}
[HttpPost]
[ActionCommand(Name = "ChangeWelcomeText")]
public ActionResult ChangeWelcomeText(HomeViewModel viewModel)
{
ModelState.Clear();
//Make wrong data
viewModel.Welcome = string.Empty;
viewModel.Welcome2 = string.Empty;
viewModel.UserListViewModel.Text = string.Empty;
viewModel.UserListViewModel.Users[0].UserName = string.Empty;
viewModel.UserListViewModel.Users[1].UserName = string.Empty;
ModelState.IsModelValid(viewModel, "Welcome" /*Validate only Welcome Groups*/);
return View("Index", viewModel);
}
[HttpPost]
[ActionCommand(Name = "SaveUsers")]
public ActionResult SaveUsers(HomeViewModel viewModel)
{
ModelState.Clear();
//Make wrong data
viewModel.Welcome = string.Empty;
viewModel.UserListViewModel.Users[0].UserName = "dafsadfsdfsafsadfsadfsadfsadf";
viewModel.UserListViewModel.Users[1].UserName = "dafsadfsdfsafsadfsadfsadfsadf";
//Validate
var isValid = ModelState.IsModelValid(viewModel, "Users" /*Validate Group: Users*/);
if (isValid)
{
//Do business
}
return View("Index", viewModel);
}
}
}
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Ach.Fulfillment.Migrations")]
[assembly: AssemblyDescription("")]
[assembly: Guid("04bfffe4-c8c5-45c6-bc2d-5c9662a444fb")]
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.SomeAnimals
{
class Dog : IAnimal, ISound
{
public string name { get; set; }
public string sex { get; set; }
public double age { get; set; }
public string owner { get; set; }
public string personalId { get; set; }
public string color { get; set; }
public string breed { get; set; }
public string MakeNoise()
{
string notHappy = "Grrrr!";
return notHappy;
}
public void GoForAWalk()
{
Console.WriteLine("Dog is happy when is a on a walk.");
}
public void BeHungry()
{
Console.WriteLine("Your dog is hungry!");
}
public string SayBau()
{
string bau = "Bau, Bau!";
return bau;
}
public void WagTail()
{
Console.WriteLine("Tail is wagging. Your dog is happy.");
}
public Dog()
{
}
public Dog(string name, double age)
{
this.name = name;
this.age = age;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SpaceHosting.Index.Sparnn.Distances;
using MSparseVector = MathNet.Numerics.LinearAlgebra.Double.SparseVector;
namespace SpaceHosting.Index.Sparnn.Clusters
{
internal class RootClusterIndex<TRecord> : BaseClusterIndex<TRecord>
where TRecord : notnull
{
private readonly IMatrixMetricSearchSpaceFactory matrixMetricSearchSpaceFactory;
private IClusterIndex<TRecord> root = null!;
public RootClusterIndex(
Random random,
IList<MSparseVector> featureVectors,
TRecord[] recordsData,
IMatrixMetricSearchSpaceFactory matrixMetricSearchSpaceFactory,
int desiredClusterSize)
: base(random, desiredClusterSize)
{
this.matrixMetricSearchSpaceFactory = matrixMetricSearchSpaceFactory;
Init(featureVectors, recordsData);
}
public override bool IsOverflowed => false;
public override async Task InsertAsync(IList<MSparseVector> featureVectors, TRecord[] records)
{
if (!root.IsOverflowed)
{
await root.InsertAsync(featureVectors, records).ConfigureAwait(false);
return;
}
Reindex(featureVectors, records);
}
public override (IList<MSparseVector> featureVectors, IList<TRecord> records) GetChildData()
{
return root.GetChildData();
}
public override Task DeleteAsync(IList<TRecord> recordsToBeDeleted)
{
return root.DeleteAsync(recordsToBeDeleted);
}
protected override Task<IEnumerable<NearestSearchResult<TRecord>[]>> SearchInternalAsync(IList<MSparseVector> featureVectors, int resultsNumber, int clustersSearchNumber)
{
return root.SearchAsync(featureVectors, resultsNumber, clustersSearchNumber);
}
protected override void Init(IList<MSparseVector> featureVectors, TRecord[] recordsData)
{
root = ClusterIndexFactory.Create(random, featureVectors, recordsData, matrixMetricSearchSpaceFactory, desiredClusterSize, this);
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextManager : MonoBehaviour
{
[SerializeField] private Text textPlayer0HP = null;
[SerializeField] private Text textPlayer1HP = null;
[SerializeField] private Text[] textTower0HP = new Text[(int)EnumBoardLength.MaxBoardLengthY];
[SerializeField] private Text[] textTower1HP = new Text[(int)EnumBoardLength.MaxBoardLengthY];
[SerializeField] private SpriteRenderer[] spriteRenderers = new SpriteRenderer[(int)EnumBoardLength.MaxBoardLengthY];
[SerializeField] private SpriteRenderer[] spriteRenderers1 = new SpriteRenderer[(int)EnumBoardLength.MaxBoardLengthY];
[SerializeField] private Sprite spriteBlack = null;
[SerializeField] private Image ImagePanel0 = null;
[SerializeField] private Image ImagePanel1 = null;
[SerializeField] private Text TextTurnNum = null;
public void SetText(int health, bool player)
{
if (player)
{
textPlayer0HP.text = "HP: " + health.ToString();
}
else if (!player)
{
textPlayer1HP.text = "HP: " + health.ToString();
}
}
public void SetTowerHPText(int health, bool player, int laneY)
{
if (player)
{
textTower0HP[laneY].text = "HP: " + health.ToString();
if (health <= 0)
{
textTower0HP[laneY].text = "";
spriteRenderers[laneY].sprite = spriteBlack;
}
}
else if (!player)
{
textTower1HP[laneY].text = "HP: " + health.ToString();
if (health <= 0)
{
textTower1HP[laneY].text = "";
spriteRenderers1[laneY].sprite = spriteBlack;
}
}
}
private Color colorOn = new Color32(255, 255, 255, 255);
private Color colorOff = new Color32(255, 255, 255, 0);
public void SetPanel(bool turn)
{
if (turn)
{
ImagePanel0.GetComponent<Image>().color = colorOff;
ImagePanel1.GetComponent<Image>().color = colorOn;
}
else if (!turn)
{
ImagePanel0.GetComponent<Image>().color = colorOn;
ImagePanel1.GetComponent<Image>().color = colorOff;
}
}
public void SetTurnNum(int value)
{
TextTurnNum.text = "Dragon " + (5 - value).ToString();
}
[SerializeField] private GameObject[] dragonIcons = new GameObject[(int)EnumMonster.Elder + 1];
public void CreateDragonIconinPanel(int dragonID, bool player)
{
var gameobject = Instantiate(dragonIcons[dragonID]);
if (player)
{
gameobject.transform.SetParent(ImagePanel1.transform);
}
else if (!player)
{
gameobject.transform.SetParent(ImagePanel0.transform);
}
gameobject.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
}
} |
using System;
namespace Zadanie_4
{
class Program
{
static int[] SortujBąbelkowo(int[] tablica)
{
int p;
int porówniania = 0, zamiany = 0; int i = 0;
for (int n = 0; n < tablica.Length; n++)
{
for (int k = i + 1; k < tablica.Length; k++)
{
porówniania++;
if (tablica[i] > tablica[k]) { p = tablica[i]; tablica[i] = tablica[k]; tablica[k] = p; zamiany++; }
i++;
}
i = 0;
}
Console.WriteLine("Porównania: {0}, Zamiany: {1}", porówniania, zamiany);
return tablica;
}
//złożoność czasowa n^2
static int[] SortujBąbelkowoLepiej(int[] tablica)
{
int p;
int porówniania = 0, zamiany = 0, zamiany1, i= 0;
for (int n = 0; n < tablica.Length; n++)
{
zamiany1 = 0;
for (int k = i + 1; k < tablica.Length; k++)
{
porówniania++;
if (tablica[i] > tablica[k]) { p = tablica[i]; tablica[i] = tablica[k]; tablica[k] = p; zamiany++; zamiany1++; }
i++;
}
if (zamiany1 == 0) break;
porówniania++;
i =0;
}
Console.WriteLine("Porównania: {0}, Zamiany: {1}", porówniania, zamiany);
return tablica;
}
static void Wyświetl(int[] tab)
{
for (int i = 0; i < tab.Length - 1; i++)
{
Console.Write(tab[i] + ",");
}
Console.Write(tab[tab.Length - 1] + "\n");
}
static void Main(string[] args)
{
int[] posortowany = { 1, 2, 3, 4, 5, 6, 7, 77, 234 };
int[] malejący = { 1342, 1243, 23, 9, 7, 4, 3, 1 };
int[] losowy = { 1, 6, 3, 6, 4, 6, 8, 2, 4, 12 };
Wyświetl(SortujBąbelkowo(posortowany));
Wyświetl(SortujBąbelkowo(malejący));
Wyświetl(SortujBąbelkowo(losowy));
Console.WriteLine();
posortowany = new int[]{ 1, 2, 3, 4, 5, 6, 7, 77, 234 };
malejący = new int[]{ 1342, 1243, 23, 9, 7, 4, 3, 1 };
losowy = new int[]{ 1, 6, 3, 6, 4, 6, 8, 2, 4, 12 };
Wyświetl(SortujBąbelkowoLepiej(posortowany));
Wyświetl(SortujBąbelkowoLepiej(malejący));
Wyświetl(SortujBąbelkowoLepiej(losowy));
Console.ReadKey();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Author: Jae Son
//Moves player along with Moving Platforms
public class CheckMovingCollision : MonoBehaviour {
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "MovingPlatform")
{
transform.parent = other.transform;
}
}
void OnCollisionExit(Collision other)
{
if (other.transform.tag == "MovingPlatform")
{
transform.parent = null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using System;
using UnityEditor.Presets;
using UnityEditor;
//[CreateAssetMenu(fileName = "DataOfComponent_", menuName = "Create Data Game/ Data Of Component")]
[InitializeOnLoad]
public class DataComponents : ScriptableObject
{
public List<DataComponent> allDataComponents;
public void AddNewData(Component new_Component , Preset new_infoComponent)
{
(bool isExists, int index) isExistsComponent = CheckDataComponent(new_Component);
if (isExistsComponent.isExists)
{
allDataComponents[isExistsComponent.index] = new DataComponent { m_Component = new_Component, infoComponent = new_infoComponent };
}
else
{
allDataComponents.Add(new DataComponent { m_Component = new_Component, infoComponent = new_infoComponent });
}
}
public (bool isExists, int index) CheckDataComponent(Component new_Component)
{
for (int i = 0; i < allDataComponents.Count; i++)
{
if (new_Component.Equals(allDataComponents[i].m_Component)) return (true, i);
}
return (false, -1);
}
public void ReomveInfoComponent(Component new_Component)
{
(bool isExists, int index) isExistsComponent = CheckDataComponent(new_Component);
if (isExistsComponent.isExists)
{
allDataComponents.RemoveAt(isExistsComponent.index);
}
}
}
[System.Serializable]
public struct DataComponent
{
public Component m_Component;
public Preset infoComponent;
} |
using eCommerceSE.Cliente;
using eCommerceSE.Model;
using System;
using System.Configuration;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Enviosbase.Producto
{
public partial class ProductoEdit : System.Web.UI.Page
{
string llave = ConfigurationManager.AppSettings["Usuario"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IdUsuario"] == null)
{
Response.Redirect("/Login.aspx");
}
if (!Page.IsPostBack)
{
cbIdCategoria.DataSource = new CategoriaProductoCliente(llave).GetAll();
cbIdCategoria.DataTextField = "Nombre";
cbIdCategoria.DataValueField = "Id";
cbIdCategoria.DataBind();
cbIdCategoria.Items.Insert(0, new ListItem("[Seleccione]", ""));
/*this.cbIdEstablecimiento.DataSource = new EstablecimientoCliente(llave).GetAll();
this.cbIdEstablecimiento.DataTextField = "Nombre";
this.cbIdEstablecimiento.DataValueField = "Id";
this.cbIdEstablecimiento.DataBind();
this.cbIdEstablecimiento.Items.Insert(0, new ListItem("[Seleccione]", ""));*/
if (Request.QueryString["Id"] != null)
{
int id = int.Parse(Request.QueryString["Id"]);
ProductoModel obj = new ProductoCliente(llave).GetById(id);
lbId.Text = obj.Id.ToString();
txtNombre.Text = obj.Nombre;
txtDescripcion.Text = obj.Descripcion;
txtPresentacion.Text = obj.Presentacion;
txtPrecio.Text = obj.Precio == null ? null : obj.Precio.ToString();
hdnFileImage.Value = obj.Imagen;
hdEstado.Value = obj.Estado.ToString();
//this.txtIdUsuarioRegistro.Text = obj.IdUsuarioRegistro == null ? null : obj.IdUsuarioRegistro.ToString();
cbIdCategoria.SelectedValue = obj.IdCategoria == null ? null : obj.IdCategoria.ToString();
txtCodigoSKU.Text = obj.CodigoSKU;
hdIdEstablecimiento.Value = obj.IdEstablecimiento == null ? null : obj.IdEstablecimiento.ToString();
txtPrecioPromocion.Text = obj.PrecioPromocion == null ? null : obj.PrecioPromocion.ToString();
txtPorcentajePromocion.Text = obj.PorcentajePromocion == null ? null : obj.PorcentajePromocion.ToString();
txtCodigo.Text = obj.Codigo;
}
else
{
hdEstado.Value = true.ToString();
hdIdEstablecimiento.Value = (Session["IdEstablecimiento"] != null) ? Session["IdEstablecimiento"].ToString() : "0";
}
if (Request.QueryString["View"] == "0")
{
Business.Utils.DisableForm(Controls);
btnCancel.Enabled = true;
}
}
}
public bool validarTamaño(int tamaño)
{
if (tamaño > int.Parse(System.Configuration.ConfigurationManager.AppSettings["tamañoArchivos"].ToString())) return false; else return true;
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
ProductoModel obj;
obj = new ProductoModel();
string filePath = "";
if (fnImagen.HasFile)
{
if (validarTamaño(fnImagen.FileBytes.Length))
{
filePath = "/ImagenesProductos/" + Session["IdEstablecimiento"].ToString() + '/' + fnImagen.FileName;
string rutaInterna = Server.MapPath("/Archivos" + filePath);
if (!Directory.Exists(Path.GetDirectoryName(rutaInterna)))
Directory.CreateDirectory(Path.GetDirectoryName(rutaInterna));
fnImagen.SaveAs(rutaInterna);
obj.Imagen = ConfigurationManager.AppSettings["RutaArchivos"].ToString() + filePath;
}
else
{
ltScripts.Text = Business.Utils.MessageBox("Atención", "El tamaño de la foto supera los " + System.Configuration.ConfigurationManager.AppSettings["tamañoArchivosReal"].ToString() + " kb", null, "error");
return;
}
}
else
{
filePath = hdnFileImage.Value;
obj.Imagen = filePath;
}
ProductoCliente business = new ProductoCliente(llave);
obj.Nombre = txtNombre.Text;
obj.Descripcion = txtDescripcion.Text;
obj.Presentacion = txtPresentacion.Text;
obj.Precio = double.Parse(txtPrecio.Text);
obj.Estado = bool.Parse(hdEstado.Value);
obj.IdUsuarioRegistro = int.Parse(Session["IdUsuario"].ToString());
obj.IdCategoria = int.Parse(cbIdCategoria.SelectedValue);
obj.CodigoSKU = txtCodigoSKU.Text;
obj.IdEstablecimiento = int.Parse(hdIdEstablecimiento.Value);
obj.PrecioPromocion = double.Parse(txtPrecioPromocion.Text);
obj.PorcentajePromocion = double.Parse(txtPorcentajePromocion.Text);
obj.Codigo = txtCodigo.Text;
if (Request.QueryString["Id"] != null)
{
obj.Id = int.Parse(Request.QueryString["Id"]);
business.Update(obj);
}
else
{
obj = business.Create(obj);
if (obj.Id == 0)
{
ltScripts.Text = Business.Utils.MessageBox("Atención", "Hay un producto creado con la misma información, por favor verifique la información e intente nuevamente", null, "error");
return;
}
}
ltScripts.Text = Business.Utils.MessageBox("Atención", "El registro ha sido guardado exitósamente", "ProductoList.aspx", "success");
}
catch (Exception)
{
ltScripts.Text = Business.Utils.MessageBox("Atención", "No pudo ser guardado el registro, por favor verifique su información e intente nuevamente", null, "error");
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("ProductoList.aspx");
}
}
}
|
using BlazorShared.Models.Appointment;
using FrontDesk.Core.Aggregates;
namespace FrontDesk.Core.Interfaces
{
public interface IAppointmentDTORepository
{
AppointmentDto GetFromAppointment(Appointment appointment);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _01.Tower_of_Hanoi
{
class TowerOfHanoi
{
static int numberOfDisks = 5;
static int stepsTaken = 0;
static Stack<int> sourceRod = new Stack<int>(Enumerable.Range(1, numberOfDisks).Reverse());
static Stack<int> destinationRod = new Stack<int>();
static Stack<int> spareRod = new Stack<int>();
static void Main()
{
//Console.Write("N = ");
//numberOfDisks = int.Parse(Console.ReadLine());
sourceRod = new Stack<int>(Enumerable.Range(1, numberOfDisks).Reverse());
PrintRods();
MoveDisks(numberOfDisks, sourceRod, destinationRod, spareRod);
}
static void MoveDisks(int bottomDisk, Stack<int> source, Stack<int> destination, Stack<int> spare)
{
if (bottomDisk == 1)
{
stepsTaken++;
destination.Push(source.Pop());
Console.WriteLine($"Step {stepsTaken}: moved disk {destination.Peek()}");
PrintRods();
}
else
{
MoveDisks(bottomDisk - 1, source, spare, destination);
// only way i found that works
stepsTaken++;
destination.Push(source.Pop());
Console.WriteLine($"Step {stepsTaken}: moved disk {destination.Peek()}");
PrintRods();
MoveDisks(bottomDisk - 1, spare, destination, source);
}
}
static void PrintRods()
{
Console.WriteLine("Source: {0}", string.Join(", ", sourceRod.Reverse()));
Console.WriteLine("Destination: {0}", string.Join(", ", destinationRod.Reverse()));
Console.WriteLine("Spare: {0}", string.Join(", ", spareRod.Reverse()));
Console.WriteLine();
}
}
} |
using System.Threading;
using System.Threading.Tasks;
using CQRS.MediatR.Query;
using MimeKit;
namespace Scheduler.MailService.Queries
{
public class MessageConverterHandler: IQueryHandler<ConvertOrderToMessage, MimeMessage>
{
public async Task<MimeMessage> Handle(ConvertOrderToMessage request, CancellationToken cancellationToken)
{
var order = request.Order;
var message = new MimeMessage();
message.To.Add(MailboxAddress.Parse(order.Email));
message.Subject = $"Order from the best company! {order.NrZamowienia}";
message.Body = new BodyBuilder()
{
TextBody = $"Dear {order.Imie} {order.Nazwisko} your order number: {order.NumerPaczki}" +
$" is on way to {order.AdresZamowienia}, thanks for buying."
}
.ToMessageBody();
return message;
}
}
}
|
using Common;
using Common.Attributes;
using Common.EfSearchModel.Model;
using IBLLService;
using MODEL.ActionModel;
using MODEL.DataTableModel;
using MODEL.ViewModel;
using ShengUI.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace ShengUI.Logic.Admin
{
[AjaxRequestAttribute]
[Description("菜单管理")]
public class MenusController : Controller
{
IFW_MODULE_MANAGER ModuleManager = OperateContext.Current.BLLSession.IFW_MODULE_MANAGER;
#region 菜单管理部分
//
// GET: /Admin/Menus/
[ActionDesc("菜单管理主页")]
[Description("[菜单管理]菜单管理主页")]
[DefaultPage]
[ActionParent]
public ActionResult MenuInfo()
{
ViewBag.ModuleLeftMenus =MODEL.ViewModel.VIEW_FW_MODULE.ToListViewModel( ModuleManager.GetListBy(m => m.MODULE_PID == "MAIN_FIRST" || m.MODULE_ID == "MAIN_FIRST"));
// UserOperateLog.WriteOperateLog("[菜单管理]浏览菜单管理主页"+SysOperate.Load.ToString());
return View();
}
[ActionDesc("菜单详细信息")]
[Description("[菜单管理]菜单详细信息")]
public ActionResult MenusDetail(string id)
{
ViewBag.TYPE = "Add";
ViewBag.PID= DataSelect.ToListViewModel(VIEW_FW_MODULE.ToListViewModel(ModuleManager.GetListBy(m => true)));
ViewBag.MVCController = DataSelect.ToListViewModel(LINQHelper.GetIenumberable<MVCController>(ConfigSettings.GetAllController(), p => p.ControllerName.ToLower() != "",
q => q.ControllerName, 200,
1));
var model = ModuleManager.Get(m => m.MODULE_ID == id);
if (model == null)
{
return View(new VIEW_FW_MODULE() { });
}
ViewBag.TYPE = "Update";
return View(VIEW_FW_MODULE.ToViewModel(model));
}
[ActionDesc("添加","Y")]
[Description("[菜单管理]菜单管理Add")]
public ActionResult Add(VIEW_FW_MODULE model)
{
bool status = false;
if (!ModelState.IsValid)
return this.JsonFormat(ModelState, status, "ERROR");
var menu = VIEW_FW_MODULE.ToEntity(model);
try
{
ModuleManager.Add(menu);
status = true;
}
catch (Exception e)
{
return this.JsonFormat("SYSERROR", status, e.Message);
}
return this.JsonFormat("/admin/menus/MenuInfo", status, SysOperate.Add.ToMessage(status), status);
}
[ActionDesc("编辑", "Y")]
[Description("[菜单管理]菜单管理Update")]
public ActionResult Update(VIEW_FW_MODULE model)
{
bool status = false;
if (!ModelState.IsValid)
return this.JsonFormat(ModelState, status, "ERROR");
var menu = VIEW_FW_MODULE.ToEntity(model);
try
{
menu.MODIFY_DT = DateTime.Now;
ModuleManager.Modify(menu, "MODULE_PID", "MODULE_NAME", "MODULE_CONTROLLER", "ISMENU", "ISVISIBLE", "ICON", "MODULE_LINK", "MODIFY_DT");
status = true;
}
catch (Exception e)
{
return this.JsonFormat("SYSERROR", status, e.Message);
}
return this.JsonFormat("/admin/menus/MenuInfo", status, SysOperate.Update.ToMessage(status), status);
}
[ActionDesc("获取菜单Grid信息")]
[Description("[菜单管理]获取菜单下的子菜单的Grid信息(首页必须)")]
public ActionResult GetMenusForGrid(QueryModel model)
{
DataTableRequest requestGrid = new DataTableRequest(HttpContext, model);
return this.JsonFormat(ModuleManager.GetMenusForGrid(requestGrid) );
}
#endregion
#region 菜单按钮管理
[ActionDesc("菜单按钮管理", "Y")]
[Description("[菜单管理]菜单按钮管理")]
public ActionResult MenuButtonConfig()
{
MODEL.ViewPage.ViewSelectParamPage page = new MODEL.ViewPage.ViewSelectParamPage(HttpContext);
var data = ModuleManager.GetListBy(p => p.MODULE_CONTROLLER == page.ControllerName).FirstOrDefault();
return this.JsonFormatSuccess(data.MODULE_CONTROLLER, "允许访问");
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Web
{
public sealed class JsonErrorForRecordID : JsonError
{
public string id;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace WebAPI_Connection_ReExam.Custom
{
public class LHistory
{
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "history")]
public List<IHistory> history { get; set; }
}
} |
using System;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using OnlineClinic.Core.DTOs;
using OnlineClinic.Core.Services;
namespace BlazorUI.Pages.People.Edit
{
public partial class PersonEdit: ComponentBase
{
[Parameter]
public int Id { get; set; }
[Inject]
protected NavigationManager NavigationManager { get; set; }
[Inject]
protected IPersonService PersonService { get; set; }
[Inject]
protected IMapper Mapper { get; set; }
private PersonEditDto editDto;
private PersonGetDto getDto;
private EditContext editContext;
protected override void OnInitialized()
{
getDto = PersonService.GetById(Id);
editDto = Mapper.Map<PersonEditDto>(getDto);
editDto.SetPersonService(PersonService);
editContext = new EditContext(editDto);
base.OnInitialized();
}
private async Task SubmitForm()
{
DateTime dobDate = DateTime.MinValue;
if(!DateTime.TryParse(editDto.DOBString, out dobDate))
editDto.DOB = DateTime.MinValue;
var isValid = editContext.Validate();
if(isValid)
{
await editDto.Save();
NavigationManager.NavigateTo("People");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using GDS.Entity;
using SqlSugar;
using GDS.Comon;
namespace GDS.Dal
{
public class ImplProjectPhase : ImplDaoBase<ProjectPhase>, IProjectPhaseDao<ProjectPhase>
{
public List<View_ProjectPhase> GetProjectPhaseListByProjectId(int ProjectId, int TemplateId)
{
try
{
using (var db = SugarDao.GetInstance())
{
db.IsNoLock = true;
var li = db.SqlQuery<View_ProjectPhase>(@"
select a.*
,b.[Id] as ProjectPhaseId
,b.[ProjectId]
,b.[TemplatePhaseId]
,b.[StartTime]
,b.[EndTime]
,b.[Status]
from TemplatePhase a left join (select * from ProjectPhase where ProjectId = @ProjectId ) b on a.id = b.TemplatePhaseId
where a.TemplateId =@TemplateId ", new { ProjectId, TemplateId });
return li;
}
}
catch (Exception ex)
{
Loger.LogErr(ex);
return null;
}
}
public string GetTaskSubjects()
{
try
{
using (var db = SugarDao.GetInstance())
{
db.IsNoLock = true;
var subjectStr = db.GetString(@"select [value] from dbo.Settings where [key]='TaskSubjects'");
return subjectStr;
}
}
catch (Exception ex)
{
Loger.LogErr(ex);
return null;
}
}
public string GetRiskSetting(string key)
{
try
{
using (var db = SugarDao.GetInstance())
{
db.IsNoLock = true;
var subjectStr = db.GetString(@"select [value] from dbo.Settings where [key]=@key", new { key });
return subjectStr;
}
}
catch (Exception ex)
{
Loger.LogErr(ex);
return null;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace pathtest
{
public partial class Form1 : Form
{
const int MAX_UNIT = 200;
CNavigationData m_ND = null;
CAStarPathFinding m_PathFinding = null;
Timer m_TM = null;
Graphics m_Buf = null;
Bitmap m_Bitmap = null;
CUnit[] m_pUnits = null;
public Form1()
{
InitializeComponent();
InitializeComponent2();
m_ND = new CNavigationData();
m_PathFinding = new CAStarPathFinding();
m_pUnits = new CUnit[MAX_UNIT];
Random rnd = new Random();
for (int i = 0;i < MAX_UNIT; ++i)
{
m_pUnits[i] = new CUnit();
if (i == 0)
{
m_pUnits[i].EnableTracking(true);
//m_pUnits[i].StartTracking(true); //주석을 해제 하면 자동 추적한다
}
else
{
m_pUnits[i].EnableTracking(false);
m_pUnits[i].SetTarget(m_pUnits[0]);
}
}
}
private void InitializeComponent2()
{
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.ClientSize = new System.Drawing.Size(640, 640);
this.Text = "PathTest";
this.Paint += new PaintEventHandler(this.BasicX_Paint);
}
private void BasicX_Paint(object sender, PaintEventArgs e)
{
DrawMap();
}
private void Form1_Load(object sender, EventArgs e)
{
if (m_ND != null)
{
if (!m_ND.Load("map.txt"))
{
MessageBox.Show("failed to loading map data");
}
else
{
for (int i = 0;i < MAX_UNIT; ++i)
{
if (!m_pUnits[i].IsTracking())
{
m_pUnits[i].RandomPos(m_ND);
}
}
}
}
m_TM = new Timer();
m_TM.Interval = 1;
m_TM.Tick += new EventHandler(Update);
m_TM.Enabled = true;
m_Bitmap = new Bitmap(640, 640);
m_Buf = Graphics.FromImage(m_Bitmap);
}
void Update(object sender, EventArgs e)
{
if (m_ND != null)
{
for (int i = 0;i < MAX_UNIT; ++i)
{
if (m_pUnits[i].IsTracking()) m_pUnits[i].SelectTarget(m_pUnits, MAX_UNIT);
m_pUnits[i].Update(m_ND, m_PathFinding);
}
}
DrawMap();
}
private void DrawMap()
{
if (m_ND == null) return;
int cx, cy;
for (int y = 0, py = 0;y < m_ND.GetHeight(); ++y, py += 16)
{
for (int x = 0, px = 0; x < m_ND.GetWidth(); ++x, px += 16)
{
cx = x * 16;
cy = y * 16;
if (m_ND.IsValidPos(x, y))
{
m_Buf.FillRectangle(Brushes.Yellow, (float)cx, (float)cy, 16.0f, 16.0f);
}
else
{
m_Buf.FillRectangle(Brushes.Red, (float)cx, (float)cy, 16.0f, 16.0f);
}
}
}
for (int i = 0; i < MAX_UNIT; ++i)
{
cx = m_pUnits[i].GetX() * 16;
cy = m_pUnits[i].GetY() * 16;
if (m_pUnits[i].IsTracking()) m_Buf.FillRectangle(Brushes.Blue, (float)cx, (float)cy, 16.0f, 16.0f);
else m_Buf.FillRectangle(Brushes.Green, (float)cx, (float)cy, 16.0f, 16.0f);
}
Graphics g = CreateGraphics();
g.DrawImage(m_Bitmap, 0.0f, 0.0f);
}
protected override void OnMouseDown(MouseEventArgs e)
{
int cx = e.X / 16;
int cy = e.Y / 16;
base.OnMouseDown(e);
if (m_PathFinding != null)
{
for (int i = 0;i < MAX_UNIT; ++i)
{
if (m_pUnits[i].IsTracking())
{
CNaviNode pStart = CNaviNode.Create(m_pUnits[i].GetX(), m_pUnits[i].GetY());
CNaviNode pEnd = CNaviNode.Create(cx, cy);
List<CNaviNode> vecPath = new List<CNaviNode>();
if (!m_PathFinding.FindPath(pStart, pEnd, ref vecPath, m_ND))
{
}
else
{
m_pUnits[i].SetPath(vecPath);
}
}
}
}
}
}
} |
using System;
using System.Linq;
namespace CodeBlog_25_AttributeAndReflecsion
{
class Program
{
static void Main(string[] args)
{
// атрибутами являются наследники базового класса
// очередной вспомогательный класс
// типа помтка, к которой мы можем потом обратиться
var photo1 = new Photo("Maldives.png")
{
Path = "D:\\Games\\Maldives.png"
};
var type = typeof(Photo);
var attributes = type.GetCustomAttributes(false);
foreach (var item in attributes)
{
Console.WriteLine(item);
}
Console.WriteLine(new string ('_', 35));
var photo2 = new Photo("Bali.png")
{
Path = "D:\\Games\\Maldives.png"
};
var type2 = typeof(Photo);
var attributes2 = type.GetCustomAttributes(false); //возвращает атрибьюты
foreach (var item in attributes2)
{
Console.WriteLine(item);
}
var properties = type2.GetProperties();
foreach (var item in properties)
{
var attr = item.GetCustomAttributes(false);
if (attr.Any(a => a.GetType() == typeof(GeoAttribute)))
{
Console.WriteLine(item.PropertyType + " " + item.Name + " " + item.Attributes);
}
//foreach (var a in attr)
//{
// Console.WriteLine(a);
//}
}
Console.ReadLine();
}
}
}
|
using FeriaVirtual.Domain.SeedWork.Events;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FeriaVirtual.Infrastructure.SeedWork.Events
{
public class DomainEventsInformation
{
private readonly Dictionary<string, Type> IndexedDomainEvents = new();
public DomainEventsInformation() =>
GetDomainTypes().ForEach(eventType => IndexedDomainEvents.Add(GetEventName(eventType), eventType));
public Type ForName(string name)
{
IndexedDomainEvents.TryGetValue(name, out Type value);
return value;
}
public string ForClass(DomainEventBase domainEvent) =>
IndexedDomainEvents.FirstOrDefault(x => x.Value.Equals(domainEvent.GetType())).Key;
private string GetEventName(Type eventType)
{
var instance = (DomainEventBase)Activator.CreateInstance(eventType);
return eventType.GetMethod("EventName").Invoke(instance, null).ToString();
}
private List<Type> GetDomainTypes()
{
var type = typeof(DomainEventBase);
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p) && !p.IsAbstract).ToList();
}
}
}
|
using System;
namespace UseFul.Uteis
{
public class ProgressUpdatedEventArgs : EventArgs
{
public ProgressUpdatedEventArgs(int pbNum, int total, int progress, string message = "")
{
PbNum = pbNum;
Total = total;
Processed = progress;
Message = message;
}
public string Message { get; private set; }
public int PbNum { get; private set; }
public int Processed { get; private set; }
public int Total { get; private set; }
}
} |
using Autofac;
using EmberKernel.Plugins.Components;
using System.Threading.Tasks;
namespace EmberKernel.Plugins
{
public abstract class Plugin : IPlugin
{
public abstract void BuildComponents(IComponentBuilder builder);
public abstract ValueTask Initialize(ILifetimeScope scope);
public abstract ValueTask Uninitialize(ILifetimeScope scope);
}
}
|
namespace DataLayer
{
using System;
using System.Data;
using System.Data.SqlClient;
public class FinanceManager
{
public DataSet GetAssetQueryDdl(string name, string div)
{
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@full_name", name), new SqlParameter("@user_div", div) };
return clsConnectionString.returnConnection.executeSelectQueryDataSet("usp_fin_fixed_asset_query_ddl", CommandType.StoredProcedure, parameterArray);
}
public DataTable GetFixedAssetDetails(int assetRegisterId)
{
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@fin_asset_register_id", assetRegisterId) };
return clsConnectionString.returnConnection.executeSelectQuery("usp_fin_fixed_asset_details", CommandType.StoredProcedure, parameterArray);
}
public DataTable SearchFixedAssetQUery(string budgetCentre, string emp, string physLoc, string yearInService, string majorCat, string minorCat, string identifier, string assetDesc, string manufacturer, string vendor, string status, string fullName, string userDiv)
{
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@budget_center", budgetCentre), new SqlParameter("@employee", emp.Trim()), new SqlParameter("@physical_location", physLoc.Trim()), new SqlParameter("@year_placed_in_service", yearInService), new SqlParameter("@major_category", majorCat), new SqlParameter("@minor_category", minorCat), new SqlParameter("@identifier", identifier.Trim()), new SqlParameter("@asset_description", assetDesc.Trim()), new SqlParameter("@manufacturer", manufacturer.Trim()), new SqlParameter("@status", status), new SqlParameter("@vendor", vendor.Trim()), new SqlParameter("@user_div", userDiv), new SqlParameter("@full_name", fullName) };
return clsConnectionString.returnConnection.executeSelectQuery("usp_fin_fixed_asset_query", CommandType.StoredProcedure, parameterArray);
}
public DataTable SearchFixedAssetQueryReport(string reportType, string budgetCentre, string emp, string physLoc, string yearInService, string majorCat, string minorCat, string identifier, string assetDesc, string manufacturer, string vendor, string status, string fullName, string userDiv)
{
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@budget_center", budgetCentre), new SqlParameter("@employee", emp), new SqlParameter("@physical_location", physLoc), new SqlParameter("@year_placed_in_service", yearInService), new SqlParameter("@major_category", majorCat), new SqlParameter("@minor_category", minorCat), new SqlParameter("@identifier", identifier), new SqlParameter("@asset_description", assetDesc), new SqlParameter("@manufacturer", manufacturer), new SqlParameter("@status", status), new SqlParameter("@vendor", vendor), new SqlParameter("@report_type", reportType), new SqlParameter("@full_name", fullName), new SqlParameter("@user_div", userDiv) };
return clsConnectionString.returnConnection.executeSelectQuery("usp_fin_fixed_asset_query_report", CommandType.StoredProcedure, parameterArray);
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using VoxelSpace.Graphics;
namespace VoxelSpace.UI {
public class VoxelIconMaterial : GeometryMaterial {
protected override string _effectResourceName => "@shader/ui/voxel";
public VoxelIconMaterial() : base("Geometry") {}
public Vector3 SunDirection {
get => this["sunDirection"].GetValueVector3();
set => this["sunDirection"].SetValue(value);
}
public float DiffuseIntensity {
get => this["diffuseIntensity"].GetValueSingle();
set => this["diffuseIntensity"].SetValue(value);
}
public float AmbientIntensity {
get => this["ambientIntensity"].GetValueSingle();
set => this["ambientIntensity"].SetValue(value);
}
}
} |
namespace _05._FilterStudentsByEmailDomain
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Startup
{
public static void Main()
{
string input = Console.ReadLine();
List<Student> students = new List<Student>();
while (input != "END")
{
string[] inputParts = input.Split(' ');
string firstName = inputParts[0];
string lastName = inputParts[1];
string email = inputParts[2];
Student student = new Student(firstName, lastName, email);
students.Add(student);
input = Console.ReadLine();
}
students.Where(s => s.Email.EndsWith("@gmail.com"))
.ToList()
.ForEach(s => Console.WriteLine($"{s.FirstName} {s.LastName}"));
}
}
} |
namespace Orc.FileSystem.Tests.Services;
using System;
using System.IO;
using System.Threading.Tasks;
using NUnit.Framework;
public class IOSynchronizationServiceFacts
{
// TODO: Write unit tests
[TestFixture]
public class TheExecuteWritingAsyncMethod
{
[Test]
public async Task WriterWrapsAnyExceptionIntoIOSynchronizationExceptionAsync()
{
try
{
using (var temporaryFilesContext = new TemporaryFilesContext("DoesNotSwallowReaderIOExceptionAsync"))
{
var rootDirectory = temporaryFilesContext.GetDirectory("output");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationService(fileService, new DirectoryService(fileService));
var alreadyExecuted = false;
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ =>
{
if (alreadyExecuted)
{
return true;
}
// preventing continuous loop
alreadyExecuted = true;
throw new IOException();
});
}
Assert.Fail("Expected exception");
}
catch (Exception ex)
{
Assert.IsInstanceOf<IOSynchronizationException>(ex);
}
}
[Test]
public async Task AllowsAccessToSameDirectoryBySameProcessAsync()
{
using var temporaryFilesContext = new TemporaryFilesContext("AllowsAccessToSameDirectoryBySameProcessAsync");
var rootDirectory = temporaryFilesContext.GetDirectory("output");
var file1 = temporaryFilesContext.GetFile("output\\file1.txt");
var file2 = temporaryFilesContext.GetFile("output\\file2.txt");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationService(fileService, new DirectoryService(fileService));
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ =>
{
// File 1
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ => true);
// File 2
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ => true);
return true;
});
}
[Test]
public async Task AllowsAccessToNestingDirectoriesBySameProcessAsync()
{
using var temporaryFilesContext = new TemporaryFilesContext("AllowsAccessToNestingDirectoriesBySameProcessAsync");
var rootDirectory = temporaryFilesContext.GetDirectory("output");
var subDirectory = temporaryFilesContext.GetDirectory("output\\subdirectory");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationService(fileService, new DirectoryService(fileService));
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ =>
{
await ioSynchronizationService.ExecuteWritingAsync(subDirectory, async _ => true);
return true;
});
}
}
[TestFixture]
public class TheExecuteReadingAsyncMethod
{
[Test]
public async Task ReaderWrapsAnyExceptionIntoIOSynchronizationExceptionAsync()
{
try
{
using (var temporaryFilesContext = new TemporaryFilesContext("DoesNotSwallowReaderIOExceptionAsync"))
{
var rootDirectory = temporaryFilesContext.GetDirectory("output");
var fileName = temporaryFilesContext.GetFile("file1.txt");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationService(fileService, new DirectoryService(fileService));
// write for creating sync file
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ =>
{
await File.WriteAllTextAsync(fileName, "12345");
return true;
});
var alreadyExecuted = false;
await ioSynchronizationService.ExecuteReadingAsync(rootDirectory, async _ =>
{
if (alreadyExecuted)
{
return true;
}
// preventing continuous loop
alreadyExecuted = true;
throw new IOException();
});
}
Assert.Fail("Expected exception");
}
catch (Exception ex)
{
Assert.IsInstanceOf<IOSynchronizationException>(ex);
}
}
[Test]
public async Task DoesNotDeleteSyncFileIfEqualsToObservedFilePathAsync()
{
using var temporaryFilesContext = new TemporaryFilesContext("DoesNotDeleteSyncFileIfEqualsToObservedFilePathAsync");
var fileName = temporaryFilesContext.GetFile("file1.txt");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationWithoutSeparateSyncFileService(fileService, new DirectoryService(fileService));
// ensure syn file exists and data file exists
await ioSynchronizationService.ExecuteWritingAsync(fileName, async _ =>
{
await File.WriteAllTextAsync(fileName, "12345");
return true;
});
var syncFile = ioSynchronizationService.GetSyncFileByPath(fileName);
// required thing
Assert.AreEqual(syncFile, fileName);
Assert.IsTrue(File.Exists(syncFile));
// nested readings
await ioSynchronizationService.ExecuteReadingAsync(fileName, async _ =>
{
await ioSynchronizationService.ExecuteReadingAsync(fileName, async _ =>
{
Assert.IsTrue(File.Exists(syncFile));
return true;
});
Assert.IsTrue(File.Exists(syncFile));
return true;
});
// Even now the refresh file should not be removed
Assert.IsTrue(File.Exists(syncFile));
}
[Test]
public async Task CorrectlyReleasesFileAfterAllNestedScopesHaveBeenReleasedAsync()
{
using var temporaryFilesContext = new TemporaryFilesContext("CorrectlyReleasesFileAfterAllNestedScopesHaveBeenReleasedAsync");
var rootDirectory = temporaryFilesContext.GetDirectory("output");
var fileName = temporaryFilesContext.GetFile("file1.txt");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationService(fileService, new DirectoryService(fileService));
// Step 1: Write
await ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ =>
{
await File.WriteAllTextAsync(fileName, "12345");
return true;
});
var syncFile = ioSynchronizationService.GetSyncFileByPath(rootDirectory);
Assert.IsTrue(File.Exists(syncFile));
// Now do 2 nested reads
await ioSynchronizationService.ExecuteReadingAsync(rootDirectory, async _ =>
{
await ioSynchronizationService.ExecuteReadingAsync(rootDirectory, async _ =>
{
Assert.IsTrue(File.Exists(syncFile));
return true;
});
Assert.IsTrue(File.Exists(syncFile));
return true;
});
// Only now the refresh file should be removed
Assert.IsFalse(File.Exists(syncFile));
}
[Test]
public async Task WaitWithReadingUntilWriteIsFinishedAsync()
{
using var temporaryFilesContext = new TemporaryFilesContext("WaitWithReadingUntilWriteIsFinishedAsync");
var rootDirectory = temporaryFilesContext.GetDirectory("output");
var fileName = temporaryFilesContext.GetFile("file1.txt");
var fileService = new FileService();
var ioSynchronizationService = new IOSynchronizationService(fileService, new DirectoryService(fileService));
// Step 1: Write, do not await
#pragma warning disable 4014
ioSynchronizationService.ExecuteWritingAsync(rootDirectory, async _ =>
#pragma warning restore 4014
{
await File.WriteAllTextAsync(fileName, "12345");
await Task.Delay(2500);
return true;
});
var startTime = DateTime.Now;
var endTime = DateTime.Now;
// Step 2: read, but should only be allowed after 5 seconds
await ioSynchronizationService.ExecuteReadingAsync(rootDirectory, async _ =>
{
endTime = DateTime.Now;
return true;
});
var delta = endTime - startTime;
// Delta should be at least 2 seconds (meaning we have awaited the writing)
Assert.IsTrue(delta > TimeSpan.FromSeconds(2));
}
}
}
|
public class Solution {
public int NumDistinct(string s, string t) {
int size1 = s.Length, size2 = t.Length;
if (size1 == 0 && size2 > 0) return 0;
if (size1 == 0 && size2 == 0) return 1;
int[,] dp = new int[size1+1, size2+1];
for (int i=0; i<=size1; i++) dp[i,0] = 1;
for (int i=1; i<=size2; i++) dp[0,i] = 0;
for (int j=1; j<=size2; j++) {
for (int i=1; i<=size1; i++) {
if (i<j) dp[i,j] = 0;
else if (s[i-1] == t[j-1]) dp[i,j] = dp[i-1, j-1] + dp[i-1, j];
else dp[i,j] = dp[i-1, j];
//Console.WriteLine($"{i} {j} {dp[i,j]}");
}
}
return dp[size1, size2];
}
} |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
namespace Microsoft.Azure.Management.ANF.Samples.Common
{
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
/// <summary>
/// Contains public methods to get configuration settigns, to initiate authentication, output error results, etc.
/// </summary>
public static class Utils
{
/// <summary>
/// Authentication scope, this is the minimum required to be able to manage resources
/// </summary>
private static string[] Scopes { get; set; } = new string[] { @"https://management.core.windows.net/.default" };
/// <summary>
/// Simple function to display this console app basic information
/// </summary>
public static void DisplayConsoleAppHeader()
{
Console.WriteLine("Azure NetAppFiles .netcore SDK Samples - Sample project that performs CRUD management operations with Azure NetApp Files SDK");
Console.WriteLine("----------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("");
}
/// <summary>
/// Function to create the configuration object, used for authentication and ANF resource information
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static ProjectConfiguration GetConfiguration(string filename)
{
return ProjectConfiguration.ReadFromJsonFile(filename);
}
/// <summary>
/// Function to authenticate against Azure AD using MSAL 3.0
/// </summary>
/// <param name="appConfig">Application configuration required for the authentication process</param>
/// <returns>AuthenticationResult object</returns>
public static async Task<AuthenticationResult> AuthenticateAsync(PublicClientApplicationOptions appConfig)
{
var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(appConfig)
.Build();
DeviceCodeFlow tokenAcquisitionHelper = new DeviceCodeFlow(app);
return (await tokenAcquisitionHelper.AcquireATokenFromCacheOrDeviceCodeFlowAsync(Scopes));
}
/// <summary>
/// Converts bytes into TiB
/// </summary>
/// <param name="size">Size in bytes</param>
/// <returns>Returns (decimal) the value of bytes in TiB scale</returns>
public static decimal GetBytesInTiB(long size)
{
return (decimal)size / 1024 / 1024 / 1024 / 1024;
}
/// <summary>
/// Converts TiB into bytes
/// </summary>
/// <param name="size">Size in TiB</param>
/// <returns>Returns (long) the value of TiB in bytes scale</returns>
public static long GetTiBInBytes(decimal size)
{
return (long)size * 1024 * 1024 * 1024 * 1024;
}
/// <summary>
/// Displays errors messages in red
/// </summary>
/// <param name="message">Message to be written in console</param>
public static void WriteErrorMessage(string message)
{
Console.ForegroundColor = ConsoleColor.Red;
Utils.WriteConsoleMessage(message);
Console.ResetColor();
}
/// <summary>
/// Displays errors messages in red
/// </summary>
/// <param name="message">Message to be written in console</param>
public static void WriteConsoleMessage(string message)
{
Console.WriteLine($"{DateTime.Now}: {message}");
}
}
}
|
using Efa.Application.Interfaces;
using Efa.Application.ViewModels;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Efa.Services.WebApi.Controllers
{
[RoutePrefix("api")]
public class ContatoGrupoController : ApiController
{
private readonly IContatoGrupoAppService _contatoGrupoApp;
private readonly IContatoPessoaAppService _contatoPessoaApp;
public ContatoGrupoController(IContatoGrupoAppService contatoGrupoApp, IContatoPessoaAppService contatoPessoaApp)
{
_contatoGrupoApp = contatoGrupoApp;
_contatoPessoaApp = contatoPessoaApp;
}
[HttpGet]
[Route("grupos")]
public HttpResponseMessage Get(int skip = 0, int take = 5)
{
var result = _contatoGrupoApp.GetAll(skip, take);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
[HttpGet]
[Route("gruposPessoas")]
public HttpResponseMessage Get()
{
var result = _contatoGrupoApp.GetGrupos();
return Request.CreateResponse(HttpStatusCode.OK, result);
}
[HttpPost]
[Route("grupos")]
public HttpResponseMessage PostGrupo(ContatoGrupoViewModel contatoGrupo)
{
if (ModelState.IsValid)
{
_contatoGrupoApp.Add(contatoGrupo);
return Request.CreateResponse(HttpStatusCode.Created, contatoGrupo);
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
[HttpPut]
[Route("grupos")]
public HttpResponseMessage SaveGrupo(ContatoGrupoViewModel contatoGrupo)
{
if (ModelState.IsValid)
{
_contatoGrupoApp.Update(contatoGrupo);
return Request.CreateResponse(HttpStatusCode.OK, contatoGrupo);
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
[HttpDelete]
[Route("grupos/{id}")]
public HttpResponseMessage Delete(Guid id)
{
var contatoGrupo = _contatoGrupoApp.GetById(id);
if (contatoGrupo == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
//excluir pessoas do grupo
_contatoPessoaApp.RemoveFromGruoup(id);
//Exclui grupo
_contatoGrupoApp.Remove(contatoGrupo);
return Request.CreateResponse(HttpStatusCode.OK, contatoGrupo);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using WAReporter.Modelo;
namespace WAReporter
{
public partial class JanelaPrincipal : Window
{
private string CaminhoMsgStoreDb = "";
private string CaminhoWaDb = "";
private List<DataGridItem> ItensDataGrid { get; set; }
public JanelaPrincipal()
{
InitializeComponent();
//foreach (var arquivoAvatar in Directory.GetFiles(@"I:\whatsApp_private\profpics"))
// if (!File.Exists(arquivoAvatar + ".jpg"))
// File.Copy(arquivoAvatar, arquivoAvatar + ".jpg");
}
private void AbrirAndroidCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var janelaAbrirArquivoAndroid = new JanelaAbrirArquivoAndroid();
janelaAbrirArquivoAndroid.SelecaoOk += delegate
{
CaminhoMsgStoreDb = janelaAbrirArquivoAndroid.arquivoTextBox.Text.Replace(".db.crypt", ".db");
CaminhoWaDb = janelaAbrirArquivoAndroid.waDbTextBox.Text;
var resultadoCarregamento = Banco.CarregarBancoAndroid(CaminhoMsgStoreDb, CaminhoWaDb);
if(resultadoCarregamento.StartsWith("ERRO"))
{
MessageBox.Show(resultadoCarregamento);
}
else
{
ItensDataGrid = new List<DataGridItem>();
foreach (var chat in Banco.Chats) ItensDataGrid.Add(new DataGridItem {
ChatItem = chat,
NomeContato = chat.Contato.NomeContato + chat.Subject,
UltimaMensagem = chat.Mensagens.Any() ? chat.Mensagens.Max(p => p.Timestamp).ToString() : "",
IsSelecionado = false });
contatosDataGrid.ItemsSource = ItensDataGrid;
Midia.Procurar(Directory.GetParent(System.IO.Path.GetDirectoryName(janelaAbrirArquivoAndroid.arquivoTextBox.Text)).FullName);
}
};
janelaAbrirArquivoAndroid.ShowDialog();
}
private void AbrirIPhoneCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var janelaAbrirArquivoIPhone = new JanelaAbrirArquivoIPhone();
janelaAbrirArquivoIPhone.SelecaoOk += delegate
{
CaminhoMsgStoreDb = janelaAbrirArquivoIPhone.arquivoTextBox.Text.Replace(".db.crypt", ".db");
CaminhoWaDb = janelaAbrirArquivoIPhone.contactsSqliteTextBox.Text;
var resultadoCarregamento = Banco.CarregarBancoIPhone(CaminhoMsgStoreDb, CaminhoWaDb);
if (resultadoCarregamento.StartsWith("ERRO"))
{
MessageBox.Show(resultadoCarregamento);
}
else
{
ItensDataGrid = new List<DataGridItem>();
foreach (var chat in Banco.Chats)
ItensDataGrid.Add(new DataGridItem
{
ChatItem = chat,
NomeContato = chat.Contato.NomeContato + chat.Subject,
UltimaMensagem = chat.Mensagens.Any() ? chat.Mensagens.Max(p => p.Timestamp).ToString() : "",
IsSelecionado = false
});
contatosDataGrid.ItemsSource = ItensDataGrid;
Midia.Procurar(Directory.GetParent(System.IO.Path.GetDirectoryName(janelaAbrirArquivoIPhone.arquivoTextBox.Text)).FullName);
}
};
janelaAbrirArquivoIPhone.ShowDialog();
}
private void ExtrairCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var janelaExtrairCriptografia = new JanelaExtrairCriptografia();
janelaExtrairCriptografia.SelecaoOk += delegate
{
CaminhoMsgStoreDb = janelaExtrairCriptografia.arquivoTextBox.Text.Replace(".db.crypt", ".db");
//CaminhoWaDb = janelaExtrairCriptografia.waDbTextBox.Text;
var resultadoCarregamento = Banco.CarregarBancoAndroid(CaminhoMsgStoreDb, CaminhoWaDb);
if (resultadoCarregamento.StartsWith("ERRO"))
{
MessageBox.Show(resultadoCarregamento);
}
else
{
ItensDataGrid = new List<DataGridItem>();
foreach (var chat in Banco.Chats)
ItensDataGrid.Add(new DataGridItem
{
ChatItem = chat,
NomeContato = chat.Contato.NomeContato + chat.Subject,
UltimaMensagem = chat.Mensagens.Any() ? chat.Mensagens.Max(p => p.Timestamp).ToString() : "",
IsSelecionado = false
});
contatosDataGrid.ItemsSource = ItensDataGrid;
Midia.Procurar(Directory.GetParent(System.IO.Path.GetDirectoryName(janelaExtrairCriptografia.arquivoTextBox.Text)).FullName);
}
};
janelaExtrairCriptografia.ShowDialog();
}
private void SairCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void selecionarTodosButton_Click(object sender, RoutedEventArgs e)
{
foreach(var itemDataGrid in ItensDataGrid)
itemDataGrid.IsSelecionado = true;
}
private void gerarRelatorioButton_Click(object sender, RoutedEventArgs e)
{
var itensSelecionados = ItensDataGrid.Where(p => p.IsSelecionado);
if(!itensSelecionados.Any())
{
MessageBox.Show("Nenhum chat selecionado.");
return;
}
var caminhoRelatorio = Path.Combine(Path.GetDirectoryName(CaminhoMsgStoreDb), "WhatsApp - Relatório "+Midia.NomeUsuario+".html");
var resultado = GeradorRelatorio.GerarRelatorioHtml(itensSelecionados.Select(p => p.ChatItem).ToList(), caminhoRelatorio);
}
private void selecionarNenhumButton_Click(object sender, RoutedEventArgs e)
{
foreach (var itemDataGrid in ItensDataGrid)
itemDataGrid.IsSelecionado = false;
}
}
public class DataGridItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Chat ChatItem { get; set; }
private bool isSelecionado;
public bool IsSelecionado
{
get { return isSelecionado; }
set
{
isSelecionado = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsSelecionado"));
}
}
public String NomeContato { get; set; }
public String UltimaMensagem { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Players { Left, Right }
public enum Stuffs { Shit, Fish, Sword, Ball }
public class Player : MonoBehaviour {
private Animator anim;
public int HP = 10;
public GameObject shitPrefab;
public GameObject fishPrefab;
public GameObject swordPrefab;
public GameObject ballPrefab;
public Players who;
public Transform thrower;
public Vector2 direction = new Vector2(1f, 1f);
public float forceMultiplier;
private void Awake()
{
anim = GetComponentInChildren<Animator>();
}
public void ThrowStuff(float force, Stuffs stuff)
{
// 扔东西
Debug.LogFormat("Player {0} throws stuff with force {1}", (who == Players.Left) ? 1 : 2, force);
GameObject stuffPrefab;
switch (stuff)
{
case Stuffs.Ball: stuffPrefab = ballPrefab; break;
case Stuffs.Fish: stuffPrefab = fishPrefab; break;
case Stuffs.Sword: stuffPrefab = swordPrefab; break;
case Stuffs.Shit: stuffPrefab = shitPrefab; break;
default: stuffPrefab = null; break;
}
Instantiate<GameObject>(stuffPrefab, thrower.transform.position, Quaternion.identity)
.GetComponent<Rigidbody2D>().AddForce(direction * ((force + 0.1f) / 1.1f * forceMultiplier));
// 动画
anim.SetTrigger("Attack");
}
public void TakeDamage(int damage)
{
HP -= damage;
UIManager.instance.UpdateHP(Mathf.Max(0, HP), who);
if (HP <= 0)
{
anim.SetTrigger("Die");
}
else
anim.SetTrigger("Hurt");
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using DBDiff.Schema.Events;
using DBDiff.Schema.SQLServer2000.Model;
using DBDiff.Schema.SQLServer2000.Compare;
namespace DBDiff.Schema.SQLServer2000
{
public class Generate
{
public event Progress.ProgressHandler OnTableProgress;
private string connectioString;
public string ConnectioString
{
get { return connectioString; }
set { connectioString = value; }
}
/// <summary>
/// Genera el schema de la base de datos seleccionada y devuelve un objeto Database.
/// </summary>
public Database Process()
{
Database databaseSchema = new Database();
GenerateTables tables = new GenerateTables(connectioString);
GenerateUserDataTypes types = new GenerateUserDataTypes(connectioString);
tables.OnTableProgress += new Progress.ProgressHandler(tables_OnTableProgress);
databaseSchema.Tables = tables.Get(databaseSchema);
databaseSchema.UserTypes = types.Get(databaseSchema);
return databaseSchema;
}
private void tables_OnTableProgress(object sender, ProgressEventArgs e)
{
if (OnTableProgress != null)
OnTableProgress(sender, e);
}
/// <summary>
/// Compara el schema de la base con otro y devuelve el script SQL con las diferencias.
/// </summary>
/// <param name="xmlCompareSchema"></param>
/// <returns></returns>
public static Database Compare(Database databaseOriginalSchema, Database databaseCompareSchema)
{
Database merge;
CompareDatabase ftables = new CompareDatabase();
merge = ftables.GenerateDiferences(databaseOriginalSchema, databaseCompareSchema);
return merge;
}
}
}
|
using Microsoft.Extensions.Logging;
namespace Sentry.Extensions.Logging.Tests;
public class LogLevelExtensionsTests
{
[Theory]
[MemberData(nameof(BreadcrumbTestCases))]
public void ToBreadcrumbLevel_TestCases((BreadcrumbLevel expected, LogLevel sut) @case)
=> Assert.Equal(@case.expected, @case.sut.ToBreadcrumbLevel());
public static IEnumerable<object[]> BreadcrumbTestCases()
{
yield return new object[] { (BreadcrumbLevel.Debug, LogLevel.Trace) };
yield return new object[] { (BreadcrumbLevel.Debug, LogLevel.Debug) };
yield return new object[] { (BreadcrumbLevel.Info, LogLevel.Information) };
yield return new object[] { (BreadcrumbLevel.Warning, LogLevel.Warning) };
yield return new object[] { (BreadcrumbLevel.Error, LogLevel.Error) };
yield return new object[] { (BreadcrumbLevel.Critical, LogLevel.Critical) };
yield return new object[] { ((BreadcrumbLevel)6, LogLevel.None) };
yield return new object[] { ((BreadcrumbLevel)int.MaxValue, (LogLevel)int.MaxValue) };
}
[Theory]
[MemberData(nameof(MelTestCases))]
public void ToMicrosoft_TestCases((LogLevel expected, SentryLevel sut) @case)
=> Assert.Equal(@case.expected, @case.sut.ToMicrosoft());
public static IEnumerable<object[]> MelTestCases()
{
yield return new object[] { (LogLevel.Debug, SentryLevel.Debug) };
yield return new object[] { (LogLevel.Information, SentryLevel.Info) };
yield return new object[] { (LogLevel.Warning, SentryLevel.Warning) };
yield return new object[] { (LogLevel.Error, SentryLevel.Error) };
yield return new object[] { (LogLevel.Critical, SentryLevel.Fatal) };
}
[Theory]
[MemberData(nameof(LogLevelToSentryLevel))]
public void ToSentryLevel_TestCases((SentryLevel expected, LogLevel sut) @case)
=> Assert.Equal(@case.expected, @case.sut.ToSentryLevel());
public static IEnumerable<object[]> LogLevelToSentryLevel()
{
yield return new object[] { (SentryLevel.Debug, LogLevel.Trace) };
yield return new object[] { (SentryLevel.Debug, LogLevel.Debug) };
yield return new object[] { (SentryLevel.Info, LogLevel.Information) };
yield return new object[] { (SentryLevel.Warning, LogLevel.Warning) };
yield return new object[] { (SentryLevel.Error, LogLevel.Error) };
yield return new object[] { (SentryLevel.Fatal, LogLevel.Critical) };
}
}
|
using System;
using Bolster.API.Status.Stateless;
using Bolster.Base;
namespace Bolster.API.Interface.Stateless
{
public static class Status
{
public static Success Success => new Success();
public static Failure Failure => new Failure();
public static Either<Success, Failure> SuccessfulResult => Either<Success, Failure>.Choose(Success);
public static Either<Success, Failure> FailureResult => Either<Success, Failure>.Choose(Failure);
public static Either<Success, Failure> ToStatus(this bool boolean) =>
boolean ? Either<Success, Failure>.Choose(new Success()) : Either<Success, Failure>.Choose(new Failure());
public static Either<Success, Failure> Safely(this Action apiAction) {
try {
apiAction();
return SuccessfulResult;
}
catch (Exception e) {
return Either<Success, Failure>.Choose(Failure.Reason(e.Message));
}
}
}
} |
using HBPonto.IoC.Extensions;
using HBPonto.IoC.Middlewares;
using HBPonto.Kernel.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace HBPonto
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddOptions();
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
services.RegisterAuthentication(appSettings);
services.RegisterRepositories();
services.RegisterContexts(appSettings);
services.RegisterServices();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<JiraAuthorizationMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(x => x
.WithOrigins("http://localhost:8100")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Media3D;
using System.Windows.Media;
namespace SpatialMapper.MediaController
{
class MediaTexture
{
private Brush _videoBrush;
private double _opacity = 1;
public Material materialTexture
{
get;
set;
}
public string parentLayer
{
get;
set;
}
public string parentMedia
{
get;
set;
}
public Brush getBrush
{
get
{
return _videoBrush;
}
}
public double Opacity
{
set
{
this._opacity = value;
this._videoBrush.Opacity = value;
}
get
{
return _opacity;
}
}
public MediaTexture(Brush videoBrush, string parentLayerName, string parentMediaName)
{
_videoBrush = videoBrush;
materialTexture = new DiffuseMaterial(_videoBrush);
parentMedia = parentMediaName;
parentLayer = parentLayerName;
}
}
}
|
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 VARP
{
public partial class MainPage : Form
{
public MainPage()
{
InitializeComponent();
}
private void MainPage_Load(object sender, EventArgs e)
{
}
private void RollingDataToolStripMenuItem_Click(object sender, EventArgs e)
{
RollingMill Rm = new RollingMill();
Rm.MdiParent = this; //IV to open in same project
if (!isWinOpen("RollingMill")) {
Rm.Show();
}
else
{
Rm.BringToFront();
}
}
private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void loginToolStripMenuItem_click(object sender, EventArgs e)
{
Login login = new Login();
login.Show();
}
private void IntermediateShearToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void dividingShearToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void QTBToolStripMenuItem_Clock(object sender, EventArgs e)
{
QTB qtb = new QTB();
qtb.MdiParent = this; //IV to open in same project
if (!isWinOpen("QTB"))
{
qtb.Show();
}
else
{
qtb.BringToFront();
}
}
// IV metod to check is page already open or not
public bool isWinOpen(string PageName)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == PageName)
{
isOpen = true;
f.BringToFront();
break;
}
}
return isOpen;
}
}
}
|
namespace Entoarox.CustomPaths
{
internal class CustomPathConfig
{
/*********
** Accessors
*********/
public int Alternatives = 0;
public string File = "";
public string Name = "";
public int Price = 0;
public string Requirements = null;
public string Salesman = "";
public bool Seasonal = false;
public int SpeedBoost = 0;
}
}
|
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SnackGame
{
public partial class Snacker : Form
{
private int direction = 0;
private int score = 1;
private Timer gameLoop = new Timer();
private Random random = new Random();
private Graphics graphics;
private Food food;
private Snack snack;
private bool BOTEnabled = false;
public Snacker()
{
InitializeComponent();
snack = new Snack();
food = new Food(random);
gameLoop.Interval = 120;
gameLoop.Tick += Update;
}
private void Snacker_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Enter:
if (LblMenu.Visible)
{
LblMenu.Visible = false;
LblStartStop.Visible = false;
BOTEnabled = false;
gameLoop.Start();
}
break;
case Keys.B:
if (LblMenu.Visible)
{
LblMenu.Visible = false;
LblStartStop.Visible = false;
BOTEnabled = true;
gameLoop.Start();
}
break;
case Keys.Space:
if (!LblMenu.Visible)
{
gameLoop.Enabled = (gameLoop.Enabled) ? false : true;
}
break;
case Keys.Right:
if (direction != 2)
direction = 0;
break;
case Keys.Down:
if (direction != 3)
direction = 1;
break;
case Keys.Left:
if (direction != 0)
direction = 2;
break;
case Keys.Up:
if (direction != 1)
direction = 3;
break;
}
}
private void Snacker_Paint(object sender, PaintEventArgs e)
{
if (!LblMenu.Visible)
{
graphics = this.CreateGraphics();
snack.Draw(graphics);
food.Draw(graphics);
}
}
private void Update(object sender, EventArgs e)
{
if(!LblMenu.Visible)
{
this.Text = string.Format("Snacker.IO - Score : {0}", score);
if(BOTEnabled)
BOT();
snack.Move(direction);
for (int i = 1; i < snack.body.Length; i++)
if (snack.body[0].IntersectsWith(snack.body[i]))
Restart();
if (snack.body[0].X < 0 || snack.body[0].X > 490)
Restart();
if (snack.body[0].Y < 0 || snack.body[0].Y > 390)
Restart();
if (snack.body[0].IntersectsWith(food.foodPiece))
{
score++;
snack.Graw();
food.Generate(random);
}
if (score < 5)
gameLoop.Interval = 1;
else if (score < 10)
gameLoop.Interval = 1;
else
gameLoop.Interval = 1;
}
this.Invalidate();
}
private void BOT()
{
if(direction == 0)
{
if(snack.body[0].X < food.foodPiece.X)
{
if(snack.body[0].X == food.foodPiece.X)
{
if (snack.body[0].Y > food.foodPiece.Y)
direction = 3;
else
direction = 1;
}
}
else
{
if (snack.body[0].Y > food.foodPiece.Y)
direction = 3;
else
direction = 1;
}
}
else if (direction == 2)
{
if(snack.body[0].X > food.foodPiece.X)
{
if(snack.body[0].X == food.foodPiece.X)
{
if (snack.body[0].Y > food.foodPiece.Y)
direction = 3;
else
direction = 1;
}
}
else
{
if (snack.body[0].Y > food.foodPiece.Y)
direction = 3;
else
direction = 1;
}
}
else if (direction == 3)
{
if(snack.body[0].Y > food.foodPiece.Y)
{
if(snack.body[0].Y == food.foodPiece.Y)
{
if (snack.body[0].X < food.foodPiece.X)
direction = 0;//right
else
direction = 2;//left
}
}
else
{
if (snack.body[0].X < food.foodPiece.X)
direction = 0;
else
direction = 2;
}
}
else if (direction == 1)
{
if (snack.body[0].Y < food.foodPiece.Y)
{
if (snack.body[0].Y == food.foodPiece.Y)
{
if (snack.body[0].X < food.foodPiece.X)
direction = 0;//right
else
direction = 2;//left
}
}
else
{
if (snack.body[0].X < food.foodPiece.X)
direction = 0;
else
direction = 2;
}
}
}
private void Restart()
{
gameLoop.Start();
graphics.Clear(SystemColors.Control);
snack = new Snack();
food = new Food(random);
direction = 0;
score = 1;
LblMenu.Visible = true;
LblStartStop.Visible = true;
}
}
}
|
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace RU.Tinkoff.Core.Nfc.Model {
// Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']"
[global::Android.Runtime.Register ("ru/tinkoff/core/nfc/model/ApplicationFileLocator", DoNotGenerateAcw=true)]
public partial class ApplicationFileLocator : global::Java.Lang.Object {
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("ru/tinkoff/core/nfc/model/ApplicationFileLocator", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (ApplicationFileLocator); }
}
protected ApplicationFileLocator (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/constructor[@name='ApplicationFileLocator' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public unsafe ApplicationFileLocator ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
return;
try {
if (((object) this).GetType () != typeof (ApplicationFileLocator)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor);
} finally {
}
}
static Delegate cb_getFirstRecord;
#pragma warning disable 0169
static Delegate GetGetFirstRecordHandler ()
{
if (cb_getFirstRecord == null)
cb_getFirstRecord = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetFirstRecord);
return cb_getFirstRecord;
}
static int n_GetFirstRecord (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.FirstRecord;
}
#pragma warning restore 0169
static Delegate cb_setFirstRecord_I;
#pragma warning disable 0169
static Delegate GetSetFirstRecord_IHandler ()
{
if (cb_setFirstRecord_I == null)
cb_setFirstRecord_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetFirstRecord_I);
return cb_setFirstRecord_I;
}
static void n_SetFirstRecord_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.FirstRecord = p0;
}
#pragma warning restore 0169
static IntPtr id_getFirstRecord;
static IntPtr id_setFirstRecord_I;
public virtual unsafe int FirstRecord {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='getFirstRecord' and count(parameter)=0]"
[Register ("getFirstRecord", "()I", "GetGetFirstRecordHandler")]
get {
if (id_getFirstRecord == IntPtr.Zero)
id_getFirstRecord = JNIEnv.GetMethodID (class_ref, "getFirstRecord", "()I");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.CallIntMethod (((global::Java.Lang.Object) this).Handle, id_getFirstRecord);
else
return JNIEnv.CallNonvirtualIntMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getFirstRecord", "()I"));
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='setFirstRecord' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("setFirstRecord", "(I)V", "GetSetFirstRecord_IHandler")]
set {
if (id_setFirstRecord_I == IntPtr.Zero)
id_setFirstRecord_I = JNIEnv.GetMethodID (class_ref, "setFirstRecord", "(I)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setFirstRecord_I, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setFirstRecord", "(I)V"), __args);
} finally {
}
}
}
static Delegate cb_getLastRecord;
#pragma warning disable 0169
static Delegate GetGetLastRecordHandler ()
{
if (cb_getLastRecord == null)
cb_getLastRecord = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetLastRecord);
return cb_getLastRecord;
}
static int n_GetLastRecord (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.LastRecord;
}
#pragma warning restore 0169
static Delegate cb_setLastRecord_I;
#pragma warning disable 0169
static Delegate GetSetLastRecord_IHandler ()
{
if (cb_setLastRecord_I == null)
cb_setLastRecord_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetLastRecord_I);
return cb_setLastRecord_I;
}
static void n_SetLastRecord_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.LastRecord = p0;
}
#pragma warning restore 0169
static IntPtr id_getLastRecord;
static IntPtr id_setLastRecord_I;
public virtual unsafe int LastRecord {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='getLastRecord' and count(parameter)=0]"
[Register ("getLastRecord", "()I", "GetGetLastRecordHandler")]
get {
if (id_getLastRecord == IntPtr.Zero)
id_getLastRecord = JNIEnv.GetMethodID (class_ref, "getLastRecord", "()I");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.CallIntMethod (((global::Java.Lang.Object) this).Handle, id_getLastRecord);
else
return JNIEnv.CallNonvirtualIntMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getLastRecord", "()I"));
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='setLastRecord' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("setLastRecord", "(I)V", "GetSetLastRecord_IHandler")]
set {
if (id_setLastRecord_I == IntPtr.Zero)
id_setLastRecord_I = JNIEnv.GetMethodID (class_ref, "setLastRecord", "(I)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setLastRecord_I, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setLastRecord", "(I)V"), __args);
} finally {
}
}
}
static Delegate cb_isOfflineAuthenticationAvailable;
#pragma warning disable 0169
static Delegate GetIsOfflineAuthenticationAvailableHandler ()
{
if (cb_isOfflineAuthenticationAvailable == null)
cb_isOfflineAuthenticationAvailable = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsOfflineAuthenticationAvailable);
return cb_isOfflineAuthenticationAvailable;
}
static bool n_IsOfflineAuthenticationAvailable (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.OfflineAuthenticationAvailable;
}
#pragma warning restore 0169
static Delegate cb_setOfflineAuthenticationAvailable_Z;
#pragma warning disable 0169
static Delegate GetSetOfflineAuthenticationAvailable_ZHandler ()
{
if (cb_setOfflineAuthenticationAvailable_Z == null)
cb_setOfflineAuthenticationAvailable_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetOfflineAuthenticationAvailable_Z);
return cb_setOfflineAuthenticationAvailable_Z;
}
static void n_SetOfflineAuthenticationAvailable_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OfflineAuthenticationAvailable = p0;
}
#pragma warning restore 0169
static IntPtr id_isOfflineAuthenticationAvailable;
static IntPtr id_setOfflineAuthenticationAvailable_Z;
public virtual unsafe bool OfflineAuthenticationAvailable {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='isOfflineAuthenticationAvailable' and count(parameter)=0]"
[Register ("isOfflineAuthenticationAvailable", "()Z", "GetIsOfflineAuthenticationAvailableHandler")]
get {
if (id_isOfflineAuthenticationAvailable == IntPtr.Zero)
id_isOfflineAuthenticationAvailable = JNIEnv.GetMethodID (class_ref, "isOfflineAuthenticationAvailable", "()Z");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isOfflineAuthenticationAvailable);
else
return JNIEnv.CallNonvirtualBooleanMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isOfflineAuthenticationAvailable", "()Z"));
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='setOfflineAuthenticationAvailable' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("setOfflineAuthenticationAvailable", "(Z)V", "GetSetOfflineAuthenticationAvailable_ZHandler")]
set {
if (id_setOfflineAuthenticationAvailable_Z == IntPtr.Zero)
id_setOfflineAuthenticationAvailable_Z = JNIEnv.GetMethodID (class_ref, "setOfflineAuthenticationAvailable", "(Z)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setOfflineAuthenticationAvailable_Z, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setOfflineAuthenticationAvailable", "(Z)V"), __args);
} finally {
}
}
}
static Delegate cb_getShortFileId;
#pragma warning disable 0169
static Delegate GetGetShortFileIdHandler ()
{
if (cb_getShortFileId == null)
cb_getShortFileId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetShortFileId);
return cb_getShortFileId;
}
static int n_GetShortFileId (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.ShortFileId;
}
#pragma warning restore 0169
static Delegate cb_setShortFileId_I;
#pragma warning disable 0169
static Delegate GetSetShortFileId_IHandler ()
{
if (cb_setShortFileId_I == null)
cb_setShortFileId_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetShortFileId_I);
return cb_setShortFileId_I;
}
static void n_SetShortFileId_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Nfc.Model.ApplicationFileLocator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.ShortFileId = p0;
}
#pragma warning restore 0169
static IntPtr id_getShortFileId;
static IntPtr id_setShortFileId_I;
public virtual unsafe int ShortFileId {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='getShortFileId' and count(parameter)=0]"
[Register ("getShortFileId", "()I", "GetGetShortFileIdHandler")]
get {
if (id_getShortFileId == IntPtr.Zero)
id_getShortFileId = JNIEnv.GetMethodID (class_ref, "getShortFileId", "()I");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.CallIntMethod (((global::Java.Lang.Object) this).Handle, id_getShortFileId);
else
return JNIEnv.CallNonvirtualIntMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getShortFileId", "()I"));
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.model']/class[@name='ApplicationFileLocator']/method[@name='setShortFileId' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("setShortFileId", "(I)V", "GetSetShortFileId_IHandler")]
set {
if (id_setShortFileId_I == IntPtr.Zero)
id_setShortFileId_I = JNIEnv.GetMethodID (class_ref, "setShortFileId", "(I)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setShortFileId_I, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setShortFileId", "(I)V"), __args);
} finally {
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class gate_mechanism : MonoBehaviour {
public ParticleEmitter gate_effect;
public GameObject gate_sprite;
public Light gate_light;
public GameObject teleporter;
public mission1 m;
public bool gates_open=false;
public void ApplyDamage(Vector4 v4) {
gate_effect.emit=true;
gate_sprite.SetActive(true);
gate_light.enabled=true;
teleporter.SetActive(true);
if (!gates_open) {m.SendShip();gates_open=true;}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeoAPI.Extensions.Feature;
using NUnit.Framework;
using Rhino.Mocks;
using SharpMap.Data.Providers;
namespace SharpMap.Tests.Data.Providers
{
[TestFixture]
public class DataTableFeatureProviderTest
{
readonly MockRepository mocks = new MockRepository();
[Test]
public void Contains()
{
var provider = new DataTableFeatureProvider("LINESTRING(20 20,40 40)");
Assert.IsFalse(provider.Contains(mocks.Stub<IFeature>()));
Assert.IsTrue(provider.Contains((IFeature) provider.Features[0]));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using HtmlAgilityPack;
using Test;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;
using System.IO;
namespace ArchosAPI
{
public class DepartmentListControl : System.Windows.Forms.ApplicationContext
{
int navigationCounter;
int timeout = 0;
private Thread thrd;
private WebBrowser ieBrowser;
private ScriptCallback scriptCallback;
public List<HtmlNode> deptNodes;
public List<string> deptList { get; set; }
/// <summary>
/// This is deprecated, this needs to be converted to using the new HttpRrquest method as WinForms really shouldnt be used in a web session.
/// </summary>
public DepartmentListControl()
{
deptNodes = new List<HtmlNode>();
thrd = new Thread(new ThreadStart(
delegate
{
Init();
System.Windows.Forms.Application.Run(this);
}));
thrd.DisableComObjectEagerCleanup();
// set thread to STA state before starting
thrd.SetApartmentState(ApartmentState.STA);
thrd.Start();
thrd.Join();
}
private void Init()
{
try
{
scriptCallback = new ScriptCallback(this);
// create a WebBrowser control
ieBrowser = new WebBrowser();
// set the location of script callback functions
ieBrowser.ObjectForScripting = scriptCallback;
// set WebBrowser event handle
ieBrowser.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(
IEBrowser_DocumentCompleted);
ieBrowser.Navigating += new
WebBrowserNavigatingEventHandler(IEBrowser_Navigating);
// initialise the navigation counter
navigationCounter = 0;
ieBrowser.Navigate(
"http://catalog.uta.edu/coursedescriptions/");
}
catch (Exception ex)
{
thrd.Abort();
this.Dispose();
}
}
// Navigating event handle
void IEBrowser_Navigating(object sender,
WebBrowserNavigatingEventArgs e)
{
// navigation count increases by one
navigationCounter++;
}
// DocumentCompleted event handle
void IEBrowser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (ieBrowser.DocumentTitle == "Course Descriptions < University of Texas Arlington")
{
var html = ((dynamic)ieBrowser.Document.DomDocument).documentElement.outerHTML;
var doc = new HtmlDocument();
doc.LoadHtml(html);
FindNode(doc.GetElementbyId("content"), "class", "sitemaplink");
deptList = deptNodes.Select(x => x.InnerText).ToList();
thrd.Abort();
}
}
catch (Exception ex)
{
thrd.Abort();
this.Dispose();
}
}
public void FindNode(HtmlNode node, string name, string value)
{
try
{
if (node.Attributes.Any(x => x.Name != null && x.Name.ToLower().Contains(name) && x.Value.ToLower().Contains(value)))
{
deptNodes.Add(node);
for (int i = 0; i < node.ChildNodes.Count; i++)
FindNode(node.ChildNodes.ElementAt(i), name, value);
}
else
for (int i = 0; i < node.ChildNodes.Count; i++)
FindNode(node.ChildNodes.ElementAt(i), name, value);
return;
}
catch(Exception ex)
{
return;
}
}
/// <summary>
/// class to hold the functions called
/// by script codes in the WebBrowser control
/// </summary>
[System.Runtime.InteropServices.ComVisible(true)]
public class ScriptCallback
{
DepartmentListControl owner;
public ScriptCallback(DepartmentListControl owner)
{
this.owner = owner;
}
// callback function to get the content
// of page in the WebBrowser control
public void getHtmlResult(int count)
{
// unequal means the content is not stable
if (owner.navigationCounter != count) return;
}
}
private void htmlTimerTick(object sender, EventArgs e)
{
}
}
}
|
namespace FamousQuoteQuiz.Api.Models
{
public class DeleteQuoteModel
{
public int Id { get; set; }
}
}
|
// talis.xivplugin.twintania
// SoundHelper.cs
using FFXIVAPP.Common.Helpers;
using FFXIVAPP.Common.Utilities;
using NAudio.Wave;
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using talis.xivplugin.twintania.Properties;
namespace talis.xivplugin.twintania.Helpers
{
internal static class SoundHelper
{
[DllImport("winmm.dll")]
public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
private static Dictionary<string, Tuple<IWavePlayer, WaveChannel32>> soundFiles = new Dictionary<string, Tuple<IWavePlayer, WaveChannel32>>();
private static WaveChannel32 loadStream(string path)
{
if (path.EndsWith("mp3"))
return new WaveChannel32(new Mp3FileReader(path));
else if (path.EndsWith("wav"))
return new WaveChannel32(new WaveFileReader(path));
else
throw new Exception("Invalid sound file " + path);
}
public static void Play(string file, int volume)
{
try
{
if(Settings.Default.TwintaniaHPWidgetUseNAudio)
{
IWavePlayer player;
WaveChannel32 stream;
if(Settings.Default.TwintaniaHPWidgetUseSoundCaching)
{
Tuple<IWavePlayer, WaveChannel32> value;
if (soundFiles.TryGetValue(file, out value))
{
Logging.Log(LogManager.GetCurrentClassLogger(), "Loaded sound file " + file + " from dictionary", new Exception());
player = value.Item1;
stream = value.Item2;
stream.Position = 0;
}
else
{
Logging.Log(LogManager.GetCurrentClassLogger(), "Stored sound file " + Constants.BaseDirectory + file + " into dictionary", new Exception());
player = new WaveOut();
stream = loadStream(Constants.BaseDirectory + file);
player.Init(stream);
soundFiles.Add(file, Tuple.Create(player, stream));
}
}
else
{
player = new WaveOut();
stream = loadStream(Constants.BaseDirectory + file);
player.Init(stream);
}
stream.Volume = (float)volume / 100;
player.Play();
player.PlaybackStopped += delegate
{
player.Dispose();
};
}
else
{
int NewVolume = ((ushort.MaxValue / 100) * volume);
uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
SoundPlayerHelper.Play(Constants.BaseDirectory, file);
}
}
catch (Exception ex)
{
Logging.Log(LogManager.GetCurrentClassLogger(), "", ex);
}
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
namespace StrategyGame
{
public class RocketForce : Force
{
public RocketForce(GameTime gameTime)
{
Id = ForcesType.RocketForce;
Hp = ForceParametrsPack.Hp[(int)Id];
Range = 4;
Speed = 40;
Armor = 0.8;
AtackPoints = 20;
Accuracy = 0.5;
Texture = TexturePack.rocketForce;
ReloadTime = 3.0;
IsReloading = true;
GameEventEngine.Add(new GameEventDelayed(() => { IsReloading = false; }, ReloadTime));
}
public override void Atack(Player player, Force enemyForce,GameTime gameTime)
{
if (!IsReloading)
{
Missile missile = new Missile(player,enemyForce, AtackPoints, Random.NextDouble() <= Accuracy,
new Point((int)(2 * (500 - PosX) * (1.5 - (double)player.PlayerID) + 500),
(int)Force.PosY + (int)(170 * 0.2)),
new Point((int)(2 * (500 - enemyForce.PosX) * ((double)player.PlayerID - 1.5) + 500),
(int)Force.PosY + (int)(170 * 0.2)));
GameEffectsEngine.Add(missile);
Missile missile2 = new Missile(player,enemyForce, AtackPoints, Random.NextDouble() <= Accuracy,
new Point((int)(2 * (500 - PosX) * (1.5 - (double)player.PlayerID) + 500),
(int)Force.PosY + (int)(170 * 0.2)),
new Point((int)(2 * (500 - enemyForce.PosX) * ((double)player.PlayerID - 1.5) + 500),
(int)Force.PosY + (int)(170 * 0.2)));
GameEventEngine.Add(new GameEventDelayed(() => { GameEffectsEngine.Add(missile2); }, 0.1));
GameEventEngine.Add(new GameEventDelayed(() => { IsReloading = false; }, ReloadTime));
IsReloading = true;
}
}
public override void Atack(Player player, GameTime gameTime)
{
if (!IsReloading)
{
MissileBase missile = new MissileBase(player, AtackPoints, Random.NextDouble() <= Accuracy,
new Point((int)(2 * (500 - PosX) * (1.5 - (double)player.PlayerID) + 500),
(int)Force.PosY + (int)(170 * 0.2)),
new Point((int)(2 * (500 - player.PlayerBase.PosX) * ((double)player.PlayerID - 1.5) + 500),
(int)Force.PosY + (int)(170 * 0.2)));
GameEffectsEngine.Add(missile);
MissileBase missile2 = new MissileBase(player, AtackPoints, Random.NextDouble() <= Accuracy,
new Point((int)(2 * (500 - PosX) * (1.5 - (double)player.PlayerID) + 500),
(int)Force.PosY + (int)(170 * 0.2)),
new Point((int)(2 * (500 - player.PlayerBase.PosX) * ((double)player.PlayerID - 1.5) + 500),
(int)Force.PosY + (int)(170 * 0.2)));
GameEventEngine.Add(new GameEventDelayed(() => { GameEffectsEngine.Add(missile2); }, 0.1));
GameEventEngine.Add(new GameEventDelayed(() => { IsReloading = false; }, ReloadTime));
IsReloading = true;
}
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace gView.Framework.system
{
public class XsdSchemaSerializer<T>
{
public T Deserialize(Stream stream)
{
// avoid errors => DTD parsing is not allowed per default:
// https://stackoverflow.com/questions/13854068/dtd-prohibited-in-xml-document-exception
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
settings.MaxCharactersFromEntities = 1024;
using (XmlReader xmlReader = XmlReader.Create(stream, settings))
{
XmlSerializer ser = new XmlSerializer(typeof(T));
return (T)ser.Deserialize(xmlReader);
}
}
public T FromString(string xml, global::System.Text.Encoding encoding)
{
MemoryStream ms = new MemoryStream();
byte[] buffer = encoding.GetBytes(xml);
ms.Write(buffer, 0, buffer.Length);
ms.Position = 0;
return Deserialize(ms);
}
public T FromUrl(string url, WebProxy proxy)
{
HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create(url);
if (proxy != null)
{
wReq.Proxy = proxy;
}
wReq.Timeout = 360000;
HttpWebResponse wresp = (HttpWebResponse)wReq.GetResponse();
int Bytes2Read = 3500000;
Byte[] b = new Byte[Bytes2Read];
DateTime t1 = DateTime.Now;
Stream stream = wresp.GetResponseStream();
MemoryStream memStream = new MemoryStream();
while (Bytes2Read > 0)
{
int len = stream.Read(b, 0, Bytes2Read);
if (len == 0)
{
break;
}
memStream.Write(b, 0, len);
}
memStream.Position = 0;
string xml = Encoding.UTF8.GetString(memStream.GetBuffer()).Trim(' ', '\0').Trim();
memStream.Close();
memStream.Dispose();
return FromString(xml, global::System.Text.Encoding.UTF8);
}
public string Serialize(T o, XmlSerializerNamespaces ns)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
UTF8Encoding utf8e = new UTF8Encoding();
XmlTextWriter xmlSink = new XmlTextWriter(ms, utf8e);
xmlSink.Formatting = Formatting.Indented;
if (ns != null)
{
ser.Serialize(xmlSink, o, ns);
}
else
{
ser.Serialize(xmlSink, o);
}
byte[] utf8EncodedData = ms.ToArray();
return utf8e.GetString(utf8EncodedData);
}
public string Serialize(T o)
{
return Serialize(o, null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Brawl_Net
{
class Player
{
public string ip = "";
public Character character = new Character();
public Player(string setip)
{
ip = setip;
}
}
class Character
{
Random r = new Random();
bool dead = false;
string name = "";
int hpMax = 100;
int hp = 100;
int staminaMax = 100;
int stamina = 100;
int strengh = 10;
int psyce = 10;
int endurance = 10;
int agility = 10;
int charisma = 10;
int luck = 10;
public Character()
{
GenerateCharacter(50);
}
public void GenerateCharacter(int powerLevel = 0)
{
if (powerLevel <= 0)
{
strengh = r.Next(3, 18);
psyce = r.Next(3, 18);
endurance = r.Next(3, 18);
agility = r.Next(3, 18);
charisma = r.Next(3, 18);
luck = r.Next(3, 18);
hpMax = hp = r.Next(endurance, endurance * 10);
staminaMax = stamina = r.Next(agility, agility * 10);
} else //66
{
int[] tempstats = new int[6] { 3, 3, 3, 3, 3, 3};
while (powerLevel > 0)
{
tempstats[r.Next(0, 6)] += 1;
powerLevel--;
}
strengh = tempstats[0];
psyce = tempstats[1];
endurance = tempstats[2];
agility = tempstats[3];
charisma = tempstats[4];
luck = tempstats[5];
hpMax = hp = endurance * 10;
staminaMax = staminaMax = agility * 10;
}
}
public virtual int Attack()
{
int crit = 1;
if (r.Next(100) < luck)
{
crit = 2;
}
return strengh * crit;
}
public virtual int Damage(int damageIn)
{
int crit = 1;
if (r.Next(100) < luck)
{
crit = 2;
}
int damageTotal = damageIn * 10 / (endurance * crit);
hp -= damageTotal;
if (hp <= 0)
{
dead = true;
}
return damageTotal;
}
public virtual void Action()
{
}
public string WriteStats()
{
return "" +
"Health : " + hp + "/" + hpMax + "\n" +
"Stamina : " + stamina + "/" + staminaMax + "\n" +
"Strenght : " + strengh + "\n" +
"Psyce : " + psyce + "\n" +
"Endurance: " + endurance + "\n" +
"Agility : " + agility + "\n" +
"Charisma : " + charisma + "\n" +
"Luck : " + luck;
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Vlc.DotNet.Core.Interops.Signatures
{
/// <summary>
/// Set the meta of the media (this function will not save the meta, call SaveMediaMeta in order to save the meta)
/// </summary>
[LibVlcFunction("libvlc_media_set_meta")]
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void SetMediaMetadata(IntPtr mediaInstance, MediaMetadatas meta, Utf8StringHandle value);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Dto.Dto.SearchTravel
{
public class FlightInputs
{
public string OriginLocationCode;
public string DestinationLocationCode;
public string FlightNumber;
public string CarrierCode;
public string DepartureDateTimeOffset;
public string ArrivalDateTimeOffset;
public string FareClassType;
public string GdsProvider;
}
}
|
using System.Collections.Generic;
namespace TpNoteDesignPatternsCSharp.BLL.Model
{
public class PersonnageBuilderWeb : PersonnageBuilder
{
public PersonnageBuilderWeb()
{
personnage = new PersonnageBLL();
}
public override PersonnageBuilder BuildListEquipement(List<IEquipement> equipements)
{
personnage.Equipements = new List<IEquipement>();
return this;
}
}
}
|
#region MIT License
/*
* Copyright (c) 2009-2011 University of Jyväskylä, Department of Mathematical
* Information Technology.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
/*
* Authors: Tomi Karppinen, Tero Jäntti
*/
using System;
using System.Collections.Generic;
using Matrix = System.Numerics.Matrix4x4;
namespace Jypeli
{
/// <summary>
/// Painonappi.
/// </summary>
public class PushButton : Label
{
internal enum State
{
Released,
Hover,
LeftPressed,
RightPressed,
Selected
}
private ShapeCache leftSideShape;
private ShapeCache topSideShape;
private ShapeCache RightSideShape;
private ShapeCache BottomSideShape;
private ShapeCache leftSidePressedShape;
private ShapeCache topSidePressedShape;
private ShapeCache RightSidePressedShape;
private ShapeCache BottomSidePressedShape;
private Image imageReleased;
private Image imagePressed;
private Image imageHover;
private State state = State.Released;
private bool isPressed { get { return state == State.LeftPressed || state == State.RightPressed; } }
private Color releasedColor;
private Color hoverColor;
private Color pressedColor;
private Color selectedColor;
/// <summary>
/// Kaikkien tulevien nappuloiden oletusväri
/// </summary>
public static Color defaultColor = new Color(29, 41, 81, 223);
/// <summary>
/// Kaikkien tulevien nappuloiden tekstin oletusväri
/// </summary>
public static Color defaultTextColor = new Color(250, 250, 250, 240);
/// <summary>
/// Kuva kun nappi on vapautettu.
/// </summary>
public Image ImageReleased
{
get { return imageReleased; }
set
{
imageReleased = value;
if (!isPressed && !Game.Mouse.IsCursorOn(this))
Image = value;
}
}
/// <summary>
/// Kuva kun nappi on alaspainettuna.
/// </summary>
public Image ImagePressed
{
get { return imagePressed; }
set
{
imagePressed = value;
if (isPressed)
Image = value;
}
}
/// <summary>
/// Kuva kun hiiren kursori on napin päällä.
/// </summary>
public Image ImageHover
{
get { return imageHover; }
set
{
imageHover = value;
if (!isPressed && Game.Mouse.IsCursorOn(this))
Image = value;
}
}
/// <summary>
/// Nappulan koko
/// </summary>
public override Vector Size
{
get
{
return base.Size;
}
set
{
base.Size = value;
InitializeShape();
}
}
/// <summary>
/// Nappulan oletusväri.
/// Asettaa myös <c>hoverColor</c>, <c>selectedColor</c> ja <c>pressedColor</c> -kenttien arvot.
/// Jos haluat itse määrittää em. tilojen värit, aseta ne tämän kentän arvon asettamisen jälkeen.
/// </summary>
public override Color Color
{
get
{
return base.Color;
}
set
{
releasedColor = value;
hoverColor = Color.Lighter(value, 40);
selectedColor = Color.Lighter(value, 40);
pressedColor = Color.Darker(value, 40);
base.Color = value;
}
}
/// <summary>
/// Nappulan väri kun hiiri viedään sen päälle.
/// </summary>
public Color HoverColor
{
get
{
return hoverColor;
}
set
{
hoverColor = value;
}
}
/// <summary>
/// Nappulan väri kun sitä klikataan.
/// </summary>
public Color PressedColor
{
get
{
return pressedColor;
}
set
{
pressedColor = value;
}
}
/// <summary>
/// Nappulan väri kun se on valittuna, esimerkiksi <c>MultiSelectWindow</c>issa.
/// </summary>
public Color SelectedColor
{
get
{
return selectedColor;
}
set
{
selectedColor = value;
}
}
/// <summary>
/// Tapahtuu kun nappia on painettu.
/// </summary>
public event Action Clicked;
/// <summary>
/// Tapahtuu kun nappia on painettu oikealla hiirenpainikkeella.
/// </summary>
public event Action RightClicked;
private void TouchHover(Touch touch)
{
SetState(State.Hover);
}
private void TouchRelease(Touch touch)
{
if (Game.TouchPanel.NumTouches <= 1)
SetState(State.Released);
}
private void TouchClick(Touch touch)
{
Click();
}
/// <summary>
/// Luo uuden painonapin.
/// </summary>
/// <param name="text">Napin teksti.</param>
public PushButton(string text)
: base(text)
{
Initialize();
}
/// <summary>
/// Luo uuden painonapin.
/// </summary>
/// <param name="image">Napin kuva.</param>
public PushButton(Image image)
: base(image)
{
Initialize();
this.Image = image;
}
/// <summary>
/// Luo uuden painonapin.
/// </summary>
/// <param name="width">Leveys.</param>
/// <param name="height">Korkeus.</param>
public PushButton(double width, double height)
: base(width, height)
{
Initialize();
}
private void Initialize()
{
InitializeMargins();
InitializeShape();
Color = defaultColor;
TextColor = defaultTextColor;
CapturesMouse = true;
AddedToGame += InitializeControls;
}
private void InitializeMargins()
{
XMargin = 15;
YMargin = 10;
}
/// <summary>
/// Luo uuden painonapin omalla kuvalla.
/// </summary>
/// <param name="width">Leveys.</param>
/// <param name="height">Korkeus.</param>
/// <param name="image">Kuva.</param>
public PushButton(double width, double height, Image image)
: this(width, height)
{
this.Image = image;
}
/// <summary>
/// Luo uuden painonapin.
/// </summary>
/// <param name="width">Leveys.</param>
/// <param name="height">Korkeus.</param>
/// <param name="text">Teksti.</param>
public PushButton(double width, double height, string text)
: base(width, height, text)
{
Initialize();
}
private void InitializeControls()
{
var l1 = Game.Mouse.ListenOn(this, MouseButton.Left, ButtonState.Pressed, SetState, null, State.LeftPressed).InContext(this);
var l2 = Game.Mouse.ListenOn(this, MouseButton.Left, ButtonState.Released, Release, null).InContext(this);
var l3 = Game.Mouse.Listen(MouseButton.Left, ButtonState.Released, Release, null).InContext(this);
var l4 = Game.Mouse.ListenOn(this, MouseButton.Right, ButtonState.Pressed, SetState, null, State.RightPressed).InContext(this);
var l5 = Game.Mouse.ListenOn(this, MouseButton.Right, ButtonState.Released, Release, null).InContext(this);
var l6 = Game.Mouse.Listen(MouseButton.Right, ButtonState.Released, Release, null).InContext(this);
var l7 = Game.Mouse.ListenMovement(1.0, CheckHover, null).InContext(this);
var l8 = Game.Instance.TouchPanel.ListenOn(this, ButtonState.Down, TouchHover, null).InContext(this);
var l9 = Game.Instance.TouchPanel.ListenOn(this, ButtonState.Released, TouchRelease, null).InContext(this);
var l10 = Game.Instance.TouchPanel.Listen(ButtonState.Released, TouchRelease, null).InContext(this);
var l11 = Game.Instance.TouchPanel.ListenOn(this, ButtonState.Released, TouchClick, null).InContext(this);
associatedListeners.AddItems(l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11);
}
private void InitializeShape()
{
//double edgeSize = Math.Min( Width, Height ) / 5;
double edgeSize = 5;
double relativeHorizontalSize = edgeSize / Width;
double relativeVerticalSize = edgeSize / Height;
Vector topLeftOuter = new Vector(-0.5, 0.5);
Vector topLeftInner = new Vector(-0.5 + relativeHorizontalSize, 0.5 - relativeVerticalSize);
Vector bottomLeftOuter = new Vector(-0.5, -0.5);
Vector bottomLeftInner = new Vector(-0.5 + relativeHorizontalSize, -0.5 + relativeVerticalSize);
Vector topRightOuter = new Vector(0.5, 0.5);
Vector topRightInner = new Vector(0.5 - relativeHorizontalSize, 0.5 - relativeVerticalSize);
Vector bottomRightOuter = new Vector(0.5, -0.5);
Vector bottomRightInner = new Vector(0.5 - relativeHorizontalSize, -0.5 + relativeVerticalSize);
IndexTriangle[] triangles = { new IndexTriangle(0, 1, 2), new IndexTriangle(1, 3, 2), };
Vector[] leftSideVertices = { topLeftOuter, topLeftInner, bottomLeftOuter, bottomLeftInner, };
Vector[] topSideVertices = { topLeftOuter, topRightOuter, topLeftInner, topRightInner, };
Vector[] rightSideVertices = { topRightOuter, bottomRightOuter, topRightInner, bottomRightInner, };
Vector[] bottomSideVertices = { bottomRightOuter, bottomLeftOuter, bottomRightInner, bottomLeftInner, };
leftSideShape = new ShapeCache(leftSideVertices, triangles);
topSideShape = new ShapeCache(topSideVertices, triangles);
RightSideShape = new ShapeCache(rightSideVertices, triangles);
BottomSideShape = new ShapeCache(bottomSideVertices, triangles);
const double scale = 1.4;
topLeftOuter = new Vector(-0.5, 0.5);
topLeftInner = new Vector(-0.5 + relativeHorizontalSize / scale, 0.5 - relativeVerticalSize / scale);
bottomLeftOuter = new Vector(-0.5, -0.5);
bottomLeftInner = new Vector(-0.5 + relativeHorizontalSize / scale, -0.5 + relativeVerticalSize * scale);
topRightOuter = new Vector(0.5, 0.5);
topRightInner = new Vector(0.5 - relativeHorizontalSize * scale, 0.5 - relativeVerticalSize / scale);
bottomRightOuter = new Vector(0.5, -0.5);
bottomRightInner = new Vector(0.5 - relativeHorizontalSize * scale, -0.5 + relativeVerticalSize * scale);
Vector[] leftSidePressedVertices = { topLeftOuter, topLeftInner, bottomLeftOuter, bottomLeftInner, };
Vector[] topSidePressedVertices = { topLeftOuter, topRightOuter, topLeftInner, topRightInner, };
Vector[] rightSidePressedVertices = { topRightOuter, bottomRightOuter, topRightInner, bottomRightInner, };
Vector[] bottomSidePressedVertices = { bottomRightOuter, bottomLeftOuter, bottomRightInner, bottomLeftInner, };
leftSidePressedShape = new ShapeCache(leftSidePressedVertices, triangles);
topSidePressedShape = new ShapeCache(topSidePressedVertices, triangles);
RightSidePressedShape = new ShapeCache(rightSidePressedVertices, triangles);
BottomSidePressedShape = new ShapeCache(bottomSidePressedVertices, triangles);
}
internal void SetState(State state)
{
this.state = state;
switch (state)
{
case State.Hover:
base.Color = hoverColor;
if (ImageHover != null)
Image = ImageHover;
break;
case State.RightPressed:
case State.LeftPressed:
base.Color = pressedColor;
if (ImagePressed != null)
ImagePressed = ImagePressed;
break;
case State.Selected:
base.Color = selectedColor;
break;
default:
base.Color = releasedColor;
if (ImageReleased != null)
Image = ImageReleased;
break;
}
}
/// <summary>
/// Suoritetaan, kun nappulaa klikattiin hiiren vasemmalla näppäimellä
/// </summary>
public void Click()
{
if (Clicked != null)
Clicked();
}
/// <summary>
/// Suoritetaan, kun nappulaa klikattiin hiiren oikealla näppäimellä
/// </summary>
public void RightClick()
{
if (RightClicked != null)
RightClicked();
}
/// <summary>
/// Lisää pikanäppäimen napille.
/// </summary>
/// <param name="key">Näppäin</param>
public Listener AddShortcut(Key key)
{
return Jypeli.Game.Instance.Keyboard.Listen(key, ButtonState.Pressed, Click, null).InContext(this);
}
/// <summary>
/// Lisää pikanäppäimen kaikille ohjaimille.
/// </summary>
/// <param name="button">Näppäin</param>
public List<Listener> AddShortcut(Button button)
{
var listeners = new List<Listener>(Game.GameControllers.Count);
Game.Instance.GameControllers.ForEach(c => listeners.Add(AddShortcut(c, button)));
return listeners;
}
/// <summary>
/// Lisää pikanäppäimen yhdelle ohjaimelle.
/// </summary>
/// <param name="player">Peliohjaimen indeksi 0-3</param>
/// <param name="button">Näppäin</param>
public Listener AddShortcut(int player, Button button)
{
return AddShortcut(Game.Instance.GameControllers[player], button);
}
/// <summary>
/// Lisää pikanäppäimen yhdelle ohjaimelle.
/// </summary>
/// <param name="controller">Peliohjain</param>
/// <param name="button">Näppäin</param>
public Listener AddShortcut(GamePad controller, Button button)
{
return controller.Listen(button, ButtonState.Pressed, Click, null).InContext(this);
}
private void Release()
{
bool wasLeft = state == State.LeftPressed;
bool wasRight = state == State.RightPressed;
if (Game.Mouse.IsCursorOn(this))
{
SetState(State.Hover);
}
else
{
SetState(State.Released);
return;
}
if (wasLeft)
Click();
else if (wasRight)
RightClick();
}
private void CheckHover()
{
if (isPressed || state == State.Selected)
return; // Ehkä voisi olla jonkinlainen lisäkorostus jos hiiri on päällä ja nappula on valittuna samanaikaisesti...
SetState(Game.Mouse.IsCursorOn(this) ? State.Hover : State.Released);
}
/// <inheritdoc/>
public override void Draw(Matrix parentTransformation, Matrix transformation)
{
base.Draw(parentTransformation, transformation);
if (Image == null)
{
Color color1 = Color.Lighter(Color, 20);
Color color2 = Color.Darker(Color, 20);
ShapeCache left = leftSideShape;
ShapeCache top = topSideShape;
ShapeCache right = RightSideShape;
ShapeCache bottom = BottomSideShape;
if (isPressed)
{
color1 = Color.Darker(Color, 20);
color2 = Color.Lighter(Color, 20);
left = leftSidePressedShape;
top = topSidePressedShape;
right = RightSidePressedShape;
bottom = BottomSidePressedShape;
}
Renderer.DrawFilledShape(left, ref transformation, Position, Size, (float)Angle.Radians, color1);
Renderer.DrawFilledShape(top, ref transformation, Position, Size, (float)Angle.Radians, color1);
Renderer.DrawFilledShape(right, ref transformation, Position, Size, (float)Angle.Radians, color2);
Renderer.DrawFilledShape(bottom, ref transformation, Position, Size, (float)Angle.Radians, color2);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace learn_180328_T
{
class Program
{
static void Main(string[] args)
{
Store s = new Store();
int[] num = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
string[] str = new string[]{ "a", "b" };
s.StoreNum<int>(num);
s.StoreNum<string>(str);
Console.ReadKey();
}
}
class Store
{
public void StoreNum<T>(T[] t)
{
T[] num=new T[10];
int i = 0;
foreach(T n in t)
{
Console.WriteLine(n);
i++;
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Portal : MonoBehaviour {
public Vector3 swirlPoint = new Vector3(0,-5,0);
public Vector3 landPoint = new Vector3(0,-15,0);
public float beamSpeed = 3.0f;
public WorldGroup WorldGroup;
public void SetColor(Color color)
{
this.GetComponentInChildren<Renderer>().material.color = 0.65f*color;
this.transform.Search("PSOuter").GetComponentInChildren<Renderer>().material.SetColor("_TintColor", 0.65f*color);
}
Dictionary<RobType,List<Robot>> robots = new Dictionary<RobType,List<Robot>>();
Dictionary<RobType,UnityEngine.UI.Text> txtNum = new Dictionary<RobType,UnityEngine.UI.Text>();
public void MoveUp(Team team, RobType rt)
{
var w = WorldGroup.World;
Robot robot = w
.FindRobots()
.Where(r => r.entity.Team == team && r.robType == rt)
.RandomSample();
if(!robot) {
return;
}
robot.GetComponent<Entity>().MoveToSpace();
System.Action<Robot> final = r => {
robots[rt].Add(robot);
UpdateNumText(rt);
};
StartCoroutine("Beam",
new object[3]{ robot, transform.position + swirlPoint, final});
}
void UpdateNumText(RobType rt)
{
txtNum[rt].text = string.Format("{0}", robots[rt].Count);
}
public void MoveDown(Team team, RobType rt)
{
Robot robot = robots[rt]
.Where(r => r.entity.Team == team)
.RandomSample();
if(!robot) {
return;
}
robots[rt].Remove(robot);
UpdateNumText(rt);
System.Action<Robot> final = r => {
robot.GetComponent<Entity>().MoveToWorld(WorldGroup.World);
};
StartCoroutine("Beam",
new object[3]{ robot, transform.position + swirlPoint, final});
}
public Robot RemoveRobot(RobType rt) {
Robot r = robots[rt].RandomSample();
if(!r) {
return r;
}
robots[rt].Remove(r);
UpdateNumText(rt);
return r;
}
public void AddRobot(Robot r) {
robots[r.robType].Add(r);
UpdateNumText(r.robType);
}
IEnumerator Beam(object[] p)
{
Robot robot = (Robot)p[0];
Vector3 target = (Vector3)p[1];
System.Action<Robot> final = (System.Action<Robot>)p[2];
while(true) {
Vector3 pos = robot.transform.position;
Vector3 dir = target - pos;
if(dir.magnitude < 1.0f) {
break;
}
pos += Time.deltaTime * beamSpeed * dir.normalized;
robot.transform.position = pos;
yield return null;
}
final(robot);
}
// Use this for initialization
void Start () {
robots[RobType.HAUL] = new List<Robot>();
robots[RobType.LASER] = new List<Robot>();
GetComponentInChildren<UnityEngine.Canvas>().worldCamera = WorldSelector.Singleton.camera;
txtNum[RobType.HAUL] = this.transform.Search("TextHaul").GetComponent<UnityEngine.UI.Text>();
var btnHaulUp = this.transform.Search("ButtonHaulUp").GetComponent<UnityEngine.UI.Button>();
btnHaulUp.onClick.AddListener(() => MoveUp(Globals.Singleton.playerTeam, RobType.HAUL));
var btnHaulDown = this.transform.Search("ButtonHaulDown").GetComponent<UnityEngine.UI.Button>();
btnHaulDown.onClick.AddListener(() => MoveDown(Globals.Singleton.playerTeam, RobType.HAUL));
txtNum[RobType.LASER] = this.transform.Search("TextLaser").GetComponent<UnityEngine.UI.Text>();
var btnLaserUp = this.transform.Search("ButtonLaserUp").GetComponent<UnityEngine.UI.Button>();
btnLaserUp.onClick.AddListener(() => MoveUp(Globals.Singleton.playerTeam, RobType.LASER));
var btnLaserDown = this.transform.Search("ButtonLaserDown").GetComponent<UnityEngine.UI.Button>();
btnLaserDown.onClick.AddListener(() => MoveDown(Globals.Singleton.playerTeam, RobType.LASER));
}
// Update is called once per frame
void Update () {
}
void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(transform.position + swirlPoint, 0.5f);
Gizmos.color = Color.black;
Gizmos.DrawWireSphere(transform.position + landPoint, 0.5f);
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Wallet.Win.Common;
using FiiiCoin.Wallet.Win.Models.UiModels;
namespace FiiiCoin.Wallet.Win.ViewModels.ShellPages
{
public class MessageViewModel : PopupShellBase
{
protected override string GetPageName()
{
return Pages.MessagePage;
}
private MessagePageData _messagePageData;
public MessagePageData MessagePageData
{
get { return _messagePageData; }
set { _messagePageData = value; RaisePropertyChanged("MessagePageData"); }
}
protected override void OnLoaded()
{
MessagePageData = new MessagePageData();
base.OnLoaded();
RegeistMessenger<MessagePageData>(OnRequestMsg);
}
protected override void Refresh()
{
MessagePageData = new MessagePageData();
}
void OnRequestMsg(MessagePageData messagePageData)
{
MessagePageData = messagePageData;
}
public override void OnOkClick()
{
base.OnOkClick();
MessagePageData.InvokeOkCallBack();
}
public override void OnCancelClick()
{
base.OnCancelClick();
MessagePageData.InvokeCancelCallBack();
}
}
} |
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
namespace NuGetPackageVisualizer.PackagesFile
{
internal class ProjectJsonProcessor : IPackageFileProcessor
{
public IEnumerable<DependencyViewModel> Packages(string filePath)
{
JObject dependencies ;
using (var input = File.OpenText(filePath))
{
var projects = JObject.Parse(input.ReadToEnd());
dependencies = (JObject) projects["dependencies"];
}
foreach (var package in dependencies.Properties())
{
var id = package.Name;
var version = (string)package.Value;
if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(version)) continue;
yield return new DependencyViewModel {NugetId = id, Version = version};
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : ReusableObject
{
protected float m_speed = 60;
public override void OnSpawn()
{
}
public override void OnUnSpawn()
{
transform.localEulerAngles = Vector3.zero;
}
private void Update()
{
transform.Rotate(0, m_speed * Time.deltaTime, 0);
}
public virtual void HitPlayer(Transform pos)
{
}
}
|
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.Net;
namespace WindowsFormsApplication1
{
public partial class tc_ile_sonuc : Form
{
public tc_ile_sonuc()
{
InitializeComponent();
}
private void tc_ile_sonuc_Load(object sender, EventArgs e)
{
ws_Adana_Lab_Entegre.EntegreLBYSLabService servis = new ws_Adana_Lab_Entegre.EntegreLBYSLabService();
ws_Adana_Lab_Entegre.HastaSonucToplu[] hs= servis.TCSonucBilgisi("21805034564", "2164", "11584398278");
DataTable dt=new DataTable();
dt.Columns.Add("Aciklama");
dt.Columns.Add("AdiSoyadi");
dt.Columns.Add("AileHekimiAdi");
dt.Columns.Add("BabaAdi");
dt.Columns.Add("Barkod");
dt.Columns.Add("BirimAdi");
dt.Columns.Add("DogumTarihi");
dt.Columns.Add("KayitTarihi");
dt.Columns.Add("ÖrnekAlmaTarihi");
for (int i = 0; i < hs.Length; i++)
{
dt.Rows.Add(hs[i].TestSonuclariGenel[0].Aciklama, hs[i].TestSonuclariGenel[0].AdiSoyadi, hs[i].TestSonuclariGenel[0].AileHekimiAdi, hs[i].TestSonuclariGenel[0].BabaAdi, hs[i].TestSonuclariGenel[0].Barkod, hs[i].TestSonuclariGenel[0].BirimAdi, hs[i].TestSonuclariGenel[0].DogumTarihi, hs[i].TestSonuclariGenel[0].KayitTarihi, hs[i].TestSonuclariGenel[0].OrnekAlmaTarihi);
}
dataGridView1.DataSource=dt;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int secili_alan = dataGridView1.SelectedCells[0].RowIndex;
string barkod = dataGridView1.Rows[secili_alan].Cells[4].Value.ToString();
textBox2.Text = barkod;
textBox2.ReadOnly = true;
}
private void button2_Click(object sender, EventArgs e)
{
ws_Adana_Lab_Entegre.EntegreLBYSLabService servis = new ws_Adana_Lab_Entegre.EntegreLBYSLabService();
ws_Adana_Lab_Entegre.HastaSonucToplu[] hs = servis.TCSonucBilgisi("21805034564", "2164", "11584398278");
DataTable dt1 = new DataTable();
dt1.Columns.Add("OrnekTipi");
dt1.Columns.Add("Sonuc");
dt1.Columns.Add("SonucAciklama");
dt1.Columns.Add("SonucBirim");
dt1.Columns.Add("SonucDurum");
dt1.Columns.Add("SonucOnayTarihi", typeof(System.DateTime));
dt1.Columns.Add("SonucReferans");
dt1.Columns.Add("SonucYorum");
dt1.Columns.Add("TestAdi");
dt1.Columns.Add("TestGrupAdi");
dt1.Columns.Add("TestID");
dt1.Columns.Add("TestParametreAdi");
for (int i = 0; i < hs[0].TestSonuclariGenel[0].TestSonuclari.Length; i++)
{
dt1.Rows.Add(hs[0].TestSonuclariGenel[0].TestSonuclari[i].OrnekTipi, hs[0].TestSonuclariGenel[0].TestSonuclari[i].Sonuc, hs[0].TestSonuclariGenel[0].TestSonuclari[i].SonucAciklama, hs[0].TestSonuclariGenel[0].TestSonuclari[i].SonucBirim, hs[0].TestSonuclariGenel[0].TestSonuclari[i].SonucDurum, hs[0].TestSonuclariGenel[0].TestSonuclari[i].SonucOnayTarihi, hs[0].TestSonuclariGenel[0].TestSonuclari[i].SonucReferans, hs[0].TestSonuclariGenel[0].TestSonuclari[i].SonucYorum, hs[0].TestSonuclariGenel[0].TestSonuclari[i].TestAdi, hs[0].TestSonuclariGenel[0].TestSonuclari[i].TestGrupAdi, hs[0].TestSonuclariGenel[0].TestSonuclari[i].TestID, hs[0].TestSonuclariGenel[0].TestSonuclari[i].TestParametreAdi);
}
}
}
}
|
using EasyWebApp.Data.Entities.AuthenticationEnties;
using EasyWebApp.Data.Entities.ServiceWebEntities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace EasyWebApp.Data.DbContext
{
public class EasyWebDbContext : IdentityDbContext<ApplicationUser>
{
public EasyWebDbContext(DbContextOptions<EasyWebDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<UserDbInfo> UserDatabaseInfos { get; set; }
}
}
|
namespace gView.Framework.Symbology
{
[global::System.AttributeUsageAttribute(global::System.AttributeTargets.Property)]
public class UseColorGradientPicker : global::System.Attribute
{
public UseColorGradientPicker()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace elexFog
{
enum FogType
{
Removed,
Adjusted,
Default
}
class FileIO
{
private const string m_removedDepth = "1";
private const string m_removedMaxViewRange = "128000.0f";
private const string m_adjustedDepth = "48";
private const string m_adjustedMaxViewRange = "128000.0f";
private string m_path;
private XDocument m_file;
public bool setPathIfValid(string path)
{
if (isPathValid(path))
{
m_path = path + "/data/ini/ConfigDefault.xml";
return true;
}
return false;
}
public void saveConfig()
{
m_file.Save(m_path);
// remove first line that's not in elex config by default
var file = File.ReadAllLines(m_path).ToList();
file.RemoveAt(0);
File.WriteAllLines(m_path, file);
}
public void readConfig()
{
createBackupIfNeeded();
m_file = XDocument.Load(m_path, LoadOptions.PreserveWhitespace);
}
public void modifyFog(FogType type)
{
var test = m_file.Elements("global").Elements("Engine").Elements("Render").Elements("Fog").Elements().First().Name.ToString();
var depths =
m_file.Elements("global").Elements("Engine").Elements("Render").Elements("Fog").Elements().ToDictionary
(
c => c.Name,
c => c.Attribute("Depth")
);
var maxViewRanges =
m_file.Elements("global").Elements("Engine").Elements("Render").Elements("Fog").Elements().ToDictionary
(
c => c.Name,
c => c.Attribute("MaxViewRange")
);
switch (type)
{
case FogType.Removed:
foreach (KeyValuePair<XName, XAttribute> v in depths)
{
v.Value.SetValue(m_removedDepth);
}
foreach (KeyValuePair<XName, XAttribute> v in maxViewRanges)
{
v.Value.SetValue(m_removedMaxViewRange);
}
break;
case FogType.Adjusted:
foreach (KeyValuePair<XName, XAttribute> v in depths)
{
v.Value.SetValue(m_adjustedDepth);
}
foreach (KeyValuePair<XName, XAttribute> v in maxViewRanges)
{
v.Value.SetValue(m_adjustedMaxViewRange);
}
break;
case FogType.Default:
depths["Low"].SetValue("96");
depths["Medium"].SetValue("128");
depths["High"].SetValue("192");
depths["Ultra"].SetValue("256");
maxViewRanges["Low"].SetValue("4800.0f");
maxViewRanges["Medium"].SetValue("4800.0f");
maxViewRanges["High"].SetValue("6400.0f");
maxViewRanges["Ultra"].SetValue("6400.0f");
break;
}
}
private bool isPathValid(string path)
{
if (File.Exists(path + "/system/ELEX.exe"))
{
return true;
}
return false;
}
private void createBackupIfNeeded()
{
if(!File.Exists(m_path + "_backup"))
{
File.Copy(m_path, m_path + "_backup");
}
}
}
}
|
namespace qbq.EPCIS.Repository.Custom.Entities
{
class EpcisEventTransformationId
{
//-----------------------------------------------------------------
//-- Tabelle zum Zwischenspeichern der TransformationID
//-----------------------------------------------------------------
//create table #EPCISEvent_TransformationID
//(
//EPCISEventID bigint not null,
//TransformationIDURN nvarchar(512) not null,
//TransformationIDID bigint null,
//);
public long EpcisEventId { get; set; }
public string TransformationIdUrn { get; set; }
public long TransformationIdId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PayRentAndUse_V3.Models
{
public class UserClass
{
public int Id { get; set; }
[Required(ErrorMessage="Please Enter Name")]
[Display(Name = "Enter Name :")]
[StringLength(maximumLength:50,MinimumLength =2,ErrorMessage ="Name must be Max 50 and Min 2" )]
public string Name { get; set; }
[Required(ErrorMessage = "Please Select Gender")]
[Display(Name = "Gender :")]
public string Gender { get; set; }
[Required(ErrorMessage = "Please Email Address")]
[Display(Name = "Email Id :")]
public string Email { get; set; }
[Required(ErrorMessage = "Please Enter Password")]
[Display(Name = "Password :")]
[DataType(DataType.Password)]
public string UserPassword { get; set; }
[Required(ErrorMessage = "Confirm Password cannot be blank")]
[Display(Name = "Confirm Password :")]
[DataType(DataType.Password)]
[Compare("UserPassword")]
public string UserRePassword { get; set; }
public DateTime DateAdded { get; set; }
public int Rating { get; set; }
public string Feedback { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using POSServices.Models;
using POSServices.WebAPIModel;
namespace POSServices.Controllers
{
[Route("api/ItemDimension")]
[ApiController]
public class ItemDimensionController : Controller
{
private readonly DB_BIENSI_POSContext _context;
public ItemDimensionController(DB_BIENSI_POSContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> getData()
{
ItemDimension item = new ItemDimension();
item.brands = _context.ItemDimensionBrand.ToList();
item.sizes = _context.ItemDimensionSize.ToList();
item.colors = _context.ItemDimensionColor.ToList();
item.departments = _context.ItemDimensionDepartment.ToList();
item.departmentTypes = _context.ItemDimensionDepartmentType.ToList();
item.genders = _context.ItemDimensionGender.ToList();
return Ok(item);
}
}
} |
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
namespace Shared
{
public class Context : DbContext
{
public Tests Tests { get; set; } = new Tests();
}
public class Test
{
[Key]
public int Key { get; set; }
}
public class Tests : DbSet<Test>
{
}
}
|
using System.Collections.Generic;
using DataLayer.Entities;
using SolarSystemWeb.Models.Entities;
namespace SolarSystemWeb.Models.ViewModels
{
public class DropDownViewModel
{
public DropDownViewModel(SpaceObjectTypeDto type, IEnumerable<SimpleModel> items)
{
Type = type;
Items = items;
}
public IEnumerable<SimpleModel> Items { get; private set; }
public SpaceObjectTypeDto Type { get; private set; }
}
} |
using System.Collections.Generic;
using StardewModdingAPI;
namespace ModUpdateMenu.Updates
{
internal interface IUpdateStatusRetriever
{
bool GetUpdateStatuses(out IList<ModStatus> statuses);
ISemanticVersion GetSMAPIUpdateVersion();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GeoSearch.Web
{
public class WMSLayer
{
//The name of layer
public string name { get; set; }
//The title of layer
public string title { get; set; }
//The rank score of layer
public double rankValue {get; set;}
//The getMap response time of layer
public double responseTime { get; set; }
//LatLonBoundingBox of the WMS layer
public BBox box { get; set; }
}
} |
using AutoFixture;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
using System;
using System.Threading.Tasks;
using SFA.DAS.Encoding;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Apprentices.ChangeEmployer;
using SFA.DAS.ProviderCommitments.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Services.Cache;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice
{
[TestFixture]
public class ConfirmEmployerViewModelMapperTests
{
private ConfirmEmployerViewModelMapper _mapper;
private ConfirmEmployerRequest _source;
private Func<Task<ConfirmEmployerViewModel>> _act;
private GetConfirmEmployerResponse _accountLegalEntityResponse;
private Mock<IEncodingService> _encodingService;
private Mock<ICacheStorageService> _cacheStorage;
private ChangeEmployerCacheItem _cacheItem;
private string _encodedAccountLegalEntityId;
[SetUp]
public void Arrange()
{
var fixture = new Fixture();
_accountLegalEntityResponse = fixture.Create<GetConfirmEmployerResponse>();
_source = fixture.Create<ConfirmEmployerRequest>();
var icommitmentApiClient = new Mock<IOuterApiClient>();
icommitmentApiClient.Setup(x => x.Get<GetConfirmEmployerResponse>(It.IsAny<GetConfirmEmployerRequest>())).ReturnsAsync(_accountLegalEntityResponse);
_cacheItem = fixture.Create<ChangeEmployerCacheItem>();
_cacheStorage = new Mock<ICacheStorageService>();
_cacheStorage.Setup(x =>
x.RetrieveFromCache<ChangeEmployerCacheItem>(It.Is<Guid>(key => key == _source.CacheKey)))
.ReturnsAsync(_cacheItem);
_encodedAccountLegalEntityId = fixture.Create<string>();
_encodingService = new Mock<IEncodingService>();
_encodingService.Setup(x => x.Encode(_cacheItem.AccountLegalEntityId,
It.Is<EncodingType>(e => e == EncodingType.PublicAccountLegalEntityId)))
.Returns(_encodedAccountLegalEntityId);
_mapper = new ConfirmEmployerViewModelMapper(icommitmentApiClient.Object, _cacheStorage.Object, _encodingService.Object);
_act = async () => await _mapper.Map(_source);
}
[Test]
public async Task ThenEmployerAccountLegalEntityPublicHashedIdIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_encodedAccountLegalEntityId, result.EmployerAccountLegalEntityPublicHashedId);
}
[Test]
public async Task ThenEmployerAccountNameIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_accountLegalEntityResponse.AccountName, result.EmployerAccountName);
}
[Test]
public async Task ThenEmployerAccountLegalEntityNameIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_accountLegalEntityResponse.LegalEntityName, result.LegalEntityName);
}
[Test]
public async Task ThenProviderIdMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.ProviderId, result.ProviderId);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.