text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Kursovay { public partial class Form12 : Form { public Form12() { InitializeComponent(); } private string result = " "; private int current_row = 0; private int current_col = 0; private int tempRow1, tempCol1, tempRow2, tempCol2, count; string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kandr\Source\Repos\Kursovay\Kursovay\Database1.mdf;Integrated Security=True"; SqlConnection sqlconnect; private void Form12_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "database1DataSet.Рецепт". При необходимости она может быть перемещена или удалена. // this.рецептTableAdapter.Fill(this.database1DataSet.Рецепт); } private void тушеныеОвощиToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); // this.продуктыTableAdapter.Fill(this.database1DataSet1.Продукты); dataGridView1.RowTemplate.MinimumHeight = 35; sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); // SqlCommand comand = new SqlCommand("SELECT [database1DataSet1.Продукты].Наименование,[database1DataSet1.Продукты].Калорийность FROM [database1DataSet1.Продукты] WHERE [database1DataSet1.Продукты].Калорийность<" + kkal.ToString() + "", sqlconnect); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='1'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void menuStrip2_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void кашиToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); dataGridView1.RowTemplate.MinimumHeight = 35; sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); // SqlCommand comand = new SqlCommand("SELECT [database1DataSet1.Продукты].Наименование,[database1DataSet1.Продукты].Калорийность FROM [database1DataSet1.Продукты] WHERE [database1DataSet1.Продукты].Калорийность<" + kkal.ToString() + "", sqlconnect); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='3'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void сокиToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); // this.продуктыTableAdapter.Fill(this.database1DataSet1.Продукты); dataGridView1.RowTemplate.MinimumHeight = 35; sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); // SqlCommand comand = new SqlCommand("SELECT [database1DataSet1.Продукты].Наименование,[database1DataSet1.Продукты].Калорийность FROM [database1DataSet1.Продукты] WHERE [database1DataSet1.Продукты].Калорийность<" + kkal.ToString() + "", sqlconnect); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='2'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void завтракиToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); // this.продуктыTableAdapter.Fill(this.database1DataSet1.Продукты); dataGridView1.RowTemplate.MinimumHeight = 35; sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); // SqlCommand comand = new SqlCommand("SELECT [database1DataSet1.Продукты].Наименование,[database1DataSet1.Продукты].Калорийность FROM [database1DataSet1.Продукты] WHERE [database1DataSet1.Продукты].Калорийность<" + kkal.ToString() + "", sqlconnect); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='4'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Приложение представляет из себя автоматизированную информационные систему технологий создания блюд." + "С его помощю Вы сможите удалять и добавлять данные в базу, производить поиск рецептов блюд,их авторов,выбирать рецепты из представленных категорий, искать блюда меньше заданной калорийности!"); } private void выходToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void главноеМенюToolStripMenuItem_Click(object sender, EventArgs e) { Form1 newForm = new Form1(); newForm.Show(); Hide(); } private void поставщикToolStripMenuItem_Click(object sender, EventArgs e) { Form2 newForm = new Form2(); newForm.Show(); Hide(); } private void продуктыToolStripMenuItem_Click(object sender, EventArgs e) { Form3 newForm = new Form3(); newForm.Show(); Hide(); } private void рецептToolStripMenuItem_Click(object sender, EventArgs e) { Form4 newForm = new Form4(); newForm.Show(); Hide(); } private void авторToolStripMenuItem_Click(object sender, EventArgs e) { Form7 newForm = new Form7(); newForm.Show(); Hide(); } private void ингредиентыToolStripMenuItem_Click(object sender, EventArgs e) { Form8 newForm = new Form8(); newForm.Show(); Hide(); } private void группыПродуктовToolStripMenuItem_Click(object sender, EventArgs e) { Form5 newForm = new Form5(); newForm.Show(); Hide(); } private void способПриготовленияToolStripMenuItem_Click(object sender, EventArgs e) { Form13 fm = new Form13(); fm.Show(); Hide(); } private void прайслистПоставщикаToolStripMenuItem_Click(object sender, EventArgs e) { Form11 newForm = new Form11(); newForm.Show(); Hide(); } private void рецептБлюдToolStripMenuItem_Click(object sender, EventArgs e) { Form12 newForm = new Form12(); newForm.Show(); Hide(); } private void списокБлюдМинимальнойКалорийностиToolStripMenuItem_Click(object sender, EventArgs e) { Form10 newForm = new Form10(); newForm.Show(); Hide(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void Печать_Click(object sender, EventArgs e) { PrintDocument Document = new PrintDocument(); Document.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage_1); PrintPreviewDialog dlg = new PrintPreviewDialog(); dlg.Document = Document; dlg.ShowDialog(); } private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { } private void printDocument1_PrintPage_1(object sender, PrintPageEventArgs e) { tempRow1 = 0; tempRow2 = 0; tempCol1 = 0; count = 0; Graphics g = e.Graphics; count++; g.DrawString("стр. " + count.ToString(), new Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point), Brushes.Black, 350, 50); int x = 100; int y = 100; int cell_height = 0; current_col = tempCol1; tempCol2 = tempCol1; current_row = tempRow1; int colCount = dataGridView1.ColumnCount; int rowCount = dataGridView1.RowCount - 1; int width = dataGridView1[current_col, current_row].Size.Width; int height = dataGridView1[current_col, current_row].Size.Height; Rectangle cell_border; SolidBrush brush = new SolidBrush(Color.Black); StringFormat str = new StringFormat(); str.Alignment = StringAlignment.Near; str.LineAlignment = StringAlignment.Center; str.Trimming = StringTrimming.EllipsisCharacter; cell_height = dataGridView1[current_col, current_row].Size.Height + 10; while (current_col < colCount) { /**/ if (x > e.MarginBounds.Width) { e.HasMorePages = true; break; }/**/ g.FillRectangle(Brushes.LightGray, new Rectangle(x, y, dataGridView1.Columns[current_col].Width, cell_height)); g.DrawRectangle(Pens.Black, x, y, dataGridView1.Columns[current_col].Width, cell_height); g.DrawString(dataGridView1.Columns[current_col].HeaderText, new Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point), Brushes.Black, new RectangleF(x, y, dataGridView1.Columns[current_col].Width, cell_height), str); x += dataGridView1[current_col, current_row].Size.Width; current_col++; } y += cell_height; x = 100; current_col = tempCol1; while (current_row < rowCount) { if (y > e.MarginBounds.Height + 100) { tempRow1 = tempRow2; if (x < e.MarginBounds.Width) tempCol1 = 0; else tempRow2 = current_row; e.HasMorePages = true; y = 100; return; } x = 100; while (current_col < colCount) { if (x > e.MarginBounds.Width) { tempCol1 = current_col; e.HasMorePages = true; break; } cell_height = dataGridView1[current_col, current_row].Size.Height + 10; cell_border = new Rectangle(x, y, width, height); g.DrawRectangle(Pens.Black, x, y, dataGridView1.Columns[current_col].Width, cell_height); g.DrawString(dataGridView1.Rows[current_row].Cells[current_col].Value.ToString(), dataGridView1.Font, Brushes.Black, new RectangleF(x, y, dataGridView1.Columns[current_col].Width, cell_height), str); x += dataGridView1[current_col, current_row].Size.Width; current_col++; } current_col = tempCol2; current_row++; y += cell_height; } } private void рецетпыToolStripMenuItem_Click(object sender, EventArgs e) { } private void блюдаНаПраздникиToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); // SqlCommand comand = new SqlCommand("SELECT [database1DataSet1.Продукты].Наименование,[database1DataSet1.Продукты].Калорийность FROM [database1DataSet1.Продукты] WHERE [database1DataSet1.Продукты].Калорийность<" + kkal.ToString() + "", sqlconnect); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='5'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void супыToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='6'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void диетическоеМенюToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='7'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void напиткиToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='8'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void мясныеБлюдаToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='9'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } private void десертыToolStripMenuItem_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); sqlconnect = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT [Рецепт].Номер,[Рецепт].Название,[Рецепт].Описание FROM [Рецепт] WHERE [Рецепт].Код_категории_рецепта='10'", sqlconnect); sqlconnect.Open(); da.Fill(ds, "Рецепт"); dataGridView1.DataSource = ds.Tables[0]; da.Dispose(); sqlconnect.Dispose(); ds.Dispose(); } } }
using LuaInterface; using RO; using SLua; using System; using System.Collections.Generic; using UnityEngine; public class Lua_RO_CallBackWhenClickOtherPlace : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_targets(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, callBackWhenClickOtherPlace.targets); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_targets(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); List<Transform> targets; LuaObject.checkType<List<Transform>>(l, 2, out targets); callBackWhenClickOtherPlace.targets = targets; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_call(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); Action action; int num = LuaDelegation.checkDelegate(l, 2, out action); if (num == 0) { callBackWhenClickOtherPlace.call = action; } else if (num == 1) { CallBackWhenClickOtherPlace expr_30 = callBackWhenClickOtherPlace; expr_30.call = (Action)Delegate.Combine(expr_30.call, action); } else if (num == 2) { CallBackWhenClickOtherPlace expr_53 = callBackWhenClickOtherPlace; expr_53.call = (Action)Delegate.Remove(expr_53.call, action); } LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_excuteOnce(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, callBackWhenClickOtherPlace.excuteOnce); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_excuteOnce(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); bool excuteOnce; LuaObject.checkType(l, 2, out excuteOnce); callBackWhenClickOtherPlace.excuteOnce = excuteOnce; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_mulityTouch(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, callBackWhenClickOtherPlace.mulityTouch); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_mulityTouch(IntPtr l) { int result; try { CallBackWhenClickOtherPlace callBackWhenClickOtherPlace = (CallBackWhenClickOtherPlace)LuaObject.checkSelf(l); bool mulityTouch; LuaObject.checkType(l, 2, out mulityTouch); callBackWhenClickOtherPlace.mulityTouch = mulityTouch; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.CallBackWhenClickOtherPlace"); LuaObject.addMember(l, "targets", new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.get_targets), new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.set_targets), true); LuaObject.addMember(l, "call", null, new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.set_call), true); LuaObject.addMember(l, "excuteOnce", new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.get_excuteOnce), new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.set_excuteOnce), true); LuaObject.addMember(l, "mulityTouch", new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.get_mulityTouch), new LuaCSFunction(Lua_RO_CallBackWhenClickOtherPlace.set_mulityTouch), true); LuaObject.createTypeMetatable(l, null, typeof(CallBackWhenClickOtherPlace), typeof(MonoBehaviour)); } }
namespace iQuest.VendingMachine.Payment.Services { internal class PaymentMethod { public int Id { get; set; } public string Name { get; set; } public PaymentMethod(int id, string name) { this.Id = id; this.Name = name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GPA_Calculator.Util { public class FourPointGradeScale : GradeScale { // Uses College Board 4.0 scale // https://pages.collegeboard.org/how-to-convert-gpa-4.0-scale public override double A_PLUS { get; } = 4.0; public override double A { get; } = 4.0; public override double A_MINUS { get; } = 3.67; public override double B_PLUS { get; } = 3.33; public override double B { get; } = 3.0; public override double B_MINUS { get; } = 2.67; public override double C_PLUS { get; } = 2.33; public override double C { get; } = 2.0; public override double C_MINUS { get; } = 1.67; public override double D_PLUS { get; } = 1.33; public override double D { get; } = 1.0; public override double D_MINUS { get; } = 0.0; public override Dictionary<string, double> GradeLetterMapping { get; protected set; } public override Dictionary<double, double> GradeLowestNumericMapping { get; protected set; } public FourPointGradeScale() { GradeLetterMapping = new Dictionary<string, double>() { { "A+", A_PLUS }, { "A", A }, { "A-", A_MINUS }, { "B+", B_PLUS }, { "B", B }, { "B-", B_MINUS }, { "C+", C_PLUS }, { "C", C }, { "C-", C_MINUS }, { "D+", D_PLUS }, { "D", D }, { "D-", D_MINUS } }; GradeLowestNumericMapping = new Dictionary<double, double>() { { 97, A_PLUS }, { 93, A }, { 90, A_MINUS }, { 87, B_PLUS }, { 83, B }, { 80, B_MINUS }, { 77, C_PLUS }, { 73, C }, { 70, C_MINUS }, { 67, D_PLUS }, { 63, D }, { 0, D_MINUS } }; } } }
namespace Bingo.Answers.Exceptions { using System; public class EntityNotFoundException : Exception { public EntityNotFoundException() { } public EntityNotFoundException(string message): base(message) { } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace netfx { /* Fast Algorithms : Box Blur Algorithm by: Wojciech Jarosz on : http://elynxsdk.free.fr/ext-docs/Blur/Fast_box_blur.pdf and the Fast Gaussian Algorithm by: Peter Kovesi on : http://www.peterkovesi.com/papers/FastGaussianSmoothing.pdf */ class Blur { public BitmapW Gaussain(BitmapW src , int Radius) { return FastGaussianBlur(src, Radius); } public BitmapW Box(BitmapW src, int Radius) { return FastBoxBlur(src, Radius); } private BitmapW FastBoxBlur(BitmapW img, int radius) { int kSize = radius; if (kSize % 2 == 0) kSize++; BitmapW Hblur = img.Clone(); float Avg = (float)1 / kSize; for (int j = 0; j < img.Height(); j++) { float[] hSum = new float[] { 0f, 0f, 0f, 0f }; float[] iAvg = new float[] { 0f, 0f, 0f, 0f }; for (int x = 0; x < kSize; x++) { Color tmpColor = img.GetPixel(x, j); hSum[0] += tmpColor.A; hSum[1] += tmpColor.R; hSum[2] += tmpColor.G; hSum[3] += tmpColor.B; } iAvg[0] = hSum[0] * Avg; iAvg[1] = hSum[1] * Avg; iAvg[2] = hSum[2] * Avg; iAvg[3] = hSum[3] * Avg; for (int i = 0; i < img.Width(); i++) { if (i - kSize / 2 >= 0 && i + 1 + kSize / 2 < img.Width()) { Color tmp_pColor = img.GetPixel(i - kSize / 2, j); hSum[0] -= tmp_pColor.A; hSum[1] -= tmp_pColor.R; hSum[2] -= tmp_pColor.G; hSum[3] -= tmp_pColor.B; Color tmp_nColor = img.GetPixel(i + 1 + kSize / 2, j); hSum[0] += tmp_nColor.A; hSum[1] += tmp_nColor.R; hSum[2] += tmp_nColor.G; hSum[3] += tmp_nColor.B; // iAvg[0] = hSum[0] * Avg; iAvg[1] = hSum[1] * Avg; iAvg[2] = hSum[2] * Avg; iAvg[3] = hSum[3] * Avg; } Hblur.SetPixel(i, j, Color.FromArgb((int)iAvg[0], (int)iAvg[1], (int)iAvg[2], (int)iAvg[3])); } } BitmapW total =Hblur.Clone(); for (int i = 0; i < Hblur.Width(); i++) { float[] tSum = new float[] { 0f, 0f, 0f, 0f }; float[] iAvg = new float[] { 0f, 0f, 0f, 0f }; for (int y = 0; y < kSize; y++) { Color tmpColor = Hblur.GetPixel(i, y); tSum[0] += tmpColor.A; tSum[1] += tmpColor.R; tSum[2] += tmpColor.G; tSum[3] += tmpColor.B; } iAvg[0] = tSum[0] * Avg; iAvg[1] = tSum[1] * Avg; iAvg[2] = tSum[2] * Avg; iAvg[3] = tSum[3] * Avg; for (int j = 0; j < Hblur.Height(); j++) { if (j - kSize / 2 >= 0 && j + 1 + kSize / 2 < Hblur.Height()) { Color tmp_pColor = Hblur.GetPixel(i, j - kSize / 2); tSum[0] -= tmp_pColor.A; tSum[1] -= tmp_pColor.R; tSum[2] -= tmp_pColor.G; tSum[3] -= tmp_pColor.B; Color tmp_nColor = Hblur.GetPixel(i, j + 1 + kSize / 2); tSum[0] += tmp_nColor.A; tSum[1] += tmp_nColor.R; tSum[2] += tmp_nColor.G; tSum[3] += tmp_nColor.B; // iAvg[0] = tSum[0] * Avg; iAvg[1] = tSum[1] * Avg; iAvg[2] = tSum[2] * Avg; iAvg[3] = tSum[3] * Avg; } total.SetPixel(i, j, Color.FromArgb((int)iAvg[0], (int)iAvg[1], (int)iAvg[2], (int)iAvg[3])); } } return total; } private BitmapW FastGaussianBlur(BitmapW src, int Raduis) { var bxs = boxesForGaussian(Raduis, 3); BitmapW img = FastBoxBlur(src, bxs[0]); BitmapW img_2 = FastBoxBlur(img, bxs[1]); BitmapW img_3 = FastBoxBlur(img_2, bxs[2]); return img_3; } private int[] boxesForGaussian(double sigma, int n) { double wIdeal = Math.Sqrt((12 * sigma * sigma / n) + 1); double wl = Math.Floor(wIdeal); if (wl % 2 == 0) wl--; double wu = wl + 2; double mIdeal = (12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4); double m = Math.Round(mIdeal); int[] sizes = new int[n]; for (int i = 0; i < n; i++) { if (i < m) { sizes[i] = (int)wl; } else { sizes[i] = (int)wu; } } return sizes; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HackerRank_HomeCode { public class BonAppetie { public void ValidateBill() { string[] nk = Console.ReadLine().TrimEnd().Split(' '); //no of array elements int n = Convert.ToInt32(nk[0]); //index of item which anna does not eat int k = Convert.ToInt32(nk[1]); List<int> bill = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(billTemp => Convert.ToInt32(billTemp)).ToList(); //bill charged by bob int b = Convert.ToInt32(Console.ReadLine().Trim()); int annaShare = 0; int annaItems = 0; for(int i = 0;i<bill.Count;i++) { if(i != k) { annaItems += bill[i]; } } annaShare = annaItems / 2; if(annaShare == b) { Console.WriteLine("Bon appetie!!"); } else { Console.WriteLine(b-annaShare); } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAttack : MonoBehaviour { private float timeBtwAttack; public float startTimeBtwAttack; public Transform attackPos; public float attackRange; public LayerMask whatIsEnemies; public LayerMask vending; public int damage; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (timeBtwAttack <= 0) { if (Input.GetKey(KeyCode.Space)) { Debug.Log("ATTACK!"); timeBtwAttack = startTimeBtwAttack; Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll( attackPos.position, attackRange, whatIsEnemies); Collider2D[] vendingMachines = Physics2D.OverlapCircleAll( attackPos.position, attackRange, vending); for (int i = 0; i < vendingMachines.Length; i++) { vendingMachines[i].GetComponent<VendingMachine>().HealPlayer(); } } } else { timeBtwAttack -= Time.deltaTime; } } }
using System; using System.Collections.Generic; using System.Text; namespace Pizzaaa.Models { class Pizza { private string name; public string Name { get { return name; } private set { if (string.IsNullOrWhiteSpace(value) || value.Length > 15) { throw new ArgumentException("Pizza name should be between 1 and 15 symbols."); } name = value; } } private Dough dough; private List<Topping> toppings; public IReadOnlyCollection<Topping> Toppings { get { return toppings; } } private double calories; public Pizza(string name) { this.Name = name; toppings = new List<Topping>(); } public void AddDough(string flourType,string bakingTehnique,string weight) { dough = new Dough(flourType, bakingTehnique, weight); } public void AddTopping(Topping topping) { if (toppings.Count==9) { throw new InvalidOperationException("Number of toppings should be in range [0..10]."); } toppings.Add(topping); } public void Pizzacalories() { double caloriesFromTopings = 0; foreach (var item in toppings) { caloriesFromTopings += item.Calories; } calories = caloriesFromTopings + dough.Calories; } public override string ToString() { return string.Format("{0} - {1:F2} Calories.", Name, calories); } } }
using System; using System.Collections.Generic; public static class ArrayExtends { /// <summary> /// 克隆一个数组 /// </summary> public static T[] Clone<T>(this T[] Array) where T : class { if (Array == null) return null; int i, len = Array.Length; T[] newArray = new T[len]; for (i = 0; i < len; i++) { newArray[i] = Array[i]; } return newArray; } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using SickDev.CommandSystem; using Newtonsoft.Json; using CommonCore.State; namespace CommonCore.World { /* * WorldConsoleInterpreter * Console commands from ARES predescessor, may be refactored and/or split */ public class WorldConsoleCommands { static GameObject SelectedObject; static string SelectedTID; //***** UTILITIES [Command] static void PrintDataPath() //TODO move elsewhere { DevConsole.singleton.Log(Application.persistentDataPath); } [Command] static void PrintPlayerInfo() { DevConsole.singleton.Log(JsonConvert.SerializeObject(GameState.Instance.PlayerRpgState)); } [Command] static void PrintSceneList() { try { var sceneNames = SceneUtils.GetSceneList(); StringBuilder sb = new StringBuilder(sceneNames.Length * 16); foreach (var s in sceneNames) { sb.AppendLine(s); } DevConsole.singleton.Log(sb.ToString()); } catch(Exception e) { Debug.LogException(e); } } //***** CHEATS [Command] static void God() { if (MetaState.Instance.SessionFlags.Contains("GodMode")) MetaState.Instance.SessionFlags.Remove("GodMode"); else MetaState.Instance.SessionFlags.Add("GodMode"); } [Command] static void Noclip() { var player = WorldUtils.GetPlayerController(); player.Clipping = !(player.Clipping); } [Command] static void Notarget() { if (MetaState.Instance.SessionFlags.Contains("NoTarget")) MetaState.Instance.SessionFlags.Remove("NoTarget"); else MetaState.Instance.SessionFlags.Add("NoTarget"); } //***** LOAD/SAVE //force a full load from file with scene transition [Command] static void Load(string name) { MetaState.Instance.TransitionType = SceneTransitionType.LoadGame; MetaState.Instance.LoadSave = CCParams.SavePath + @"\" + name; MetaState.Instance.Intents.Clear(); SceneManager.LoadScene("LoadingScene"); } //force loading from file [Command] static void Restore(string name) { GameState.DeserializeFromFile(CCParams.SavePath + @"\" + name); Restore(); } //force loading from state [Command] static void Restore() { MetaState.Instance.TransitionType = SceneTransitionType.LoadGame; BaseSceneController bsc = WorldUtils.GetSceneController(); bsc.Restore(); } //force saving to gamestate [Command] static void Save() { BaseSceneController bsc = WorldUtils.GetSceneController(); bsc.Save(); } //force saving to a file [Command] static void Save(string name) { Save(); GameState.SerializeToFile(CCParams.SavePath + @"\" + name); } //***** SCENE WARP [Command] static void Warp(string scene) { Warp(scene, string.Empty); } [Command] static void Warp(string scene, string spawnPoint) { WorldUtils.ChangeScene(scene, spawnPoint, Vector3.zero, Vector3.zero); } [Command] static void Warp(string scene, Vector3 position) { Warp(scene, position, Vector3.zero); } [Command] static void Warp(string scene, Vector3 position, Vector3 rotation) { WorldUtils.ChangeScene(scene, null, position, rotation); } [Command] static void WarpEx(string scene, bool hideloading) { WorldUtils.ChangeScene(scene, null, Vector3.zero, Vector3.zero, hideloading, null); } [Command] static void WarpEx(string scene, bool hideloading, string overrideobject) { WorldUtils.ChangeScene(scene, null, Vector3.zero, Vector3.zero, hideloading, overrideobject); } //***** OBJECT MANIPULATION [Command] static void Spawn(string fid) { WorldUtils.SpawnObject(fid, null, (WorldUtils.GetPlayerObject().transform.position + (WorldUtils.GetPlayerObject().transform.forward * 1.0f)), Vector3.zero, null); } //pick object by form id [Command] static void Prid(string fid) { var objs = WorldUtils.FindObjectsWithFormID(fid); if (objs == null || objs.Length < 1) { DevConsole.singleton.LogWarning("No refs found with form id!"); return; } if (objs.Length > 1) DevConsole.singleton.LogWarning("More than one ref with form id!"); var obj = objs[0]; if (obj != null && obj.GetComponent<BaseController>()) { SelectedTID = obj.name; SelectedObject = obj; } else { DevConsole.singleton.LogWarning("Ref null or invalid!"); } DevConsole.singleton.Log("Found TID: " + SelectedTID); } //pick object by tag (ARES tag, not Unity tag) [Command] static void Prbt(string tag) { var objs = WorldUtils.FindObjectsWithTag(tag); if (objs == null || objs.Length < 1) { DevConsole.singleton.LogWarning("No refs found with tag!"); return; } if (objs.Length > 1) DevConsole.singleton.LogWarning("More than one ref with tag!"); var obj = objs[0]; if (obj != null && obj.GetComponent<BaseController>()) { SelectedTID = obj.name; SelectedObject = obj; } else { DevConsole.singleton.LogWarning("Ref null or invalid!"); } DevConsole.singleton.Log("Found TID: " + SelectedTID); } //pick object by TID [Command] static void Pick(string tid) { var obj = WorldUtils.FindObjectByTID(tid); if (obj == null) { DevConsole.singleton.LogWarning("Couldn't find TID!"); return; } if (obj.GetComponent<BaseController>() == null) { DevConsole.singleton.LogWarning("Ref has no controller!"); } SelectedTID = tid; SelectedObject = obj; DevConsole.singleton.Log("Found TID: " + tid); } //display info of selected ref [Command] static void GetInfo() { if(SelectedObject != null) { StringBuilder sb = new StringBuilder(256); //name, form id sb.AppendFormat("TID: {0} | FID: {1} \n", SelectedObject.name, SelectedObject.GetComponent<BaseController>().FormID); //coords sb.AppendFormat("Location: ({0:f2},{1:f2},{2:f2})\n", SelectedObject.transform.position.x, SelectedObject.transform.position.y, SelectedObject.transform.position.z); //enabled? active? sb.AppendFormat("Active: {0} | Visible: {1}", SelectedObject.activeSelf, SelectedObject.GetComponent<BaseController>().GetVisibility()); DevConsole.singleton.Log(sb.ToString()); } else { DevConsole.singleton.Log("No object selected!"); } } //deselect ref [Command] static void Dref() { SelectedTID = null; SelectedObject = null; } //***** ACTOR MANIPULATION [Command] static void SetAiState(string newState, bool lockState) { var ac = SelectedObject.GetComponent<ActorController>(); bool wasLocked = ac.LockAiState; if (wasLocked) ac.LockAiState = false; ac.EnterState((ActorAiState)Enum.Parse(typeof(ActorAiState), newState)); ac.LockAiState = wasLocked || lockState; } [Command] static void SetAnimState(string newState, bool lockState) { var ac = SelectedObject.GetComponent<ActorController>(); bool wasLocked = ac.LockAnimState; if (wasLocked) ac.LockAnimState = false; ac.SetAnimation((ActorAnimState)Enum.Parse(typeof(ActorAnimState), newState)); ac.LockAnimState = wasLocked || lockState; } [Command] static void Kill() { var ac = SelectedObject.GetComponent<ActorController>(); ac.Health = 0; } [Command] static void Disable() { var ac = SelectedObject.GetComponent<BaseController>(); ac.gameObject.SetActive(false); } [Command] static void Destroy() { GameObject.Destroy(SelectedObject); } [Command] static void Resurrect() { var ac = SelectedObject.GetComponent<ActorController>(); ac.gameObject.SetActive(true); ac.Health = ac.MaxHealth; ac.EnterState(ac.BaseAiState); } } }
using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using InfluxData.Net.InfluxDb.Formatters; using InfluxData.Net.InfluxDb.Infrastructure; namespace InfluxData.Net.InfluxDb.RequestClients { public interface IInfluxDbRequestClient { IInfluxDbFormatter GetFormatter(); Task<IInfluxDbApiResponse> PingAsync(); Task<IInfluxDbApiResponse> GetQueryAsync(IDictionary<string, string> requestParams); Task<IInfluxDbApiResponse> GetQueryAsync(HttpContent content = null, IDictionary<string, string> requestParams = null, bool includeAuthToQuery = true, bool headerIsBody = false); Task<IInfluxDbApiResponse> PostDataAsync(IDictionary<string, string> requestParams); Task<IInfluxDbApiResponse> PostDataAsync(HttpContent content = null, IDictionary<string, string> requestParams = null, bool includeAuthToQuery = true, bool headerIsBody = false); } }
using UnityEngine; using System.Collections; using System; [ExecuteInEditMode] public class SceneMenager : MonoBehaviour { static public float ScreenBalanceW, ScreenBalanceH; private int FontSize; static public int Style; static public int Cover; private int[] Settings; public GUISkin SkinStandartSet; void Awake() { DontDestroyOnLoad(this.transform.gameObject); SetAppSettings(); } void Start() { ScreenBalanceW = 800.0f / Settings[0]; ScreenBalanceH = 600.0f / Settings[1]; if ((Screen.width / Screen.height) > 1.333f) ScreenBalanceW = 800.0f / (Screen.height * 1.333f); FontSize = (int)(14 / ScreenBalanceW); } void OnGUI() { GUI.skin = SkinStandartSet; if (FontSize < 14) { GUIStyle LabelStyle = GUI.skin.GetStyle("label"); LabelStyle.fontSize = FontSize; GUIStyle ToggleStyle = GUI.skin.GetStyle("toggle"); ToggleStyle.fontSize = FontSize; GUIStyle ButtonStyle = GUI.skin.GetStyle("button"); ButtonStyle.fontSize = FontSize; GUIStyle RoomListStyle = GUI.skin.GetStyle("RoomList"); RoomListStyle.fontSize = FontSize; GUIStyle ErrorBoxStyle = GUI.skin.GetStyle("ErrorBox"); ErrorBoxStyle.fontSize = FontSize; GUIStyle HeaderStyle = GUI.skin.GetStyle("Header"); HeaderStyle.fontSize = FontSize * 2; GUIStyle TextField = GUI.skin.GetStyle("textfield"); TextField.fontSize = FontSize; GUIStyle TextArea = GUI.skin.GetStyle("textarea"); TextArea.fontSize = FontSize; GUIStyle LabelCenter = GUI.skin.GetStyle("LabelCenter"); LabelCenter.fontSize = FontSize; GUIStyle Box = GUI.skin.GetStyle("box"); Box.fontSize = FontSize; } else { GUIStyle LabelStyle = GUI.skin.GetStyle("label"); LabelStyle.fontSize = 14; GUIStyle ToggleStyle = GUI.skin.GetStyle("toggle"); ToggleStyle.fontSize = 14; GUIStyle ButtonStyle = GUI.skin.GetStyle("button"); ButtonStyle.fontSize = 14; GUIStyle RoomListStyle = GUI.skin.GetStyle("RoomList"); RoomListStyle.fontSize = 14; GUIStyle ErrorBoxStyle = GUI.skin.GetStyle("ErrorBox"); ErrorBoxStyle.fontSize = 14; GUIStyle HeaderStyle = GUI.skin.GetStyle("Header"); HeaderStyle.fontSize = 28; GUIStyle TextField = GUI.skin.GetStyle("textfield"); TextField.fontSize = 14; GUIStyle TextArea = GUI.skin.GetStyle("textarea"); TextArea.fontSize = 14; GUIStyle LabelCenter = GUI.skin.GetStyle("LabelCenter"); LabelCenter.fontSize = 14; GUIStyle Box = GUI.skin.GetStyle("box"); Box.fontSize = 14; } } void SetAppSettings() { TextAsset file = Resources.Load("AppSettings") as TextAsset; string StrSettings = file.text; int k = -1; int n = 0; int i = 0; Settings = new int[4]; while (StrSettings != string.Empty) { k = StrSettings.IndexOf(' '); n++; if (n == 1) { StrSettings = StrSettings.Remove(0, k + 1); } if (n == 2) { Settings[i] = Convert.ToInt32(StrSettings.Substring(k, StrSettings.IndexOf(';') - k)); StrSettings = StrSettings.Remove(0, StrSettings.IndexOf(';') + 1); n = 0; i++; } } Style = Settings[2]; Cover = Settings[3]; Screen.SetResolution(Settings[0], Settings[1], false); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; ////works in x/y plane ////**** //// QUADRANTS //// //// 0 | 1 //// ----- //// 2 | 3 //namespace helper //{ // public class QuadTree<T> // { // private enum QuadTreeDir // { // L, // R, // U, // D, // LU, // LD, // RU, // RD, // STOP // } // private class FSM_QuadDirPair // { // public char m_quadrant; // public QuadTreeDir m_dir; // public FSM_QuadDirPair(char quadrant, QuadTreeDir dir) // { // m_quadrant = quadrant; // m_dir = dir; // } // public static bool operator ==(FSM_QuadDirPair a, FSM_QuadDirPair b) // { // return (a.m_quadrant == b.m_quadrant && a.m_dir == b.m_dir); // } // public static bool operator !=(FSM_QuadDirPair a, FSM_QuadDirPair b) // { // return (a.m_quadrant != b.m_quadrant || a.m_dir != b.m_dir); // } // public override bool Equals(object obj) // { // return this == (FSM_QuadDirPair)obj; // } // public override int GetHashCode() // { // return m_quadrant.GetHashCode() * 17 + m_dir.GetHashCode(); // } // } // static private Dictionary<FSM_QuadDirPair, FSM_QuadDirPair> m_FSM; // public readonly Vector3 m_centerPos; // public readonly int m_maxLevel; // public readonly float m_sideLength; // Dictionary<string, T> m_linearNodes; // static QuadTree() // { // m_FSM = new Dictionary<FSM_QuadDirPair, FSM_QuadDirPair>(); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.R), new FSM_QuadDirPair('1', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.L), new FSM_QuadDirPair('1', QuadTreeDir.L)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.D), new FSM_QuadDirPair('2', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.U), new FSM_QuadDirPair('2', QuadTreeDir.U)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.RU), new FSM_QuadDirPair('3', QuadTreeDir.U)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.RD), new FSM_QuadDirPair('3', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.LD), new FSM_QuadDirPair('3', QuadTreeDir.L)); // m_FSM.Add(new FSM_QuadDirPair('0', QuadTreeDir.LU), new FSM_QuadDirPair('3', QuadTreeDir.LU)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.R), new FSM_QuadDirPair('0', QuadTreeDir.R)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.L), new FSM_QuadDirPair('0', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.D), new FSM_QuadDirPair('3', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.U), new FSM_QuadDirPair('3', QuadTreeDir.U)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.RU), new FSM_QuadDirPair('2', QuadTreeDir.RU)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.RD), new FSM_QuadDirPair('2', QuadTreeDir.R)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.LD), new FSM_QuadDirPair('2', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('1', QuadTreeDir.LU), new FSM_QuadDirPair('2', QuadTreeDir.U)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.R), new FSM_QuadDirPair('3', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.L), new FSM_QuadDirPair('3', QuadTreeDir.L)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.D), new FSM_QuadDirPair('0', QuadTreeDir.D)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.U), new FSM_QuadDirPair('0', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.RU), new FSM_QuadDirPair('1', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.RD), new FSM_QuadDirPair('1', QuadTreeDir.D)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.LD), new FSM_QuadDirPair('1', QuadTreeDir.LD)); // m_FSM.Add(new FSM_QuadDirPair('2', QuadTreeDir.LU), new FSM_QuadDirPair('1', QuadTreeDir.L)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.R), new FSM_QuadDirPair('2', QuadTreeDir.R)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.L), new FSM_QuadDirPair('2', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.D), new FSM_QuadDirPair('1', QuadTreeDir.D)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.U), new FSM_QuadDirPair('1', QuadTreeDir.STOP)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.RU), new FSM_QuadDirPair('0', QuadTreeDir.R)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.RD), new FSM_QuadDirPair('0', QuadTreeDir.RD)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.LD), new FSM_QuadDirPair('0', QuadTreeDir.D)); // m_FSM.Add(new FSM_QuadDirPair('3', QuadTreeDir.LU), new FSM_QuadDirPair('0', QuadTreeDir.STOP)); // } // public QuadTree(Vector3 centerWorldPos, float sideLength, int maxLevel) // { // if (sideLength <= 0) // throw new System.Exception("Side length must be greater than zero!"); // if (maxLevel < 0) // throw new System.Exception("Max level must not be negative!"); // m_centerPos = centerWorldPos; // m_sideLength = sideLength; // m_maxLevel = maxLevel; // m_linearNodes = new Dictionary<string, T>(); // m_linearNodes.Add("", new QuadTreeNode("", new Vector3(), m_sideLength)); // } // public int NodeCount // { // get { return m_linearNodes.Count; } // } // public Dictionary<string, QuadTreeNode> Nodes // { // get { return m_linearNodes; } // } // public void Subdivide(QuadTreeNode node) // { // float childSideLength = m_sideLength / Mathf.Pow(2.0f, node.Level + 1); // float childSideLengthHalf = childSideLength / 2.0f; // string code0 = node.Code + 0; // string code1 = node.Code + 1; // string code2 = node.Code + 2; // string code3 = node.Code + 3; // m_linearNodes[code0] = new QuadTreeNode(code0, node.RelativePos + new Vector3(-1, 0, 1) * childSideLengthHalf, childSideLength); // m_linearNodes[code1] = new QuadTreeNode(code1, node.RelativePos + new Vector3(1, 0, 1) * childSideLengthHalf, childSideLength); // m_linearNodes[code2] = new QuadTreeNode(code2, node.RelativePos + new Vector3(-1, 0, -1) * childSideLengthHalf, childSideLength); // m_linearNodes[code3] = new QuadTreeNode(code3, node.RelativePos + new Vector3(1, 0, -1) * childSideLengthHalf, childSideLength); // m_linearNodes.Remove(node.Code); // } // public bool Contains(string code) // { // return m_linearNodes.ContainsKey(code); // } // public Vector3 GetNodeWorldPosition(QuadTreeNode node) // { // if (!Contains(node.Code)) // throw new System.Exception("Node not from this quadtree!"); // return m_centerPos + node.RelativePos; // } // public float GetDistance(QuadTreeNode a, QuadTreeNode b) // { // return (a.RelativePos - b.RelativePos).magnitude; // } // //TODO: isnt fully implemented yet // public HashSet<QuadTreeNode> GetNeighbours(QuadTreeNode node) // { // HashSet<QuadTreeNode> allNeighbours = new HashSet<QuadTreeNode>(); // for (int i = 0; i < 8; i++) // { // QuadTreeDir dir = (QuadTreeDir)i; // string equalNeigbourCode = getEqualNeigbourCode(node.Code, dir); // if (Contains(equalNeigbourCode)) // allNeighbours.Add(m_linearNodes[equalNeigbourCode]); // } // return allNeighbours; // } // private static string getEqualNeigbourCode(string code, QuadTreeDir dir) // { // string resultCode = ""; // for (int i = code.Length; i >= 0; i--) // { // var newQuadDirPair = m_FSM[new FSM_QuadDirPair(code[i], dir)]; // resultCode = newQuadDirPair.m_quadrant + resultCode; // if (newQuadDirPair.m_dir == QuadTreeDir.STOP && i > 0) // { // resultCode = code.Substring(0, i - 1) + resultCode; // } // } // return resultCode; // } // } //} //public class QuadTreeNode //{ // public readonly string Code; // public readonly int Level; // public readonly Vector3 RelativePos; // public readonly float SideLength; // bool m_isWalkable = true; // public QuadTreeNode(string code, Vector3 relativePos, float sideLength) // { // Code = code; // Level = Code.Length; // RelativePos = relativePos; // SideLength = sideLength; // } // public bool IsWalkable // { // get { return m_isWalkable; } // set { m_isWalkable = value; } // } //}
using System; using System.Numerics; class TribonacciSequence { static void Main() { checked { BigInteger firstNum = BigInteger.Parse(Console.ReadLine()); BigInteger secondNum = BigInteger.Parse(Console.ReadLine()); BigInteger thirdNum = BigInteger.Parse(Console.ReadLine()); int sequenceLength = int.Parse(Console.ReadLine()); BigInteger currentNum = 0; if (sequenceLength == 1) { Console.WriteLine(firstNum); } else if (sequenceLength == 2) { Console.WriteLine(secondNum); } else if (sequenceLength == 3) { Console.WriteLine(thirdNum); } else { for (int i = 3; i < sequenceLength; i++) { currentNum = firstNum + secondNum + thirdNum; firstNum = secondNum; secondNum = thirdNum; thirdNum = currentNum; } Console.WriteLine(currentNum); } } } }
using System; using System.Collections.Generic; using System.Text; using Sisters.WudiLib; namespace Marchen.Model { /// <summary> /// api设定,设定接收与发送api,只写了http方式 /// </summary> public static class ApiProperties { /// <summary> /// 监听地址 /// </summary> public static string ApiPostAddr { get; set; } /// <summary> /// API端口地址 /// </summary> public static string ApiAddr { get; set; } /// <summary> /// API实例 /// </summary> public static HttpApiClient HttpApi { get; set; } /// <summary> /// 内容转发地址,将收到的所有内容再次上报到此地址 /// </summary> public static string ApiForwardToAddr { get; set; } } public static class SelfProperties { /// <summary> /// 自己的QQ号,保持自动获取 /// </summary> public static string SelfID { get; set; } } /// <summary> /// 数据库属性,只写了Oracle DB方式 /// </summary> class DBProperties { /// <summary> /// 数据库用户名 /// </summary> public static string DBUserID { get; set; } /// <summary> /// 数据库密码 /// </summary> public static string DBPassword { get; set; } /// <summary> /// 数据库地址 /// </summary> public static string DBAddress { get; set; } /// <summary> /// 数据库监听端口 /// </summary> public static string DBPort { get; set; } /// <summary> /// 数据库服务名 /// </summary> public static string DBServiceName { get; set; } } /// <summary> /// 环境设定,主要指的是调试环境 /// </summary> class EnvSettings { /// <summary> /// 调试模式,启动后只对调试群号内容响应 /// </summary> public static string TestMode { get; set; } /// <summary> /// 调试群号 /// </summary> public static string TestGrpID { get; set; } } }
namespace ReadyGamerOne.EditorExtension { public enum ArgType { Int=0, Float=1, String=2, Bool=3, Vector3=4 } }
/* * This short method demonstrates how we can read data from console. * This file demonstrates the below concept: * - reading data from console. */ using System; using System.Collections.Generic; namespace CSBasic { /// <summary> /// This is a ReadFromConsole class used for the demo. /// This is xml style documention and a good practice to use. /// </summary> class ReadFromConsole { public void ReadStringFromConsole() { string input = ""; var readString = new List<string>() { }; while (input != "q") { Console.WriteLine("Enter some string that you would like or enter 'q' to quit"); // this is how we read data from console. input = Console.ReadLine(); readString.Add(input); } Console.WriteLine("Reading back the items that were entered by you"); foreach(var item in readString) { Console.WriteLine($"read {item}"); } } } }
using System; using ALM.Reclutamiento.AccesoDatos; using ALM.Reclutamiento.Entidades; using System.Collections.Generic; using System.Data; using MySql.Data.MySqlClient; namespace ALM.Reclutamiento.Datos { public class DEmpresa : Conexion { public List<EEmpresa> ObtenerEmpresas(EEmpresa parametro) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtEmpresas"); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombre", parametro.NombreComercial)); if (parametro.Estatus < 0) parametro.Estatus = 2; accesoDatos.ListaParametros.Add(new MySqlParameter("pEstatus", parametro.Estatus.ToString())); return accesoDatos.CargarTabla().DataTableMapToList<EEmpresa>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public List<EEmpresa> ObtenerEmpresasID(EEmpresa parametro) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtEmpresasID"); accesoDatos.ListaParametros.Add(new MySqlParameter("pDominio", parametro.Dominio)); return accesoDatos.CargarTabla().DataTableMapToList<EEmpresa>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public List<EEmpresa> ObtenerIdEmpresaSiguiente() { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtIdEmpresaSiguiente"); return accesoDatos.CargarTabla().DataTableMapToList<EEmpresa>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public void RegistrarEmpresa(EEmpresa parametro) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPInsEmpresa"); accesoDatos.ListaParametros.Add(new MySqlParameter("pDominio", parametro.Dominio)); accesoDatos.ListaParametros.Add(new MySqlParameter("pRFC", parametro.RFC)); accesoDatos.ListaParametros.Add(new MySqlParameter("pProductKey", parametro.ProductKey)); accesoDatos.ListaParametros.Add(new MySqlParameter("pAdministrador", parametro.Administrador)); accesoDatos.ListaParametros.Add(new MySqlParameter("pContrasenia", parametro.Contrasenia)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreComercial", parametro.NombreComercial)); accesoDatos.ListaParametros.Add(new MySqlParameter("pRutaLogo", parametro.Logo)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEmail", parametro.Email)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreRepresentante", parametro.NombreRepresentante)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEmailRepresentante", parametro.EmailRepresentante)); accesoDatos.ListaParametros.Add(new MySqlParameter("pTelefonoRepresentante", parametro.TelefonoRepresentante)); accesoDatos.ListaParametros.Add(new MySqlParameter("pObservaciones", parametro.Observaciones)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreOtroContacto", parametro.NombreOtroContacto)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEmailOtroContacto", parametro.EmailOtroContacto)); accesoDatos.ListaParametros.Add(new MySqlParameter("pTelefonoOtroContacto", parametro.TelefonoOtroContacto)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEsActivo", parametro.EsActivo)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEsVigente", parametro.EsVigente)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNumeroUsuarios", parametro.NumeroUsuarios)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNumeroClientes", parametro.NumeroClientes)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNumeroRegistros", parametro.NumeroRegistros)); accesoDatos.Ejecutar(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public void ActualizarEmpresa(EEmpresa parametro) { Utilerias.Utilerias utileria = null; try { AbrirConexion(); utileria = new Utilerias.Utilerias(); utileria.Clave = ""; utileria.Clave = utileria.Descifrar(System.Configuration.ConfigurationManager.AppSettings[Constante.Clave]); parametro.Contrasenia = utileria.Cifrar(parametro.Contrasenia); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPActEmpresa"); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdEmpresa", parametro.IdEmpresa)); accesoDatos.ListaParametros.Add(new MySqlParameter("pDominio", parametro.Dominio)); accesoDatos.ListaParametros.Add(new MySqlParameter("pProductKey", parametro.ProductKey)); accesoDatos.ListaParametros.Add(new MySqlParameter("pAdministrador", parametro.Administrador)); accesoDatos.ListaParametros.Add(new MySqlParameter("pContrasenia", parametro.Contrasenia)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreComercial", parametro.NombreComercial)); accesoDatos.ListaParametros.Add(new MySqlParameter("pRFC",parametro.RFC)); accesoDatos.ListaParametros.Add(new MySqlParameter("pRutaLogo", parametro.Logo)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEmail", parametro.Email)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreRepresentante", parametro.NombreRepresentante)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEmailRepresentante", parametro.EmailRepresentante)); accesoDatos.ListaParametros.Add(new MySqlParameter("pTelefonoRepresentante", parametro.TelefonoRepresentante)); accesoDatos.ListaParametros.Add(new MySqlParameter("pObservaciones", parametro.Observaciones)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreOtroContacto", parametro.NombreOtroContacto)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEmailOtroContacto", parametro.EmailOtroContacto)); accesoDatos.ListaParametros.Add(new MySqlParameter("pTelefonoOtroContacto", parametro.TelefonoOtroContacto)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEsActivo", parametro.EsActivo)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEsVigente", parametro.EsVigente)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNumeroUsuarios", parametro.NumeroUsuarios)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNumeroClientes", parametro.NumeroClientes)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNumeroRegistros", parametro.NumeroRegistros)); accesoDatos.Ejecutar(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; ///<summary> /// Script Manager: Denver /// Description: Handles displaying which spell the player has selected /// graphically. /// Date Modified: 17/10/2018 ///</summary> public class UISpells : MonoBehaviour { [Header("Spell Images.")] [Tooltip("Fire Spell Image.")] [SerializeField] private Image m_fireSpellImage; [Tooltip("Ice Spell Image.")] [SerializeField] private Image m_iceSpellImage; [Tooltip("Lightning Spell Image.")] [SerializeField] private Image m_lightningSpellImage; [Header("Spell Sprites.")] [Tooltip("Fire Spell Sprites. Unselected and selected.")] [SerializeField] private Sprite[] m_fireSpellSprites = new Sprite[2]; [Tooltip("Ice Spell Sprites. Unselected and selected.")] [SerializeField] private Sprite[] m_iceSpellSprites = new Sprite[2]; [Tooltip("Lightning Spell Sprites. Unselected and selected.")] [SerializeField] private Sprite[] m_lightningSpellSprites = new Sprite[2]; private PlayerSpellManager m_spellManager; void Start() { // get instance of the player m_spellManager = FindObjectOfType<PlayerSpellManager>(); } void FixedUpdate() { switch(m_spellManager.m_eSpellType) { case eSpellType.FIRE: m_fireSpellImage.sprite = m_fireSpellSprites[1]; m_iceSpellImage.sprite = m_iceSpellSprites[0]; m_lightningSpellImage.sprite = m_lightningSpellSprites[0]; break; case eSpellType.ICE: m_fireSpellImage.sprite = m_fireSpellSprites[0]; m_iceSpellImage.sprite = m_iceSpellSprites[1]; m_lightningSpellImage.sprite = m_lightningSpellSprites[0]; break; case eSpellType.LIGHTNING: m_fireSpellImage.sprite = m_fireSpellSprites[0]; m_iceSpellImage.sprite = m_iceSpellSprites[0]; m_lightningSpellImage.sprite = m_lightningSpellSprites[1]; break; default: Debug.LogError("Could not find spell type.", gameObject); break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Web.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Optimization; using System.Web.Helpers; using System.Security.Claims; namespace GameStore.WebUI { public class Global : HttpApplication { void Session_Start(Object sender, EventArgs e) { Session["CartCount"] = 0; Session["OrderCount"] = 0; } void Application_Start(object sender, EventArgs e) { // Code that runs on application startup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; //GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add( // new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json"))); //GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add( // new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml"))); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); } public override string GetVaryByCustomString(HttpContext context, string custom) { if (custom == "User") { if (context.User.Identity == null || String.IsNullOrEmpty(context.User.Identity.Name)) return "None"; else return "User-" + context.User.Identity.Name; } return base.GetVaryByCustomString(context, custom); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; class MatrixFillingC { static void Main() { /*Write a program that fills and prints a matrix of size (n, n) - C */ Console.Write("Enter matrix's size: "); int n = int.Parse(Console.ReadLine()); int[,] matrix = new int[n, n]; int counter = 1; matrix[n - 1, 0] = counter; matrix[0, n - 1] = n * n; counter++; for (int index = n - 2; index >= 0; index--) { for (int row = 0; row <= n - 1; row++) { for (int col = n - 1; col >= 0; col--) { if (row == col) { if (row - index < 0) { continue; } else { matrix[col, row - index] = counter; counter++; } } } } } counter = (n * n) - 1; for (int index = n - 2; index > 0; index--) { for (int col = n - 1; col > 0; col--) { for (int row = 0; row <= n - 1; row++) { if (row == col) { if (col - index < 0) { continue; } else { matrix[col - index, row] = counter; counter--; } } } } } Console.WriteLine(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write("{0,-3} ", matrix[i, j]); } Console.WriteLine(); Console.WriteLine(); } } }
using ClassLibrary; using ClassLibrary.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BusinessLayer.Queries { class StatutQuery { private readonly Context _context; public StatutQuery(Context context) { _context = context; } public IQueryable<Statut> GetAll() { return _context.Statut; } public IQueryable<Statut> GetByID(int id) { return _context.Statut.Where(s => s.Id == id); } } }
using UnityEngine; public class ScaleAwake : MonoBehaviour { [SerializeField] private Vector3 _fromScale; [SerializeField] private Vector3 _toScale; [SerializeField] private float _scaleTime = 0.5f; private bool _scale; private float _scaleTimer = 0.0f; private void Awake() { _scale = true; } private void Update() { UpdateScale(); } private void UpdateScale() { if (!_scale) return; if (_scaleTimer > _scaleTime) { _scale = false; return; } var lerp = Mathf.Clamp01(_scaleTimer / _scaleTime); transform.localScale = Vector3.Lerp(_fromScale, _toScale, lerp); _scaleTimer += Time.deltaTime; } }
namespace BracketMatcher { using System; using System.Collections.Generic; using System.IO; internal static class Program { private class Pair { public List<Pair> children = new List<Pair>(); public int oIndex; public int cIndex; public int level; } private static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Invalid command"); Console.WriteLine(" Usage: BracketMatcher input"); return; } foreach (var input in File.ReadAllLines(args[0])) { // Step 1: Build the parse tree with a simple stack var stack = new Stack<Pair>(); var root = new Pair { oIndex = -1, cIndex = input.Length, level = 0 }; stack.Push(root); int maxLevel = 0; for (int i = 0; i < input.Length; i++) { if (input[i] == '(') { Pair newPair = new Pair(); newPair.oIndex = i; Pair parent = stack.Peek(); parent.children.Add(newPair); newPair.level = parent.level + 1; maxLevel = Math.Max(newPair.level, maxLevel); stack.Push(newPair); } else if (input[i] == ')') { Pair match = stack.Pop(); match.cIndex = i; } } // Step 2: build the output char[,] output = new char[maxLevel + 1, input.Length]; for (int i = 0; i < maxLevel + 1; i++) { for (int j = 0; j < input.Length; j++) { output[i, j] = ' '; } } var bfsQueue = new Queue<Pair>(); bfsQueue.Enqueue(root); while (bfsQueue.Count > 0) { var currentPair = bfsQueue.Dequeue(); if (currentPair.level != 0) { for (int i = currentPair.oIndex; i <= currentPair.cIndex; i++) { output[currentPair.level - 1, i] = '-'; } for (int i = currentPair.level - 1; i < maxLevel; i++) { output[i, currentPair.oIndex] = '|'; output[i, currentPair.cIndex] = '|'; } output[currentPair.level - 1, currentPair.oIndex] = '+'; output[currentPair.level - 1, currentPair.cIndex] = '+'; } foreach (var child in currentPair.children) { bfsQueue.Enqueue(child); } } for (int i = 0; i < input.Length; i++) { output[maxLevel, i] = input[i]; } // Step 3: Output for (int i = 0; i < maxLevel + 1; i++) { for (int j = 0; j < input.Length; j++) { Console.Write(output[i, j]); } Console.WriteLine(); } } } } }
using UnityEngine; using System.Collections; public class zonepointer : MonoBehaviour { // Use this for initialization public Transform gettransform () { Transform tosend = transform; return tosend; } void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; public class CameraBehaviour : MonoBehaviour { public Transform target; public float speed = 10f; // Use this for initialization void Start () { //Vector3 trPos = new Vector3 (target.position.x, target.position.y, -10); //transform.position = trPos; } // Update is called once per frame void LateUpdate () { Vector3 mousePos = GameObject.FindObjectOfType<Camera> ().ScreenToWorldPoint(Input.mousePosition); mousePos.z = -10; this.transform.position = Vector3.MoveTowards (this.transform.position, (target.position*2.5f + mousePos) /7*2 , speed * Time.deltaTime); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class ObjectPoolItem { public GameObject objetosParaAgrupar; public int quantosObjetos; public bool expanda; } public class ObjectPooler : MonoBehaviour { public static ObjectPooler compartilhada; public List<ObjectPoolItem> itensparAgrupar; public List<GameObject>objetosAgrupados; public bool expanda = true; void Awake() { compartilhada = this; } void Start() { objetosAgrupados = new List<GameObject>(); foreach(ObjectPoolItem item in itensparAgrupar) { for (int i = 0; i < item.quantosObjetos; i++) { GameObject obj = (GameObject)Instantiate(item.objetosParaAgrupar); obj.SetActive(false); objetosAgrupados.Add(obj); } } } public GameObject PegarObjetoAgrupado(string tag) { for (int i = 0; i < objetosAgrupados.Count; i++) { if (!objetosAgrupados[i].activeInHierarchy && objetosAgrupados[i].tag == tag) { return objetosAgrupados[i]; } } foreach(ObjectPoolItem item in itensparAgrupar) { if (item.objetosParaAgrupar.tag == tag) { if (item.expanda) { GameObject obj = (GameObject)Instantiate(item.objetosParaAgrupar); obj.SetActive(false); objetosAgrupados.Add(obj); return obj; } } } return null; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace kassasysteem.Classes { class Token { public string access_token = null; public string expires_in = null; public string refresh_token = null; } class Me { public string CurrentDivision = null; public string FullName = null; } static class OAuth { public static String Code = null, State = null, AccessToken = null, RefreshToken = null, CurrentDivision = null, FullName = null; private static Double ExpiredAt = DateTime.UtcNow.Ticks / 10000000; //============ getAccess =============================== static public async Task getAccess() { if (Code == null) { throw new ExactError("Code NULL"); } if (AccessToken == null) { await getToken(); } if (CurrentDivision == null) { await getMe(); } if ((DateTime.UtcNow.Ticks / 10000000) > ExpiredAt) { await getRefreshToken(); } } //============ getToken =============================== static public async Task getToken() { Uri request = new Uri(Constants.BASE_URI + "/api/oauth2/token"); HttpClient client = new HttpClient(); String poststring = "grant_type=authorization_code" + "&code=" + Code + "&redirect_uri=" + Constants.CALLBACK_URL + "&client_id={" + Constants.CLIENT_ID + "}" + "&client_secret=" + Constants.CLIENT_SECRET; StringContent content = new StringContent(poststring, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage respons = await client.PostAsync(request, content); if (respons.IsSuccessStatusCode == false) { throw new ExactError("getToken Mislukt: status = " + respons.StatusCode.ToString()); } respons.EnsureSuccessStatusCode(); string responsecontent = await respons.Content.ReadAsStringAsync(); Token token = JsonConvert.DeserializeObject<Token>(responsecontent); AccessToken = token.access_token; RefreshToken = token.refresh_token; string ExpiresIn = token.expires_in; ExpiredAt = System.Convert.ToDouble(ExpiresIn) + DateTime.UtcNow.Ticks / 10000000; } //============ getRefreshToken =============================== static public async Task getRefreshToken() { Uri request = new Uri(Constants.BASE_URI + "/api/oauth2/token"); HttpClient client = new HttpClient(); String poststring = "grant_type=refresh_token" + "&refresh_token=" + OAuth.RefreshToken + "&client_id={" + Constants.CLIENT_ID + "}" + "&client_secret=" + Constants.CLIENT_SECRET; StringContent content = new StringContent(poststring, System.Text.Encoding.UTF8, "Content-Type: application/x-www-form-urlencoded"); HttpResponseMessage respons = await client.PostAsync(request, content); if (respons.IsSuccessStatusCode == false) { throw new ExactError("refreshToken Mislukt: status = " + respons.StatusCode.ToString()); } respons.EnsureSuccessStatusCode(); string responsecontent = await respons.Content.ReadAsStringAsync(); Token token = JsonConvert.DeserializeObject<Token>(responsecontent); AccessToken = token.access_token; RefreshToken = token.refresh_token; string ExpiresIn = token.expires_in; ExpiredAt = System.Convert.ToDouble(ExpiresIn) + DateTime.UtcNow.Ticks / 10000000; } //============ getMe =============================== static public async Task getMe() { if ((DateTime.UtcNow.Ticks / 10000000) > ExpiredAt) await getRefreshToken(); Uri request = new Uri(Constants.BASE_URI + "/api/v1/current/Me?access_token=" + OAuth.AccessToken); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); HttpResponseMessage respons = await client.GetAsync(request); if (respons.IsSuccessStatusCode == false) { throw new ExactError("getMe Mislukt: status = " + respons.StatusCode.ToString()); } respons.EnsureSuccessStatusCode(); string responsecontent = await respons.Content.ReadAsStringAsync(); JObject content = JObject.Parse(responsecontent); IList<JToken> results = content["d"]["results"].Children().ToList(); JToken result = results[0]; Me me = JsonConvert.DeserializeObject<Me>(results[0].ToString()); CurrentDivision = me.CurrentDivision; FullName = me.FullName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary2 { public class MedicinskaSestra: Uposlenik { private string strucnaSprema; public MedicinskaSestra(string i, string p, DateTime dr, string mr, string JMBG, string u, string ps, string em, DateTime datum, string spp) : base(i, p, dr, mr, JMBG, u, ps, em, datum) { strucnaSprema = spp; } public string StrucnaSprema { get => strucnaSprema; set => strucnaSprema = value; } } }
using FatCat.Nes.OpCodes.Loading; using FluentAssertions; namespace FatCat.Nes.Tests.OpCodes.Loading { public class LoadAccumulatorTests : LoadingTests { protected override string ExpectedName => "LDA"; public LoadAccumulatorTests() => opCode = new LoadAccumulator(cpu, addressMode); protected override void VerifyCpuValueSet() => cpu.Accumulator.Should().Be(FetchedData); } }
using System; namespace IMDB.Api.Repositories.Interfaces { public interface IMoviePlotKeywordRepository : IGenericRepository<Entities.MoviePlotKeyword> { } }
using System.IO; namespace angular.euromade.ru.Models.Import.CommerceMLSource { /// <summary> /// Отвечает за загрузку файла CommerceML из базы данных /// </summary> /// <remarks> /// Пустой так как у меня отсутствует подключение к prod базе. /// Создан с целью продемонстрировать зачем был создан ICommerceMLSource /// (помимо этого ICommerceMLSource будет использоваться в mock unit тестах. /// </remarks> public class CommerceMLMSSQLSource : ICommerceMLSource { public MemoryStream GetSource() { throw new System.NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Server.MatchMaking { enum QueueType { Normal, BotGame, Nan2 } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HudManager : Manager<HudManager> { #region Labels & Values [Header("HudManager")] [Header("Texts")] [SerializeField] private Text m_TxtBestScore; [SerializeField] private Text m_TxtScore; [SerializeField] private Text m_TxtNLives; [SerializeField] private Text m_TxtNEnemiesLeftBeforeVictory; [Header("Health bar")] [SerializeField] private Slider m_Slider; [SerializeField] private Slider m_SliderBoss; [SerializeField] public GameObject m_Border; [Header("Texts Prefabs")] [SerializeField] public GameObject m_PrefScore; [SerializeField] public GameObject m_PrefGameOverScore; [SerializeField] public GameObject m_PrefNewBestScore; [Header("GameOverTexts")] [SerializeField] private Text m_TxtGameOverScore; [SerializeField] private Text m_TxtGameOverBestScore; private float _fadeMode; #endregion protected override void Awake() { base.Awake(); _fadeMode = 0.0f; m_Border.GetComponent<Image>().CrossFadeAlpha(_fadeMode, 0, true); SetImageState(m_Border.transform, true); } #region Manager implementation public void SetBorderBoss(bool state, bool init = false) { _fadeMode = (state) ? 1.0f : 0.0f; m_Border.GetComponent<Image>().CrossFadeAlpha(_fadeMode, 3.25f, false); SetImageState(m_Border.transform, init); } private void SetImageState(Transform transform, bool init) { float duration = (init) ? 0.0f : 3.5f; Image image = transform.gameObject.GetComponent<Image>(); if (image) image.CrossFadeAlpha(_fadeMode, duration, init); for (int i = 0; i < transform.childCount; i++) SetImageState(transform.GetChild(i), init); } #endregion #region Callbacks to GameManager events protected override void GameStatisticsChanged(GameStatisticsChangedEvent e) { m_TxtBestScore.text = e.eBestScore.ToString(); m_TxtGameOverBestScore.text = e.eBestScore.ToString(); m_TxtScore.text = e.eScore.ToString(); m_TxtGameOverScore.text = e.eScore.ToString(); m_TxtNLives.text = e.eNLives.ToString(); m_Slider.value = e.eNLives; } protected override void GameBossShoted(GameBossShotedEvent e) => m_SliderBoss.value = e.eNLives; protected override void NewBoss(NewBossEvent e) => m_SliderBoss.maxValue = e.eNLives; protected override IEnumerator InitCoroutine() { yield break; } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace WebApplication1.Controllers { [EnableCors(methods: "*", headers: "*", origins: "*")] public class UsersController : ApiController { public IHttpActionResult GettAllUsers() { return Ok(DB.userList); } [HttpPost] public IHttpActionResult UserFound(User u) { foreach (var i in DB.userList) { if (i.UserName == u.UserName) { if (i.Password == u.Password) return Ok(true); return Ok(u.Password); } } return Ok(false); } [HttpPost] public IHttpActionResult AddUser(User u) { DB.userList.Add(new User {UserName=u.UserName,Adress=u.Adress,Email=u.Email,Password=u.Password}); return Ok(u.UserName); } } }
// // System.Net.ListenerAsyncResult // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // Copyright (c) 2005 Ximian, Inc (http://www.ximian.com) // // // 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. // using System; using System.Threading; namespace Reactor.Net { class ListenerAsyncResult : IAsyncResult { private ManualResetEvent handle; private bool synch; private bool completed; private AsyncCallback cb; private object state; private Exception exception; private HttpListenerContext context; private object locker = new object(); private ListenerAsyncResult forward; internal bool EndCalled; internal bool InGet; public ListenerAsyncResult(AsyncCallback cb, object state) { this.cb = cb; this.state = state; } internal void Complete(Exception exc) { if (forward != null) { forward.Complete(exc); return; } exception = exc; if (InGet && (exc is ObjectDisposedException)) { exception = new HttpListenerException(500, "Listener closed"); } lock (locker) { completed = true; if (handle != null) { handle.Set(); } if (cb != null) { ThreadPool.UnsafeQueueUserWorkItem(InvokeCB, this); } } } static WaitCallback InvokeCB = new WaitCallback(InvokeCallback); static void InvokeCallback(object o) { ListenerAsyncResult ares = (ListenerAsyncResult)o; if (ares.forward != null) { InvokeCallback(ares.forward); return; } try { ares.cb(ares); } catch { } } internal void Complete(HttpListenerContext context) { Complete(context, false); } internal void Complete(HttpListenerContext context, bool synch) { if (forward != null) { forward.Complete(context, synch); return; } this.synch = synch; this.context = context; lock (locker) { AuthenticationSchemes schemes = context.Listener.SelectAuthenticationScheme(context); if ((schemes == AuthenticationSchemes.Basic || context.Listener.AuthenticationSchemes == AuthenticationSchemes.Negotiate) && context.Request.Headers["Authorization"] == null) { context.Response.StatusCode = 401; context.Response.Headers["WWW-Authenticate"] = schemes + " realm=\"" + context.Listener.Realm + "\""; context.Response.OutputStream.Close(); IAsyncResult ares = context.Listener.BeginGetContext(cb, state); this.forward = (ListenerAsyncResult)ares; lock (forward.locker) { if (handle != null) { forward.handle = handle; } } ListenerAsyncResult next = forward; for (int i = 0; next.forward != null; i++) { if (i > 20) { Complete(new HttpListenerException(400, "Too many authentication errors")); } next = next.forward; } } else { completed = true; this.synch = false; if (handle != null) { handle.Set(); } if (cb != null) { ThreadPool.UnsafeQueueUserWorkItem(InvokeCB, this); } } } } internal HttpListenerContext GetContext() { if (forward != null) { return forward.GetContext(); } if (exception != null) { throw exception; } return context; } public object AsyncState { get { if (forward != null) { return forward.AsyncState; } return state; } } public WaitHandle AsyncWaitHandle { get { if (forward != null) { return forward.AsyncWaitHandle; } lock (locker) { if (handle == null) { handle = new ManualResetEvent(completed); } } return handle; } } public bool CompletedSynchronously { get { if (forward != null) { return forward.CompletedSynchronously; } return synch; } } public bool IsCompleted { get { if (forward != null) { return forward.IsCompleted; } lock (locker) { return completed; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Asteroid_Joakim_Levin { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SoundEffect background_music; SoundEffect sound_city_hit; SoundEffect sound_asteroid_hit; SoundEffectInstance soundeffectinstance; Texture2D asteroid_texture; Texture2D background_texture; Texture2D city5_texture; Texture2D city4_texture; Texture2D city3_texture; Texture2D city2_texture; Texture2D city1_texture; Texture2D city0_texture; Rectangle city_boundingbox; HUD hud; int score; int life = 5; List<Asteroid> asteroid_list = new List<Asteroid>(); //Creates a list of Asteroids. Random random = new Random(); bool running = true; //When life = 0 the game stops by setting running to false. public Game1() { graphics = new GraphicsDeviceManager(this); this.Window.Title = "Asteroid Asteroids destroyed: " + score + " Buildings left: " + life; //Writes out text in the window title. //Sets the screen size. graphics.PreferredBackBufferHeight = 500; graphics.PreferredBackBufferWidth = 1220; graphics.IsFullScreen = false; random = new Random (); Content.RootDirectory = "Content"; } protected override void Initialize() { this.IsMouseVisible = true; //Makes the mouse cursor visible. base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); background_music = Content.Load<SoundEffect>(@"music_background"); //Loads the background music. sound_asteroid_hit = Content.Load<SoundEffect>(@"sound_asteroid_hit"); //Loads the sound that plays when an asteroid gets hit. sound_city_hit = Content.Load<SoundEffect>(@"sound_city_hit"); //Loads the sound that plays when an asteroid hits the city. asteroid_texture = Content.Load<Texture2D>(@"asteroid"); //Loads the asteroid texture. background_texture = Content.Load<Texture2D>(@"background"); //Loads the background texture. city5_texture = Content.Load<Texture2D>(@"city_5"); //Loads the city with 5 lives texture. city4_texture = Content.Load<Texture2D>(@"city_4"); //Loads the city with 4 lives texture. city3_texture = Content.Load<Texture2D>(@"city_3"); //Loads the city with 3 lives texture. city2_texture = Content.Load<Texture2D>(@"city_2"); //Loads the city with 2 lives texture. city1_texture = Content.Load<Texture2D>(@"city_1"); //Loads the city with 1 lives texture. city0_texture = Content.Load<Texture2D>(@"city_0"); //Loads the destroyed city texture. city_boundingbox = new Rectangle(0, 400, 1220, 300); //Creates a boundingbox for the city. //Creates four asteroids at the start of the game. for (int i = 0; i < 4; i++) asteroid_list.Add(new Asteroid(new Vector2(random.Next(720 - 70), -70), asteroid_texture)); soundeffectinstance = background_music.CreateInstance(); soundeffectinstance.IsLooped = true; //Makes the music_background loop during the game. soundeffectinstance.Play(); hud = new HUD(); hud.hudFont = Content.Load<SpriteFont>("TheFont"); } protected override void UnloadContent() { } float spawn = 0; protected override void Update(GameTime gameTime) { if (Keyboard.GetState().IsKeyDown(Keys.Escape)) //Click the Escape button to close the program. this.Exit(); KeyMouseReader.Update(); if (running) { spawn += (float)gameTime.ElapsedGameTime.TotalSeconds; foreach (Asteroid a in asteroid_list) { a.Update(gameTime); if (KeyMouseReader.LeftClick() || KeyMouseReader.RightClick()) { if (a.asteroid_boundingbox.Contains(KeyMouseReader.mouse_position)) //When you click this line will check to see if the mouse position is inside the asteroids boundingbox. { asteroid_list.Remove(a); //If the mouse position is inside the asteroids boundingbox, the asteroid is removed. sound_asteroid_hit.Play(); //It then plays the sound for asteroids getting hit. hud.Score += 1; //Increases the score in the HUD by one per destoryed asteroid. score = score + 1; //Increases the score in the window title by one per destroyed asteroid. this.Window.Title = "Asteroid Asteroids destroyed: " + score + " Buildings left: " + life; break; //Stops the if and updates the asteroid_list. } } if (a.asteroid_boundingbox.Intersects(city_boundingbox)) //When the asteroids boundingbox hits the city's boundingbox { asteroid_list.Remove(a); //The asteroid is removed. sound_city_hit.Play(); //Then the sound is played for when an asteroid hits the city. hud.Life -= 1; //Deceeases the amount of lives you have left in the HUD by one per asteroid that hits the city. life = life - 1; //Decreases the amount of lives you have left in the window title by one per asteroid that hits the city. this.Window.Title = "Asteroid Asteroids destroyed: " + score + " Buildings left: " + life; break; } } if (life == 0) //When you run out of lives, { this.Window.Title = "Asteroid Asteroids destroyed: " + score + " Buildings left: " + life + " The city is lost! Press Esc to run for your life!"; running = false; //the game stops. } } LoadAsteroid(); base.Update(gameTime); } //This makes sure that if there's less than three asteroids in-game it spawns asteroids untill there's seven of them. public void LoadAsteroid() { int randX = random.Next(50, 1170); if (spawn <= 2) { spawn = 0; if (asteroid_list.Count() < 7) { asteroid_list.Add(new Asteroid(new Vector2(randX, -100), asteroid_texture)); } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); spriteBatch.Begin(); spriteBatch.Draw(background_texture, new Vector2(0, 0), Color.White); //The game will draw out different city textures based of how many lives you have left. if (life == 5) { spriteBatch.Draw(city5_texture, new Vector2(0, 200), Color.White); } if (life == 4) { spriteBatch.Draw(city4_texture, new Vector2(0, 200), Color.White); } if (life == 3) { spriteBatch.Draw(city3_texture, new Vector2(0, 200), Color.White); } if (life == 2) { spriteBatch.Draw(city2_texture, new Vector2(0, 200), Color.White); } if (life == 1) { spriteBatch.Draw(city1_texture, new Vector2(0, 200), Color.White); } if (life == 0) { spriteBatch.Draw(city0_texture, new Vector2(0, 200), Color.White); } foreach (Asteroid a in asteroid_list) //Draws every asteroid in asteroid_list. a.Draw(spriteBatch); hud.Draw(spriteBatch); //Draws the HUD. spriteBatch.End(); base.Draw(gameTime); } } }
using RenovoTools.Common; namespace RenovoLive.Features.ServiceEvents.BusinessLayer.ServiceEventTransition.Validators.DMValidators { public class DMCompletedToClosedTransitionValidator : BaseDMToClosedTransitionValidator { public DMCompletedToClosedTransitionValidator(IServiceEventResourcesHelper resourcesHelper, IServiceEventHelper serviceEventHelper) : base(resourcesHelper, serviceEventHelper) { } public override ReturnStatus IsValidTransition(ServiceEvent serviceEvent, ServiceEventTransitionValidationArguments args) { var parentValidation = base.IsValidTransition(serviceEvent, args); if (parentValidation.WasSuccessful == false) { return parentValidation; } if (serviceEvent.Timeline.CompletedOn.HasValue == false) { return ReturnStatus.Fail(TransitionError.NoWorkCompletedTime); } if (serviceEvent.Timeline.CompletedOn <= serviceEvent.Timeline.ArrivedOn) { return ReturnStatus.Fail(TransitionError.CompletedBeforeArrived); } return ReturnStatus.Success(TransitionError.CannotJumpToClosed); } } }
using System; namespace ITWServer.Systems { public class SessionSystem : System { public SessionSystem(ITWServer server, Network.PacketHandler packetHander) : base(server, packetHander) { server.OnAcceptClient += OnAcceptClient; packetHander.Bind<ITW.Protocol.ToServer.Session.Connect>(Connect); packetHander.Bind<ITW.Protocol.ToServer.Session.Disconnect>(Disconnect); } private void OnAcceptClient(Vdb.Session session) { Console.WriteLine("AcceptClient : " + session.client.Client.Handle); } private bool Connect(Vdb.Session session, ITW.Protocol.ToServer.Session.Connect packet) { Console.Write("Connect : " + packet.Id); return true; } private bool Disconnect(Vdb.Session session, ITW.Protocol.ToServer.Session.Disconnect packet) { Console.Write("Disconnect : " + session.client.Client.Handle); server.CloseSession(session); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cas24 { class Program { static void Main(string[] args) { string Choice; do { Console.Clear(); Console.WriteLine("Qa Telefonski imenik \n"); Console.WriteLine("1.Unos novog imena"); Console.WriteLine("2.Listanje imenika"); Console.WriteLine("3. Pretraga"); Console.WriteLine("Q kraj rada"); Choice = Console.ReadLine(); switch (Choice.ToUpper()) { case "1": break; case "2": break; case "3": break; case "Q": break; default: break; } }while(Choice.ToUpper() != "Q"); static void AddNewName() { string FirstName, LastName, Adress, Phone; FirstName = Important.GetUserInput("Unesite ime"); LastName = Important.GetUserInput("Unesite prezime"); email = Important.GetUserInput("Unesite email"); FileX.Write(FirstName, LastName, email); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ServiceStack; namespace AddressBookWebService { public class SubmissionService: Service { public object Post(Submission submission) { return new SubmissionResponse() { Id = 1 }; } } }
using System; using System.Collections.Generic; using Ego.PDF; using Ego.PDF.Data; namespace Ego.PDF.Font { public class FontDefinition { public FontTypeEnum type { get; set; } public string name { get; set; } public int up { get; set; } public int ut { get; set; } public int i { get; set; } //file information public int n { get; set; } public int length1 { get; set; } public int length2 { get; set; } public object diff { get; set; } public int? diffn { get; set; } public string file { get; set; } public int size1 { get; set; } public int size2 { get; set; } public int originalsize { get; set; } public PHP.OrderedMap cw { get; set; } public Dictionary<string, int> Widths { get; set; } public Dictionary<string, string> desc { get; set; } public FontDefinition() { this.cw = new PHP.OrderedMap(); this.Widths = new Dictionary<string, int>(); this.desc = new Dictionary<string, string>(); } public void RegisterWidths() { foreach (string par in cw.Keys) { int width = Convert.ToInt32(cw[par]); this.Widths[par] = width; } } } }
using System; using System.Collections.Generic; using System.Text; namespace DEMO_DDD.DOMAIN.Entidades { public class Produto : Entity { public string Nome { get; set; } public decimal Valor { get; set; } public bool Disponivel { get; set; } public int ClienteId { get; set; } public Cliente Cliente { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("ClassProgressInfo")] public class ClassProgressInfo : MonoClass { public ClassProgressInfo(IntPtr address) : this(address, "ClassProgressInfo") { } public ClassProgressInfo(IntPtr address, string className) : base(address, className) { } public GameObject m_bone { get { return base.method_3<GameObject>("m_bone"); } } public TAG_CLASS m_class { get { return base.method_2<TAG_CLASS>("m_class"); } } public Material m_iconMaterial { get { return base.method_3<Material>("m_iconMaterial"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace App1 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AniView2 : ContentView { public AniView2() { InitializeComponent(); } void Ani_Clicked(object sender, System.EventArgs e) { var btn = sender as Button; var fate = double.Parse(btn.CommandParameter.ToString()); aniImg.FadeTo(fate, 2000); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyThreadPool { public class ThreadPoolFactory { public static IThreadPool CreatePool() { IThreadPool threadPool = null; threadPool = new WorkerThreadPool(); return threadPool; } } }
using SalaoG.Models; using SalaoG.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SalaoG.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Menu : MasterDetailPage { private ObservableCollection<ItensMenu> _menuLista; public Menu() { InitializeComponent(); _menuLista = ItensMenuService.GetMenuItens(); ListMenu.ItemsSource = _menuLista; //Detail = new NavigationPage(new MenuDetail()); Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(MenuDetail))); } private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = (ItensMenu)e.SelectedItem; //obtem o tipo de objeto Type pagina = item.TargetType; if (item.Title.ToUpper() == "Sair".ToUpper()) { System.Environment.Exit(0); } /* Abre uma pagina correspondente ao um item selecionado no listView cria uma isntancia do tipo selecioando usando o construtor */ Detail = new NavigationPage((Page)Activator.CreateInstance(pagina)); IsPresented = false; } } }
using System; public class UpYunBlocksUploadTaskInfo : UpYunTaskInfo { }
using System; class Program { public static void Main (string[] args) { Console.WriteLine ("Insira o custo:"); double custo = double.Parse(Console.ReadLine()); double distribuidor = custo*0.28; double imposto = custo*0.45; double consumidorpaga = custo+distribuidor+imposto; Console.WriteLine("O consumidor paga "+consumidorpaga); } }
using FreeCodeQuiz.Models; using Microsoft.EntityFrameworkCore; namespace FreeCodeQuiz.Data { public class FreeCodeQuizContext : DbContext { public FreeCodeQuizContext(DbContextOptions<FreeCodeQuizContext> options) : base(options) { } public DbSet<Question> Questions { get; set; } public DbSet<Category> Categories { get; set; } } }
using System; using System.Net; using System.Threading.Tasks; using System.Collections.Generic; using System.Diagnostics; using Newtonsoft.Json; using System.Net.Http; namespace MusicLib { public class SoundCloudDataProvider { //Endpoint to RESOLVE a track id or playlist id const string RESOLVE_URL_ENDPOINT = "http://api.soundcloud.com/resolve.json?url={0}&client_id={1}"; private Uri _uri; public SoundCloudDataProvider(string clientId, string resolveUrl) { string url = String.Format(RESOLVE_URL_ENDPOINT, resolveUrl, clientId); _uri = new Uri(url); } public async Task<T> LoadTrack<T>() { try { string data = await DownloadAsync(_uri); return JsonConvert.DeserializeObject<T>(data); } catch (Exception ex) { Debug.WriteLine("SoundCloudDataProvider.LoadTrack: {0}", ex); return default(T); } } public async Task<string> DownloadAsync(Uri url) { HttpClient client = new HttpClient(); var message = new HttpRequestMessage(HttpMethod.Get, url); using (var response = await client.SendAsync(message)) { return await response.Content.ReadAsStringAsync(); } } } }
namespace OCP.AppFramework.Db { /** * This is returned or should be returned when a find request finds more than one * row * @since 7.0.0 */ public class MultipleObjectsReturnedException : System.Exception , IMapperException { /** * Constructor * @param string msg the error message * @since 7.0.0 */ // public function __construct(msg){ // parent::__construct(msg); // } } }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Runtime.InteropServices; namespace NtApiDotNet.Win32.Security.Native { internal enum UserInformationClass { UserGeneralInformation = 1, UserPreferencesInformation, UserLogonInformation, UserLogonHoursInformation, UserAccountInformation, UserNameInformation, UserAccountNameInformation, UserFullNameInformation, UserPrimaryGroupInformation, UserHomeInformation, UserScriptInformation, UserProfileInformation, UserAdminCommentInformation, UserWorkStationsInformation, UserSetPasswordInformation, UserControlInformation, UserExpiresInformation, UserInternal1Information, UserInternal2Information, UserParametersInformation, UserAllInformation, UserInternal3Information, UserInternal4Information, UserInternal5Information, UserInternal4InformationNew, UserInternal5InformationNew, UserInternal6Information, UserExtendedInformation, UserLogonUIInformation } [StructLayout(LayoutKind.Sequential)] internal struct USER_FULL_NAME_INFORMATION { public UnicodeStringOut FullName; } [StructLayout(LayoutKind.Sequential)] internal struct USER_PRIMARY_GROUP_INFORMATION { public uint PrimaryGroupId; } [StructLayout(LayoutKind.Sequential)] internal struct USER_HOME_INFORMATION { public UnicodeStringOut HomeDirectory; public UnicodeStringOut HomeDirectoryDrive; } [StructLayout(LayoutKind.Sequential)] internal struct USER_SCRIPT_INFORMATION { public UnicodeStringOut ScriptPath; } [StructLayout(LayoutKind.Sequential)] internal struct USER_PROFILE_INFORMATION { public UnicodeStringOut ProfilePath; } [StructLayout(LayoutKind.Sequential)] internal struct USER_ADMIN_COMMENT_INFORMATION { public UnicodeStringOut AdminComment; } [StructLayout(LayoutKind.Sequential)] internal struct USER_WORKSTATIONS_INFORMATION { public UnicodeStringOut WorkStations; } [StructLayout(LayoutKind.Sequential)] internal struct USER_CONTROL_INFORMATION { public uint UserAccountControl; } [StructLayout(LayoutKind.Sequential)] internal struct USER_SET_PASSWORD_INFORMATION { public UnicodeStringInSecure Password; [MarshalAs(UnmanagedType.U1)] public bool PasswordExpired; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Zhouli.BLL; using Zhouli.BLL.Interface; using Zhouli.Common; using Zhouli.Common.ResultModel; using Zhouli.DbEntity.Models; using Zhouli.DI; using Zhouli.Dto.ModelDto; using ZhouliSystem.Data; using ZhouliSystem.Filters; using ZhouliSystem.Models; namespace Zhouli.Bms.Areas.BlogManager.Controllers { [VerificationLogin] [Area("Blog")] public class FriendshipLinkController : Controller { private readonly IBlogFriendshipLinkBLL _blogFriendshipLinkBLL; private readonly UserAccount _userAccount; public FriendshipLinkController(IBlogFriendshipLinkBLL blogFriendshipLinkBLL, UserAccount userAccount) { _blogFriendshipLinkBLL = blogFriendshipLinkBLL; _userAccount = userAccount; } public IActionResult Index() { return View(); } public IActionResult FriendshipLinkAdd() { return View(); } #region 获取友情链接分页数据 /// <summary> /// 获取友情链接分页数据 /// </summary> /// <param name="page"></param> /// <param name="limit"></param> /// <param name="searchstr"></param> /// <returns></returns> public IActionResult GetFriendshipLinkList(string page, string limit, string searchstr) { var messageModel = _blogFriendshipLinkBLL .GetFriendshipLinkList(page, limit, searchstr); return Ok(new { code = 0, msg = "获取成功", count = messageModel.Data.RowCount, data = messageModel.Data.Data }); } #endregion #region 添加友情链接 /// <summary> /// 添加友情链接 /// </summary> /// <param name="blog"></param> /// <returns></returns> public IActionResult AddorUpdateFriendshipLink(BlogFriendshipLinkDto blog) { var resModel = new ResponseModel(); var handleResult = _blogFriendshipLinkBLL.AddorEditFriendshipLink(blog, _userAccount.GetUserInfo().UserId); resModel.RetCode = handleResult.Result ? StatesCode.success : StatesCode.failure; resModel.RetMsg = handleResult.Msg; resModel.Data = handleResult.Data; return Ok(resModel); } #endregion #region 删除友情链接 /// <summary> /// 删除友情链接 /// </summary> /// <param name="FriendshipLinkId"></param> /// <returns></returns> public IActionResult DeleteFriendshipLink(List<string> friendshipLinkId) { var resModel = new ResponseModel(); //此处删除进行逻辑删除 var handleResult = _blogFriendshipLinkBLL.DelFriendshipLink(friendshipLinkId); resModel.RetCode = handleResult.Result ? StatesCode.success : StatesCode.failure; resModel.RetMsg = handleResult.Msg; return Ok(resModel); } #endregion #region 审核友情链接 /// <summary> /// 审核友情链接 /// </summary> /// <param name="FriendshipLinkId"></param> /// <returns></returns> public IActionResult SfFriendshipLink(int friendshipLinkId) { var resModel = new ResponseModel(); var handleResult = _blogFriendshipLinkBLL.SfFriendshipLinkList(friendshipLinkId); resModel.RetCode = handleResult.Result ? StatesCode.success : StatesCode.failure; resModel.RetMsg = handleResult.Msg; return Ok(resModel); } #endregion } }
using System.Collections; using System.Collections.Generic; using JetBrains.Annotations; using UnityEngine; [CreateAssetMenu(menuName = "Data/int")] public class IntData : ScriptableObject { public int value; public void SetVal(int val) { value = val; } public void IncrementVal() { value++; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Com2Com.ViewModel { public class SlaveDeviceViewModel { } }
public class CleanUp : GAction { public override bool PrePerform() { target = GWorld.Instance.GetResourceQueue("Puddles").RemoveResourse(); if (target == null) return false; return true; } public override bool PostPerform() { GWorld.Instance.GetWorld().ModifyState("puddles", -1); Destroy(target.gameObject); return true; } }
using Model.DataEntity; using Model.Models.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Uxnet.Web.Controllers; using Business.Helper; using Model.Helper; using TaskCenter.Properties; using Utility; namespace TaskCenter.Controllers { public class SampleController : SampleController<EIVOEntityDataContext> { // GET: Sample protected ModelSource models; protected SampleController() : base() { models = new ModelSource(modelsBase); } public ModelSource DataSource => models; public int DecryptKeyValue(QueryViewModel viewModel,out bool expired) { int keyID = viewModel.DecryptKeyValue(out long ticks); expired = (DateTime.Now.Ticks - ticks) > Settings.Default.TimeoutTicks; return keyID; } protected override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //System.Diagnostics.Debugger.Launch(); if (filterContext.Exception != null) { Logger.Error(filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.Result = new JsonResult { Data = new { result = false, message = filterContext.Exception?.Message, }, JsonRequestBehavior = JsonRequestBehavior.AllowGet, }; } } } }
using System.Xml.Serialization; namespace PlatformRacing3.Web.Responses.Procedures; public class DataAccessGetMyBlocks2Response : DataAccessDataResponse<DataAccessGetMyBlocks2Response.MyBlocksData> { [XmlElement("category")] public string Category { get; set; } private DataAccessGetMyBlocks2Response() { } public DataAccessGetMyBlocks2Response(string category) { this.Rows = new List<MyBlocksData>(); this.Category = category; } public void AddBlock(uint blockId) { this.Rows.Add(new MyBlocksData(blockId)); } public class MyBlocksData { [XmlElement("block_id")] public uint BlockId { get; set; } private MyBlocksData() { } public MyBlocksData(uint blockId) { this.BlockId = blockId; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace CLI.FileTypeSession { static class FileRecorder { public static void Recording(List<string> resultCalculate, string path) { File.AppendAllLines(path, resultCalculate); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using log4net; using Newtonsoft.Json; using SpiderCore.Cache; using SpiderCore.Extendsions; namespace SpiderCore.Scheduler { /// <summary> /// /// /// 存储结构:队列 /// 队列格式:spider:request:domain /// 数据示例: /// spider:request:www.mfniu.com /// spider:request:ma.mfniu.com /// /// </summary> public class RedisScheduler : IScheduler { private readonly ILog _logger = LogManager.GetLogger(typeof(RedisScheduler)); /// <summary> /// 当前网站索引 /// </summary> private int _currentIndex = 0; private string _currentRedisKey = ""; private readonly string _filename = "domain.txt"; private List<string> _domainList = new List<string>(); private const string RedisQueueRequestUrlFormat = "spider:request:{0}"; public RedisScheduler() { //load domain data LoadDomainList(); SetCurrentRedisKey(); } public bool Push(Request request) { try { if (request == null) return false; request.UrlHash = request.Url.ToMd5(); var json = JsonConvert.SerializeObject(request); var uri = new Uri(request.Url); var redisKey = string.Format(RedisQueueRequestUrlFormat, uri.Host).ToLower(); RedisContext.RedisDatabase.ListLeftPush(redisKey, json); if (_domainList.Contains(uri.Host) == false) { _domainList.Add(uri.Host); } return true; } catch (Exception ex) { _logger.Error(ex); } return false; } public Request Pop() { try { if (_domainList.Any() == false) return null; var json = RedisContext.RedisDatabase.ListRightPop(_currentRedisKey); if (string.IsNullOrEmpty(json)) return null; return JsonConvert.DeserializeObject<Request>(json); } catch (Exception ex) { _logger.Error(ex); } return null; } public void Switch() { if (_currentIndex >= _domainList.Count) { _currentIndex = 0; } else { _currentIndex++; } SetCurrentRedisKey(); } private void SetCurrentRedisKey() { if (_domainList.Count == 0 || _currentIndex >= _domainList.Count) return; var domain = _domainList[_currentIndex]; _currentRedisKey = string.Format(RedisQueueRequestUrlFormat, domain).ToLower(); } private void LoadDomainList() { if (File.Exists(_filename) == false) { File.WriteAllText(_filename, String.Empty, Encoding.UTF8); } _domainList = File.ReadAllLines(_filename, Encoding.UTF8).Distinct().Select(p => p.ToLower()).ToList(); } ~RedisScheduler() { using (var sw = new StreamWriter(_filename, false, Encoding.UTF8)) { _domainList.Distinct().ToList().ForEach(p => sw.WriteLine(p)); sw.Close(); sw.Dispose(); } } } }
using System.Collections.Generic; using System.Linq; using Project33.Data; using Project33.Services.Models; namespace Project33.Services { public class FavoritesService { private readonly FavoritesContext _FavoritesContext; public FavoritesService() { _FavoritesContext = new FavoritesContext(); } public List<Favorites> GetFavorites() { return _FavoritesContext.Favorites.Select(BuildFavor).ToList(); } private Favorites BuildFavor(Favorites f) { return new Favorites() { id = f.id, book_id = f.book_id, user_id = f.user_id, book_name = f.book_name }; } } }
using System; using System.Runtime.Serialization; namespace Jieshai.Exceptions { [Serializable] public class ObjectFilterSoftException : ValidateException { public ObjectFilterSoftException(string message) :base(message) { } public ObjectFilterSoftException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserFactory.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using CGI.Reflex.Core.Entities; namespace CGI.Reflex.Core.Tests.Factories { public class UserFactory : BaseFactory<User> { public UserFactory(AllFactories factories) : base(factories) { } protected override User CreateImpl() { return new User { UserName = Rand.String(10), Email = Rand.Email(), Company = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.UserCompany), IsLockedOut = false, Role = Factories.Role.Save() }; } } }
 namespace IndiePortable.Formatter.Binary.GraphIteration { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; internal class ObjectGraphIterator { public ObjectGraphIterator() { } public dynamic GetGraphData(object graphRoot) { } private dynamic GetGraphData(object currentObj, IList<dynamic> currentData, IEnumerable<ISurrogateSelector> surrogateSelectors) { } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Identity; namespace API.Entities { public class AppUser : IdentityUser<int> { public ICollection<Trip> UserTrips { get; set; } public ICollection<AppUserRole> UserRoles { get; set; } } }
using System.Data; using System.Data.Entity; using BookStore.Data.Migrations; using BookStore.Model; namespace BookStore.Data { internal class BookStoreDbContext : DbContext, IBookStoreDbContext { public BookStoreDbContext() : base("BookStoreConnection") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookStoreDbContext, Configuration>()); } public IDbSet<Book> Books { get; set; } public IDbSet<Author> Authors { get; set; } public IDbSet<Review> Reviews { get; set; } public new IDbSet<TEntity> Set<TEntity>() where TEntity : class { return base.Set<TEntity>(); } public DbContextTransaction BeginTransaction() { return this.Database.BeginTransaction(); } public DbContextTransaction BeginTransaction(IsolationLevel isolationLevel) { return this.Database.BeginTransaction(isolationLevel); } } }
namespace MvcTurbine.Diagnostic.Models { public class DiagnosticResult { public DiagnosticResult() { Passed = false; } public string Name { get; set; } public bool Passed { get; set; } public string Info { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Products_and_Categories.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Microsoft.EntityFrameworkCore; namespace Products_and_Categories.Controllers { public class HomeController : Controller { private ProdCatContext dbContext; public HomeController(ProdCatContext context) { dbContext = context; } [HttpGet] [Route("")] public IActionResult Index() { List<Product> dbProducts = dbContext.products.ToList(); NewProductModel viewModel = new NewProductModel(); viewModel.allProducts = dbProducts; return View("Index", viewModel); } [HttpPost] [Route("/create_product")] public IActionResult CreateProduct(Product newProd) { dbContext.Add(newProd); dbContext.SaveChanges(); return RedirectToAction("Index"); } [HttpGet] [Route("/products/{id}")] public IActionResult ViewProduct(int id) { ProductViewModel viewModel = new ProductViewModel(); Product thisProduct = dbContext.products.Include(a => a.catAssociation).ThenInclude(c => c.Category).FirstOrDefault(prod => prod.ProductId == id); List<Category> usedCategories = new List<Category>(); foreach(Association association in thisProduct.catAssociation) { usedCategories.Add(association.Category); } List<Category> allCats = dbContext.categories.Include(a => a.prodAssociation).ThenInclude(p => p.Product).ToList(); List<Category> unusedCategories =allCats.Except(usedCategories).ToList(); viewModel.Product = thisProduct; viewModel.CatsOfProd = usedCategories; viewModel.notMyCats = unusedCategories; return View("ViewProduct", viewModel); } [HttpPost] [Route("/update_product")] public IActionResult UpdateProduct(ProductViewModel newAssociation) //Using the view model to get access to association { dbContext.Add(newAssociation.association); //adding the association from the viewmodel dbContext.SaveChanges(); return RedirectToAction("ViewProduct", new{id = newAssociation.association.ProductId}); //redirecting the id of the product with its new category } [HttpGet] [Route("/categories")] public IActionResult Categories() { List<Category> dbCategories = dbContext.categories.ToList(); NewCategoryModel viewModel = new NewCategoryModel(); viewModel.allCategories = dbCategories; return View("Categories", viewModel); } [HttpPost] [Route("/create_category")] public IActionResult CreateCategory(Category newCat) { dbContext.Add(newCat); dbContext.SaveChanges(); return RedirectToAction("Categories"); } [HttpGet] [Route("/category/{id}")] public IActionResult ViewCategory(int id) { Console.WriteLine("**********VIEWING CATEGORIES***************"); CategoryViewModel viewModel = new CategoryViewModel(); Category thisCategory = dbContext.categories.Include(a => a.prodAssociation).ThenInclude(p => p.Product).FirstOrDefault(cat => cat.CategoryId == id); List<Product> usedProducts = new List<Product>(); foreach(Association association in thisCategory.prodAssociation) { usedProducts.Add(association.Product); } List<Product> allProds = dbContext.products.Include(a => a.catAssociation).ThenInclude(c => c.Category).ToList(); List<Product> unusedProducts = allProds.Except(usedProducts).ToList(); viewModel.Category = thisCategory; viewModel.ProdsOfCat = usedProducts; viewModel.notMyProds = unusedProducts; return View("ViewCategory", viewModel); } [HttpPost] [Route("/update_category")] public IActionResult UpdateCategory(ProductViewModel newAssociation) //Using the view model to get access to association { dbContext.Add(newAssociation.association); //adding the association from the viewmodel dbContext.SaveChanges(); return RedirectToAction("ViewCategory", new{id = newAssociation.association.CategoryId}); //redirecting the id of the product with its new category } public IActionResult Privacy() { return View(); } } }
 using System; namespace RecipeLibrary.Web { class UriHandler { public static Uri MakeRecipeURI(string recipeLink) { var uriBuilder = new UriBuilder { Host = String.Empty, Scheme = "http", Path = recipeLink }; return uriBuilder.Uri; } } }
using HtmlAgilityPack; using SGDE.ReadingCertifications.Extensions; using SGDE.ReadingCertifications.Models; using System.IO; using System.Linq; namespace SGDE.ReadingCertifications.Service { public class ServiceReadingCertificationsFromHtml { public CertificarionXLS CertificarionXLS { get; } = new CertificarionXLS(); public void ReadFile() { var filePath = "c:\\Temp\\CERT N°4 OFERTA 133.V1D.2022_1.html"; var html = File.ReadAllText(filePath); html = System.Web.HttpUtility.HtmlDecode(html); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); // CAPITULOS var nodesDetailCertification = htmlDocument.DocumentNode.SelectNodes("//td/span[@class='fc1538a29d-f953-4d11-a6b0-46c28732c2d0-5' or @class='fc1538a29d-f953-4d11-a6b0-46c28732c2d0-6']"); var subLists = nodesDetailCertification.ToList().ChunkBy(7); subLists = subLists.Where(x => x.Count == 7).ToList(); foreach (var list in subLists) { var partida = new Partida(list); CertificarionXLS.AddPartida(partida); } // SUBCAPITULOS nodesDetailCertification = htmlDocument.DocumentNode.SelectNodes("//td/span[@class='fc1538a29d-f953-4d11-a6b0-46c28732c2d0-7' or @class='fc1538a29d-f953-4d11-a6b0-46c28732c2d0-8' or @class='fc1538a29d-f953-4d11-a6b0-46c28732c2d0-9']"); subLists = nodesDetailCertification.ToList().ChunkBy(14); subLists = subLists.Where(x => x.Count == 14).ToList(); foreach (var list in subLists) { var partida = new Partida(list); CertificarionXLS.AddPartida(partida); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ExpVMsape.Context; using ExpVMsape.Models; namespace ExpVMsape.Controllers { public class HorariosMesController : Controller { private ExpContextULT db = new ExpContextULT(); // GET: HorariosMes [Authorize(Users = ("gerencia@diarionorte.com,ventas@diarionorte.com,m_benitez@diarionorte.com,admin@diarionorte.com,cac@diarionorte.com"))] public ActionResult Index() { //////// INICIO MÓDULO CREACION BATCH PLANILLAS HORARIOS //for (int i = 8; i < 13; i++) //{ // HorariosMes horarioMesCh = new HorariosMes(); // HorariosMes horarioMesCt = new HorariosMes(); // horarioMesCh.Periodo = new DateTime(2016, i, 1); // horarioMesCt.Periodo = new DateTime(2016, i, 1); // horarioMesCh.Editorial = "Chaco"; // horarioMesCt.Editorial = "Corrientes"; // db.HorariosMes.Add(horarioMesCt); // db.SaveChanges(); // db.HorariosMes.Add(horarioMesCh); // db.SaveChanges(); //} //for (int j = 1; j < 3; j++) //{ // HorariosMes horarioMesCh = new HorariosMes(); // HorariosMes horarioMesCt = new HorariosMes(); // horarioMesCh.Periodo = new DateTime(2017, j, 1); // horarioMesCt.Periodo = new DateTime(2017, j, 1); // horarioMesCh.Editorial = "Chaco"; // horarioMesCt.Editorial = "Corrientes"; // db.HorariosMes.Add(horarioMesCt); // db.SaveChanges(); // db.HorariosMes.Add(horarioMesCh); // db.SaveChanges(); //} //var listaHorarios = db.HorariosMes.ToList(); //int idHM = 0; //foreach (var item in db.InformeTallers.ToList().OrderBy(t => t.IdInformeTaller)) //{ // try // { // idHM = listaHorarios.Find(i => i.Periodo.Value.Year == item.FechaEdicion.Year & // i.Periodo.Value.Month == item.FechaEdicion.Month & // i.Editorial == item.Editorial).IdHMes; // } // catch (Exception) // { // return HttpNotFound(); // } // HorariosDias horariosDias = new HorariosDias(); // horariosDias.Fecha = item.FechaEdicion; // horariosDias.HoraInicio = item.Suplementos.FirstOrDefault().HoraInicioImp; // horariosDias.HoraFin = item.Suplementos.LastOrDefault().HoraFinImp; // horariosDias.IdHMes = idHM; // db.HorariosDias.Add(horariosDias); // HorariosMes planillaMes = db.HorariosMes.Find(idHM); // planillaMes.HorariosDias.Add(horariosDias); // db.Entry(planillaMes).State = EntityState.Modified; // db.SaveChanges(); //} ///////// fin MÓDULO CREACION BATCH PLANILLAS HORARIOS return View(db.HorariosMes.ToList()); } // GET: HorariosMes/Details/5 [Authorize(Users = ("gerencia@diarionorte.com,ventas@diarionorte.com,m_benitez@diarionorte.com,admin@diarionorte.com,cac@diarionorte.com"))] public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } HorariosMes horariosMes = db.HorariosMes.Find(id); if (horariosMes == null) { return HttpNotFound(); } int horas = 0; int minutos = 0; int acumHoras = 0; int acumMinutos = 0; decimal promHoras = 0; decimal promMinutos = 0; List<int> horasList = new List<int>(); List<int> minutosList = new List<int>(); foreach (var item in horariosMes.HorariosDias) { minutos = item.HoraFin.Minute; minutos -= item.HoraInicio.Minute; if (minutos < 0) { minutos += 60; horas = item.HoraFin.Hour; horas -= (item.HoraInicio.Hour + 1 ); if (horas < 0) { horas += 24; } } else { horas = item.HoraFin.Hour; horas -= (item.HoraInicio.Hour); if (horas < 0) { horas += 24; } } horasList.Add(horas); minutosList.Add(minutos); acumHoras += horas; acumMinutos += minutos; } promMinutos = ((decimal)acumMinutos / 60) ; ViewBag.totHoras = Math.Truncate(acumHoras + promMinutos); ViewBag.totMinutos = Math.Truncate(((acumHoras + promMinutos)- Math.Truncate(acumHoras + promMinutos)) *60); promHoras = (acumHoras + promMinutos) / (horariosMes.HorariosDias.Count()); ViewBag.promHoras = Math.Truncate( promHoras); ViewBag.promMin = Math.Truncate((promHoras - Math.Truncate(promHoras))*60); ViewBag.listaHoras = horasList; ViewBag.listaMinutos = minutosList; return View(horariosMes); } // GET: HorariosMes/Create [Authorize(Users = ("admin@diarionorte.com"))] public ActionResult Create() { return View(); } // POST: HorariosMes/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "IdHMes,Editorial,Periodo,TotHoras,TotMinutos")] HorariosMes horariosMes) { if (ModelState.IsValid) { db.HorariosMes.Add(horariosMes); db.SaveChanges(); return RedirectToAction("Index"); } return View(horariosMes); } // GET: HorariosMes/Edit/5 [Authorize(Users = ("admin@diarionorte.com"))] public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } HorariosMes horariosMes = db.HorariosMes.Find(id); if (horariosMes == null) { return HttpNotFound(); } return View(horariosMes); } // POST: HorariosMes/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Users = ("admin@diarionorte.com"))] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "IdHMes,Editorial,Periodo,TotHoras,TotMinutos")] HorariosMes horariosMes) { if (ModelState.IsValid) { db.Entry(horariosMes).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(horariosMes); } // GET: HorariosMes/Delete/5 [Authorize(Users = ("admin@diarionorte.com"))] public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } HorariosMes horariosMes = db.HorariosMes.Find(id); if (horariosMes == null) { return HttpNotFound(); } return View(horariosMes); } // POST: HorariosMes/Delete/5 [HttpPost, ActionName("Delete")] [Authorize(Users = ("admin@diarionorte.com"))] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { HorariosMes horariosMes = db.HorariosMes.Find(id); db.HorariosMes.Remove(horariosMes); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HeladacWeb.AppLogic { public class PrivacyApi { const string baseUrl = "https://api.lithic.com"; string apiKey = Utility.configuration["Lithic:"+ (Utility.isDevMode ? "sandbox" : "prod") + ":apiKey"]; RestClient client; public PrivacyApi() { client = new RestClient(baseUrl); } public void getNewCreateCardFromPrivacy() { var request = new RestRequest("v1/card", Method.POST); client.Timeout = -1; request.AddHeader("Authorization", "api-key "+ apiKey); request.AddHeader("Content-Type", "application/json"); request.RequestFormat = DataFormat.Json; request.AddJsonBody(new {memo= "New Card", spend_limit=1,spend_limit_duration= "TRANSACTION", state="OPEN",type ="SINGLE_USE"}); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); } } }
using Booking.Agency.Base.Data; using Booking.DataAccess; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.Services; namespace Booking.Agency { /// <summary> /// Summary description for MasterBackendService /// </summary> [WebService(Namespace = "http://bookingagency.com/webservices")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class MasterBackendService : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string CheckIfAgentUserIsValid(string Username, string Password) { bool isAuthenticared = Membership.ValidateUser(Username, Password); MembershipUser mu = Membership.GetUser(Username); if (!isAuthenticared) { return "Wrong username or password"; } if (mu != null) { if (mu.IsApproved == false) { return "Your account has been disabled!"; } else { string[] rolesArray = Roles.GetRolesForUser(mu.UserName); if (!rolesArray.Contains("AgentUser")) { return "Your account is not Agent User anymore, you cant login!"; } } } return "OK"; } [WebMethod] public MembershipUser ReturnAgentCreditelians(string Username) { MembershipUser mu = Membership.GetUser(Username); return Membership.GetUser(Username); } [WebMethod] public Guid ReturnAgentId(string Username) { MembershipUser mu = Membership.GetUser(Username); BaseRepository bs = new BaseRepository(); return (Guid)Membership.GetUser(Username).ProviderUserKey; } [WebMethod] public BookingAgencyUser ReturnBookingAgent(string Username) { using (var context = new BookingAgencyEntities()) { context.Configuration.ProxyCreationEnabled = false; return context.BookingAgencyUsers.Where(u => u.Username == Username).Single(); } } [WebMethod] public void UpdateMessageAsSeen(SentMessage UpdateMessageAsSeen) { BaseRepository bs = new BaseRepository(); bs.UpdateMessage(UpdateMessageAsSeen); } [WebMethod] public void SendMessageFromAgent(SentMessage message) { BaseRepository bs = new BaseRepository(); bs.SendMessage(message); } [WebMethod] public void CreateReservationFromAgent(Reservation reservation) { BaseRepository bs = new BaseRepository(); bs.CreateReservation(reservation); } [WebMethod] public void CreateAccomodationAndAssignOwner(Accomodation accomodation, Guid ownerId) { BaseRepository bs = new BaseRepository(); bs.CreateAccomodation(accomodation); bs.AssingAccomodationOwner(ownerId, accomodation.AccomodationId); } [WebMethod] public void UpdateAccomodation(Accomodation accomodation) { BaseRepository bs = new BaseRepository(); bs.UpdateAccomodation(accomodation); } [WebMethod] public List<Comment> GetCommentsForOwnerId(Guid ownerId) { BaseRepository bs = new BaseRepository(); return bs.GetCommentsForOwnerId(ownerId); } [WebMethod] public List<Reservation> GetReservationsForOwnerId(Guid ownerId) { BaseRepository bs = new BaseRepository(); return bs.GetReservationsForOwnerId(ownerId); } [WebMethod] public List<SentMessage> GetSentMessagesForOwnerId(Guid ownerId) { BaseRepository bs = new BaseRepository(); return bs.GetSentMessagesForOwnerId(ownerId); } [WebMethod] public List<Rating> GetRatingsForOwnerAccomodations(Guid ownerId) { BaseRepository bs = new BaseRepository(); return bs.GetRatingsForOwnerAccomodations(ownerId); } [WebMethod] public List<BookingAgencyUser> GetAllAccomodationUsers() { BaseRepository bs = new BaseRepository(); return bs.GetAllApprovedAccomodationUsers(); } [WebMethod] public void SaveImageForAccomodation(AccomodationImage ai) { BaseRepository bs = new BaseRepository(); bs.SaveImageForAccomodation(ai); } } }
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 LambdaAndLinq { public partial class Form1 : Form { public Form1() { InitializeComponent(); } class Person { public string Name { get; set; } public string LastName { get; set; } public byte Age { get; set; } } List<int> numbers = new List<int>() { 34, 32, 51122, 22, 1, 7876, 33552, 334, 2278, 66453, 7432, 9 }; List<Person> ppl = new List<Person>() { new Person() {Name="Vardenis",LastName="Pavardenis",Age=17}, new Person() {Name="Vard",LastName="enis",Age=25}, new Person() {Name="Vardenis",LastName="Pavandenis",Age=22}, new Person() {Name="Who's",LastName="this guy",Age=25}, new Person() {Name="Vardenis",LastName="fon Pavardenis XIV",Age=255}, new Person() {Name="Local",LastName="Barbarian",Age=55} }; private void button1_Click(object sender, EventArgs e) { listBox1.DataSource = null; listBox1.Items.Clear(); //foreach (int item in numbers) //{ // if (item%2 == 0) // { // listBox1.Items.Add(item); // } //} //same, but with lambda ( => ) listBox1.DataSource = numbers.FindAll(item => item % 2 == 0); } private void btnVardenis_Click(object sender, EventArgs e) { listBox1.DataSource = null; listBox1.Items.Clear(); //find all people with the name Vardenis // var rez = ppl.FindAll(People => People.Name == "Vardenis"); //combine name and last name into one string var rez = ppl.FindAll(item => item.Name == "Vardenis").Select(item => new { FullName = item.Name + " " + item.LastName, Age = item.Age }); foreach (var item in rez) { listBox1.Items.Add(item); } } private void btnSortPeople_Click(object sender, EventArgs e) { listBox1.DataSource = null; listBox1.Items.Clear(); foreach (var x in ppl.OrderBy(item => item.Name).ThenBy(item => item.Age)) { listBox1.Items.Add(x.Name + " " + x.LastName + " " + x.Age); } } private void button2_Click(object sender, EventArgs e) { listBox1.DataSource = null; listBox1.Items.Clear(); listBox1.DataSource = (from item in numbers where item % 2 == 0 select item).ToList(); } private void button3_Click(object sender, EventArgs e) { listBox1.DataSource = null; listBox1.Items.Clear(); foreach (var x in (from item in ppl where item.Name == "Vardenis" select item).ToList()) { listBox1.Items.Add(x.Name + " " + x.LastName + " " + x.Age); } } private void button4_Click(object sender, EventArgs e) { listBox1.DataSource = null; listBox1.Items.Clear(); var rez = (from item in ppl orderby item.LastName descending, item.Age ascending select item).ToList(); foreach (var item in rez) { listBox1.Items.Add(item.Name + " " + item.LastName + " " + item.Age); } } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlCommand sql_comm = new SqlCommand(); DataSet ds = new DataSet(); SqlConnection sql_conn = new SqlConnection(); SqlDataAdapter sql_adp = new SqlDataAdapter(); string str_conn; protected void Page_Load(object sender, EventArgs e) { /////////////////////////////////// if (Session["owner"] == "student") { sql_comm.Parameters.AddWithValue("@user", Session["usr"].ToString()); sql_comm.Parameters.AddWithValue("@pass", Session["pwd"].ToString()); try { str_conn = ConfigurationManager.AppSettings.Get(0); sql_conn.ConnectionString = str_conn; sql_comm.Connection = sql_conn; sql_comm.CommandType = CommandType.StoredProcedure; if (!IsPostBack) { sql_comm.CommandText = "hsp_readstd_chen_prop"; sql_adp.SelectCommand = sql_comm; sql_conn.Open(); sql_adp.Fill(ds, "t1"); sql_conn.Close(); Txtdaneshjoid.Text = ds.Tables["t1"].Rows[0].ItemArray[0].ToString().Trim(); Txtname.Text = ds.Tables["t1"].Rows[0].ItemArray[1].ToString().Trim(); Txtfamily.Text = ds.Tables["t1"].Rows[0].ItemArray[2].ToString().Trim(); Txtfathername.Text = ds.Tables["t1"].Rows[0].ItemArray[3].ToString().Trim(); int i; Drdday.Items.Clear(); Drdmonth.Items.Clear(); Drdyear.Items.Clear(); for (i = 1; i <= 9; i++) Drdyear.Items.Add("130" + i.ToString()); for (i = 10; i <= 70; i++) Drdyear.Items.Add("13" + i.ToString()); for (i = 1; i <= 12; i++) Drdmonth.Items.Add(i.ToString()); for (i = 1; i <= 31; i++) Drdday.Items.Add(i.ToString()); Drdday.Text = ds.Tables["t1"].Rows[0].ItemArray[6].ToString().Trim(); Drdmonth.Text = ds.Tables["t1"].Rows[0].ItemArray[5].ToString().Trim(); Drdyear.Text = ds.Tables["t1"].Rows[0].ItemArray[4].ToString().Trim(); Txtmail.Text = ds.Tables["t1"].Rows[0].ItemArray[7].ToString().Trim(); Txtphon.Text = ds.Tables["t1"].Rows[0].ItemArray[8].ToString().Trim(); ds.Clear(); } } catch (Exception exp) { Lbmsg.Text = exp.Message;// "خطا در انجام عملیات !"; } } else { Response.Redirect("studentER.aspx"); } } protected void btnregester_Click(object sender, EventArgs e) { try { sql_comm.Parameters.Clear(); sql_comm.CommandText = "hsp_writestd_chen_prop"; sql_comm.Parameters.AddWithValue("@user",Session["usr"].ToString()); sql_comm.Parameters.AddWithValue("@pass",Session["pwd"].ToString()); sql_comm.Parameters.AddWithValue("@name",Txtname.Text.Trim()); sql_comm.Parameters.AddWithValue("@family",Txtfamily.Text.Trim()); sql_comm.Parameters.AddWithValue("@father",Txtfathername.Text.Trim()); sql_comm.Parameters.AddWithValue("@bthy",Drdyear.Text.Trim()); sql_comm.Parameters.AddWithValue("@bthm",Drdmonth.Text.Trim()); sql_comm.Parameters.AddWithValue("@bthd",Drdday.Text.Trim()); sql_comm.Parameters.AddWithValue("@email", Txtmail.Text.Trim()); sql_comm.Parameters.AddWithValue("@tel",Txtphon.Text.Trim()); sql_conn.Open(); sql_comm.ExecuteNonQuery(); sql_conn.Close(); Lbmsg.Text = "مشخصات جدید شما با موفقییت ثبت شد"; } catch (Exception exp) { Lbmsg.Text = "خطا در انجام عملیات !"; } } protected void Drdmonth_SelectedIndexChanged(object sender, EventArgs e) { int i; if (Convert.ToInt32(Drdmonth.SelectedItem.Text) <= 6) { Drdday.Items.Clear(); for (i = 1; i <= 31; i++) Drdday.Items.Add(i.ToString()); } else if (Convert.ToInt32(Drdmonth.SelectedItem.Text) > 6 && Convert.ToInt32(Drdmonth.SelectedItem.Text) <= 11) { Drdday.Items.Clear(); for (i = 1; i <= 30; i++) Drdday.Items.Add(i.ToString()); } else { Drdday.Items.Clear(); for (i = 1; i <= 29; i++) Drdday.Items.Add(i.ToString()); } } protected void lbtn_logoff_Click1(object sender, EventArgs e) { try { sql_comm.Parameters.Clear(); sql_comm.CommandType = CommandType.StoredProcedure; sql_comm.CommandText = "sp_upd_std_online2"; sql_comm.Parameters.AddWithValue("@online", false); sql_comm.Parameters.AddWithValue("@usr", Session["usr"].ToString()); sql_comm.Parameters.AddWithValue("@pwd", Session["pwd"].ToString()); sql_conn.Open(); sql_comm.ExecuteNonQuery(); sql_conn.Close(); Session.Abandon(); Response.Redirect("LogOut.aspx"); } catch (Exception exp) { sql_conn.Close(); Lbmsg.Text = "خطا در انجام عملیات !"; } } }
using ProManager.Entities.Base; using System; using System.ComponentModel.DataAnnotations; namespace ProManager.Entities.Common { public class SystemRoles : BaseModel { [StringLength(80)] public string Name { get; set; } [StringLength(200)] public string Description { get; set; } public bool HasTenants { get; set; } public Int16 Type { get; set; } } }
using System; [CustomLuaClass] public enum DUTaskState { Waiting, Running, Pause, Complete, Cancel, Error }
using System; namespace CCCP.DAL.Entities { public class Registration { public int Id { get; set; } public int UserId { get; set; } public DateTime Timestamp { get; set; } public int SubmitCount { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LearningEnglishSpa { public class AppSettings { public string IdentityUrl { get; set; } public string VocabularyUrl { get; set; } public string WordImageUrl { get; set; } public string SpeechUrl { get; set; } public string TrainingUrl { get; set; } } }
using System; using System.Collections.Generic; //Write a program that shows the binary representation of given 16-bit signed integer number (the C# type short). class BinaryShort { static void Main(string[] args) { Console.WriteLine(InMemory(-32768)); Console.WriteLine(InMemory(0)); Console.WriteLine(InMemory(-1)); Console.WriteLine(InMemory(32767)); Console.WriteLine(InMemory(654)); } static string InMemory(int number) { List<char> numberInBinary = new List<char> { }; if (number >= 0) { numberInBinary = ConvertDecimalToBinary(number); while (numberInBinary.Count < 16) { numberInBinary.Add('0'); } } else { number = (int)Math.Pow(2, 16) / 2 + number; numberInBinary = ConvertDecimalToBinary(number); while (numberInBinary.Count < 15) { numberInBinary.Add('0'); } numberInBinary.Add('1'); } numberInBinary.Reverse(); return string.Join("", numberInBinary); } static List<char> ConvertDecimalToBinary(int number) { List<char> numberInHex = new List<char> { }; while (number != 0) { byte remainder = (byte)(number % 2); char remainderAsChar = (char)('0' + remainder); numberInHex.Add(remainderAsChar); number /= 2; } return numberInHex; } }
using System; using System.Diagnostics; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; using Spring.Core.IO; using Spring.Properties; namespace Spring.Objects.Factory.Config { /// <summary> /// Variable-Placeholder for spring.net, that loads variables for configuration from a validate-able json-file. /// </summary> public class JsonVariableSource : IVariableSource { private readonly JObject _variables; /// <summary> /// Ctor. /// </summary> /// <param name="location">location of the json-file.</param> public JsonVariableSource(IResource location) { if (location == null) { throw new ArgumentNullException(nameof(location)); } Location = location; _variables = LoadJson(Location); if (CanResolveVariable("$schema")) { string schemaLocation = ResolveVariable("$schema"); IResource schemaResource = new FileSystemResource(Location.File.Directory.FullName + "\\" + schemaLocation); ValidateResource(_variables, schemaResource); } } /// <summary> /// Convenience property. Gets a single location /// to read properties from. /// </summary> /// <value>A location to read properties from.</value> public IResource Location { get; } /// <summary> /// Before requesting a variable resolution, a client should /// ask, whether the source can resolve a particular variable name. /// </summary> /// <param name="name">the name of the variable to resolve</param> /// <returns><c>true</c> if the variable can be resolved, <c>false</c> otherwise</returns> public bool CanResolveVariable(string name) { JToken selectToken = _variables.SelectToken(name); return selectToken != null; } /// <summary> /// Resolves variable value for the specified variable name. /// </summary> /// <param name="name">The name of the variable to resolve.</param> /// <returns> /// The variable value if able to resolve, <c>null</c> otherwise. /// </returns> public string ResolveVariable(string name) { JToken selectToken = _variables.SelectToken(name); if (selectToken != null) { return selectToken.Value<string>(); } else { return null; } } private static JObject LoadJson(IResource location) { JObject variables; using (Stream stream = location.InputStream) { using (StreamReader sr = new StreamReader(stream)) { string json = sr.ReadToEnd(); variables = JsonConvert.DeserializeObject<JObject>(json); } } return variables; } private void ValidateResource(JObject variables, IResource schemaLocation) { JObject schemaObject; try { schemaObject = LoadJson(schemaLocation); } catch (Exception e) { Debug.WriteLine(Spring.Properties.Resources.Debug_Shema_Not_Found + Environment.NewLine + e); return; } JSchema schema = JSchema.Parse(schemaObject.ToString()); if (!variables.IsValid(schema)) { throw new FormatException(string.Format(Resources.Exception_Invalid_Json, schemaLocation.File.FullName)); } } } }
using System.Data.Entity.ModelConfiguration; using RMAT3.Models; namespace RMAT3.Data.Mapping { public class AuditTypeMap : EntityTypeConfiguration<AuditType> { public AuditTypeMap() { // Primary Key HasKey(t => t.AuditTypeId); // Properties Property(t => t.AddedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedCommentTxt) .HasMaxLength(100); Property(t => t.AuditTypeCd) .HasMaxLength(30); Property(t => t.AuditTypeTxt) .HasMaxLength(200); // Table & Column Mappings ToTable("AuditType", "OLTP"); Property(t => t.AuditTypeId).HasColumnName("AuditTypeId"); Property(t => t.AddedByUserId).HasColumnName("AddedByUserId"); Property(t => t.AddTs).HasColumnName("AddTs"); Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId"); Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt"); Property(t => t.UpdatedTs).HasColumnName("UpdatedTs"); Property(t => t.IsActiveInd).HasColumnName("IsActiveInd"); Property(t => t.EffectiveFromDt).HasColumnName("EffectiveFromDt"); Property(t => t.EffectiveToDt).HasColumnName("EffectiveToDt"); Property(t => t.AuditTypeCd).HasColumnName("AuditTypeCd"); Property(t => t.AuditTypeTxt).HasColumnName("AuditTypeTxt"); Property(t => t.IsWarrantyRequiredInd).HasColumnName("IsWarrantyRequiredInd"); Property(t => t.EventTypeId).HasColumnName("EventTypeId"); // Relationships HasOptional(t => t.EventType) .WithMany(t => t.AuditTypes) .HasForeignKey(d => d.EventTypeId); } } }
using System; using Microsoft.Xna.Framework; namespace DCL.Maths { public struct Quaternion { #region Fields //4 Factors (Real numbers of single precision) float fRe, fX, fY, fZ; #endregion #region Constants //Quaternions that represent the X, Y and Z axes public static readonly Quaternion i = new Quaternion(0, 1, 0, 0); public static readonly Quaternion j = new Quaternion(0, 0, 1, 0); public static readonly Quaternion k = new Quaternion(0, 0, 0, 1); #endregion #region Properties /****4 Factors (Real numbers of single precision)****/ /// <summary> /// Gets or sets the scalar (real) part of the quaternion /// </summary> public float Re { set { fRe = value; } get { return fRe; } } /// <summary> /// Gets or sets the i factor of the quaternion /// </summary> public float X { set { fX = value; } get { return fX; } } /// <summary> /// Gets or sets the j factor of the quaternion /// </summary> public float Y { set { fY = value; } get { return fY; } } /// <summary> /// Gets or sets the k factor of the quaternion /// </summary> public float Z { set { fZ = value; } get { return fZ; } } /// <summary> /// Gets the vector part of the quaternion as an instance of the Vector3 Structure (used in WP7) /// </summary> public Vector3 VectorPart { get { return new Vector3((float)X, (float)Y, (float)Z); } } /// <summary> /// The magnitude (absolute value) of the quaternion /// </summary> public float Abs { get { return (float)Math.Sqrt(fRe * fRe + fX * fX + fY * fY + fZ * fZ); } } #endregion #region Constructors /// <summary> /// Creates a quaternion, which has only the scalar (real) part /// </summary> /// <param name="RealNumber">A real number of single precision</param> public Quaternion(float RealNumber) { fRe = RealNumber; fX = 0; fY = 0; fZ = 0; } /// <summary> /// Creates a quaternion, which has only the vector part /// </summary> /// <param name="v">An instance of the Vector3 (used in WP7) structure</param> public Quaternion(Vector3 v) { fRe = 0; fX = v.X; fY = v.Y; fZ = v.Z; } /// <summary> /// Creates a quaternion by setting all the four factors /// </summary> /// <param name="Re">The scalar (real) part of the quaternion</param> /// <param name="X">The i factor</param> /// <param name="Y">The i factor</param> /// <param name="Z">The i factor</param> public Quaternion(float Re, float X, float Y, float Z) { fRe = Re; fX = X; fY = Y; fZ = Z; } #endregion #region Methods /// <summary> /// Returns the conjugate of the quaternion /// </summary> public Quaternion Conjugate() { return new Quaternion(fRe, -fX, -fY, -fZ); } /// <summary> /// Returns the inverse of the quaternion /// </summary> public Quaternion Reciprocal() { if (fRe == 0 && fX == 0 && fY == 0 && fZ == 0) throw new DivideByZeroException("Trying to find the reciprocal of a zero number"); Quaternion temp = this.Conjugate(); temp.Re /= (fRe * fRe + fX * fX + fY * fY + fZ * fZ); temp.X /= (fRe * fRe + fX * fX + fY * fY + fZ * fZ); temp.Y /= (fRe * fRe + fX * fX + fY * fY + fZ * fZ); temp.Z /= (fRe * fRe + fX * fX + fY * fY + fZ * fZ); return temp; } /// <summary> /// Returns the normalized (with the magnitude of 1) quaternion /// </summary> public Quaternion Normalize() { float a = Abs; return new Quaternion(fRe / a, fX / a, fY / a, fZ / a); } /// <summary> /// Calculates the rotation quaternion from the axis and the rotation angle /// </summary> /// <param name="Axis">The quaternion that represents axis; it may be denormalized</param> /// <param name="Angle">The angle of rotation in radians</param> public static Quaternion RotationQuaternion(Quaternion Axis, double Angle) { Quaternion normAxis = Axis.Normalize(); float sin = (float)Math.Sin(Angle/2); return new Quaternion((float)Math.Cos(Angle / 2), sin * normAxis.X, sin * normAxis.Y, sin * normAxis.Z); } /// <summary> /// Rotates the vector around the axis by the specified angle /// </summary> /// <param name="Source">The quaternion that represents the vector to be rotated</param> /// <param name="Axis">The quaternion that represents axis; it may be denormalized</param> /// <param name="Angle">The angle of rotation in radians</param> public static Quaternion Rotate(Quaternion Source, Quaternion Axis, double Angle) { Quaternion qRot = Quaternion.RotationQuaternion(Axis, Angle); return (qRot * Source * qRot.Conjugate()); } #endregion #region Operators public static Quaternion operator +(Quaternion l, Quaternion r) { return new Quaternion(l.Re + r.Re, l.X + r.X, l.Y + r.Y, l.Z + r.Z); } public static Quaternion operator -(Quaternion l, Quaternion r) { return new Quaternion(l.Re - r.Re, l.X - r.X, l.Y - r.Y, l.Z - r.Z); } public static Quaternion operator *(Quaternion l, Quaternion r) { return new Quaternion(l.Re * r.Re - l.X * r.X - l.Y * r.Y - l.Z * r.Z, l.Re * r.X + l.X * r.Re + l.Y * r.Z - l.Z * r.Y, l.Re * r.Y + l.Y * r.Re + l.Z * r.X - l.X * r.Z, l.Re * r.Z + l.Z * r.Re + l.X * r.Y - l.Y * r.X); } public static Quaternion operator *(float l, Quaternion r) { return new Quaternion(l * r.Re, l * r.X, l * r.Y, l * r.Z); } public static Quaternion operator *(Quaternion l, float r) { return new Quaternion(l.Re * r, l.X * r, l.Y * r, l.Z * r); } //public static Quaternion operator /(Quaternion l, Quaternion r) //{ //two variants? //} public static bool operator ==(Quaternion l, Quaternion r) { return (l.Re == r.Re && l.X == r.X && l.Y == r.Y && l.Z == r.Z); } public static bool operator !=(Quaternion l, Quaternion r) { return !(l == r); } #endregion #region Type casting //The quaternion can be created implicity from a vector or from a real number public static implicit operator Quaternion(float d) { return new Quaternion(d); } public static implicit operator Quaternion(Vector3 v) { return new Quaternion(0, v.X, v.Y, v.Z); } //An explicit convert from the quaternion to a vector; the real-part may be non-zero public static explicit operator Vector3(Quaternion q) { return new Vector3(q.fX, q.fY, q.fZ); } #endregion #region Overridden methods /// <summary> /// Returns the string representation of the quaternion /// </summary> public override string ToString() { string fmt = ""; if (fRe > 0) fmt += fRe.ToString()+" "; else if (fRe < 0) fmt += ("- " + (-fRe).ToString()) + " "; if (fX > 0) fmt += String.Format("{0}{1}i ", (fmt=="") ? "" : "+ ", (fX == 1) ? "" : fX.ToString()); else if (fX < 0) fmt += String.Format("- {0}i ", (fX == -1) ? "" : (-fX).ToString()); if (fY > 0) fmt += String.Format("{0}{1}j ", (fmt == "") ? "" : "+ ", (fY == 1) ? "" : fY.ToString()); else if (fY < 0) fmt += String.Format("- {0}j ", (fY == -1) ? "" : (-fY).ToString()); if (fZ > 0) fmt += String.Format("{0}{1}k", (fmt == "") ? "" : "+ ", (fZ == 1) ? "" : fZ.ToString()); else if (fZ < 0) fmt += String.Format("- {0}k", (fZ == -1) ? "" : (-fZ).ToString()); if (fmt == "") fmt = "0"; return fmt; } /// <summary> /// Returns the string representation of the quaternion with specified precision /// </summary> public string ToString(int Precision) { string fmt = ""; if (fRe > 0) fmt += Common.Round(fRe, Precision).ToString() + " "; else if (fRe < 0) fmt += ("- " + (-Common.Round(fRe, Precision)).ToString()) + " "; if (fX > 0) fmt += String.Format("{0}{1}i ", (fmt == "") ? "" : "+ ", (fX == 1) ? "" : Common.Round(fX, Precision).ToString()); else if (fX < 0) fmt += String.Format("- {0}i ", (fX == -1) ? "" : (-Common.Round(fX, Precision)).ToString()); if (fY > 0) fmt += String.Format("{0}{1}j ", (fmt == "") ? "" : "+ ", (fY == 1) ? "" : Common.Round(fY, Precision).ToString()); else if (fY < 0) fmt += String.Format("- {0}j ", (fY == -1) ? "" : (-Common.Round(fY, Precision)).ToString()); if (fZ > 0) fmt += String.Format("{0}{1}k", (fmt == "") ? "" : "+ ", (fZ == 1) ? "" : Common.Round(fZ, Precision).ToString()); else if (fZ < 0) fmt += String.Format("- {0}k", (fZ == -1) ? "" : (-Common.Round(fZ, Precision)).ToString()); if (fmt == "") fmt = "0"; return fmt; } /// <summary> /// Defines if the current instance of quaternion is equal to the parameter /// </summary> public override bool Equals(object obj) { return obj is Quaternion && this == (Quaternion)obj; } /// <summary> /// Returns the hash code of the current instance of quaternion /// </summary> public override int GetHashCode() { return (int)fRe ^ (int)fX ^ (int)fY ^ (int)fZ; } #endregion } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using UnityEditor; using UnityEngine; namespace EnhancedEditor.Editor { /// <summary> /// Special <see cref="EnhancedPropertyDrawer"/> for fields with the attribute <see cref="ToggleButtonAttribute"/>. /// </summary> [CustomDrawer(typeof(ToggleButtonAttribute))] public class ToggleButtonPropertyDrawer : EnhancedPropertyDrawer { #region Decorator Content public override bool OnGUI(Rect _position, SerializedProperty _property, GUIContent _label, out float _height) { // Uncompatible property management. if (_property.propertyType != SerializedPropertyType.Boolean) { _height = 0f; return false; } ToggleButtonAttribute _attribute = Attribute as ToggleButtonAttribute; _position = EditorGUI.PrefixLabel(_position, _label); _position.size = new Vector2(_attribute.Width, _attribute.Height); using (var _scope = new EditorGUI.PropertyScope(_position, _label, _property)) { bool _value = _property.boolValue; bool _newValue = GUI.Toggle(_position, _value, EditorGUIUtility.IconContent(_attribute.IconName), EnhancedEditorStyles.ToolbarControl); if (_newValue != _value) { _property.boolValue = _newValue; } } _height = _position.height; return true; } #endregion } }
namespace Terminal.Interactive.PoorMans { public interface IMetaNode { IMetaNode Traverse(string[] path); object GetValue(); } }
using UnityEngine; using System.Collections; public class HeroMove : MonoBehaviour { //Player Movement public float moveSpeed; public float jumpHeight; public float moveVelocity; //Ground Check public Transform groundCheck; public float groundCheckRadius; public LayerMask whatIsGround; private bool grounded; //Double Jump private bool doubleJumped; //Player Animation //private Animator anim; void Start() { //anim = GetComponent<Animator>(); } void FixedUpdate() { grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround); } void Update() { //Stops player from sticking to the wall moveVelocity = 0f; //Move Right if (Input.GetKey(KeyCode.D)) { //GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y); //Debug.Log("I moved right"); moveVelocity = moveSpeed; } //Move Left if (Input.GetKey(KeyCode.A)) { //GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y); //Debug.Log("I moved left"); moveVelocity = -moveSpeed; } //Move Right if (Input.GetKey(KeyCode.RightArrow)) { //GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y); //Debug.Log("I moved right"); moveVelocity = moveSpeed; } //Move Left if (Input.GetKey(KeyCode.LeftArrow)) { //GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y); //Debug.Log("I moved left"); moveVelocity = -moveSpeed; } //Stops Player from sticking to the wall GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D> ().velocity.y); // Jump if (Input.GetKeyDown(KeyCode.Space) && grounded) { GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight); //Debug.Log("I jumped"); } //Player Walk Animation //anim.SetFloat("Speed", Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x)); //Player Flip if (GetComponent<Rigidbody2D>().velocity.x > 0) transform.localScale = new Vector3(1f, 1f, 1f); else if (GetComponent<Rigidbody2D>().velocity.x < 0) transform.localScale = new Vector3(-1f, 1f, 1f); //Double Jump if (grounded) doubleJumped = false; if (Input.GetKeyDown(KeyCode.Space) && !doubleJumped && !grounded) { GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight); doubleJumped = true; //Debug.Log("I jumped twice"); } //Player Jump Animation //anim.SetBool("Grounded", grounded); } /*void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "bat") { GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight); } }*/ }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SMSEntities.SMSDBEntities; using MySql.Data.MySqlClient; using System.Data; using System.Configuration; namespace SMSDAL.SMSDB { public class VisitorCheckInOutDBA { // `AddVisitorCheckInOut`(IN p_name VARCHAR(100),IN p_address VARCHAR(500), IN p_fromcompany VARCHAR(100), //IN p_tocompany INT, IN p_telno VARCHAR(20),IN p_persontovisit VARCHAR(100), IN p_eventid INT, IN p_temp INT, //IN p_visitortype INT, IN p_keys VARCHAR(100), IN p_passid INT, IN p_gateid INT, IN p_vehicleplatenumber VARCHAR(20), //IN p_guardname VARCHAR(100),IN p_remarks VARCHAR(500), IN p_checkintime DATETIME, IN p_checkouttime DATETIME) public int InsertVisitorCheckInOut(VisitorCheckInOut p_VisitorCheckInOut) { try { int result = 0; MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("p_nricid",p_VisitorCheckInOut.nricid), new MySqlParameter("p_name",p_VisitorCheckInOut.name), new MySqlParameter("p_address",p_VisitorCheckInOut.address), new MySqlParameter("p_fromcompany",p_VisitorCheckInOut.fromcompany), new MySqlParameter("p_tocompany",p_VisitorCheckInOut.tocompany), new MySqlParameter("p_telno",p_VisitorCheckInOut.telno), new MySqlParameter("p_persontovisit",p_VisitorCheckInOut.persontovisit), new MySqlParameter("p_eventid",p_VisitorCheckInOut.eventid), new MySqlParameter("p_temp",p_VisitorCheckInOut.temp), new MySqlParameter("p_visitortype",p_VisitorCheckInOut.visitortypeID), new MySqlParameter("p_keyid",p_VisitorCheckInOut.keyid), new MySqlParameter("p_passid",p_VisitorCheckInOut.passid), new MySqlParameter("p_gateid",p_VisitorCheckInOut.gateid), new MySqlParameter("p_vehicleplatenumber",p_VisitorCheckInOut.vehicleplatenumber), new MySqlParameter("p_guardname",p_VisitorCheckInOut.guardname), new MySqlParameter("p_remarks",p_VisitorCheckInOut.remarks), new MySqlParameter("p_checkintime",p_VisitorCheckInOut.checkintime), new MySqlParameter("p_checkouttime",p_VisitorCheckInOut.checkouttime), new MySqlParameter("p_snapshotpath",p_VisitorCheckInOut.snapshotpath), new MySqlParameter("p_deploymentid",p_VisitorCheckInOut.deploymentid), new MySqlParameter("p_blockorphone",p_VisitorCheckInOut.blockorphone), new MySqlParameter("p_fullnricid",p_VisitorCheckInOut.fullnricid), //new MySqlParameter("p_visitingcompany",p_VisitorCheckInOut.visitingcompany), new MySqlParameter("p_purpose",p_VisitorCheckInOut.purpose), new MySqlParameter("p_IsBlockGuest",p_VisitorCheckInOut.IsBlockGuest), new MySqlParameter("p_BlockType",p_VisitorCheckInOut.BlockType), new MySqlParameter("p_BlockRemarks",p_VisitorCheckInOut.BlockRemarks), new MySqlParameter("p_BlockDays",0), new MySqlParameter("p_BlockedDate",p_VisitorCheckInOut.BlockedDate), new MySqlParameter("p_UnblockedDate",p_VisitorCheckInOut.UnblockedDate), new MySqlParameter("p_result",MySqlDbType.Int32, 2,ParameterDirection.Output,false,1,1,"Out",DataRowVersion.Default,result) }; return MySQLDB.MySQLDBHelper.ExecuteNonQuery("AddVisitorCheckInOut", CommandType.StoredProcedure, parameters); } catch (Exception ex) { throw ex; } } public int UpadateVisitorCheckInOut(VisitorCheckInOut p_VisitorCheckInOut) { int result = 0; MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("p_nricid",p_VisitorCheckInOut.nricid), new MySqlParameter("p_name",p_VisitorCheckInOut.name), new MySqlParameter("p_address",p_VisitorCheckInOut.address), new MySqlParameter("p_fromcompany",p_VisitorCheckInOut.fromcompany), new MySqlParameter("p_tocompany",p_VisitorCheckInOut.tocompany), new MySqlParameter("p_telno",p_VisitorCheckInOut.telno), new MySqlParameter("p_persontovisit",p_VisitorCheckInOut.persontovisit), new MySqlParameter("p_eventid",p_VisitorCheckInOut.eventid), new MySqlParameter("p_temp",p_VisitorCheckInOut.temp), new MySqlParameter("p_visitortype",p_VisitorCheckInOut.visitortypeID), new MySqlParameter("p_keyid",p_VisitorCheckInOut.keyid), new MySqlParameter("p_passid",p_VisitorCheckInOut.passid), new MySqlParameter("p_gateid",p_VisitorCheckInOut.gateid), new MySqlParameter("p_vehicleplatenumber",p_VisitorCheckInOut.vehicleplatenumber), new MySqlParameter("p_guardname",p_VisitorCheckInOut.guardname), new MySqlParameter("p_remarks",p_VisitorCheckInOut.remarks), new MySqlParameter("p_checkintime",p_VisitorCheckInOut.checkintime), new MySqlParameter("p_checkouttime",p_VisitorCheckInOut.checkouttime), new MySqlParameter("p_snapshotpath",p_VisitorCheckInOut.snapshotpath), new MySqlParameter("p_deploymentid",p_VisitorCheckInOut.deploymentid), new MySqlParameter("p_blockorphone",p_VisitorCheckInOut.blockorphone), //new MySqlParameter("p_visitingcompany",p_VisitorCheckInOut.visitingcompany), new MySqlParameter("p_purpose",p_VisitorCheckInOut.purpose), new MySqlParameter("p_IsBlockGuest",Convert.ToBoolean(p_VisitorCheckInOut.IsBlockGuest)), new MySqlParameter("p_BlockType",p_VisitorCheckInOut.BlockType), new MySqlParameter("p_BlockRemarks",p_VisitorCheckInOut.BlockRemarks), new MySqlParameter("p_BlockDays",p_VisitorCheckInOut.BlockDays), new MySqlParameter("p_BlockedDate",p_VisitorCheckInOut.BlockedDate), new MySqlParameter("p_UnblockedDate",p_VisitorCheckInOut.UnblockedDate), new MySqlParameter("p_result",MySqlDbType.Int32, 2,ParameterDirection.Output,false,1,1,"Out",DataRowVersion.Default,result) }; return MySQLDB.MySQLDBHelper.ExecuteNonQuery("UpdateVisitorCheckInOut", CommandType.StoredProcedure, parameters); } public int DeleteVisitorCheckInOut(int p_NRICID) { MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("p_nricid", p_NRICID)}; return MySQLDB.MySQLDBHelper.ExecuteNonQuery("DeleteVisitorCheckInOut", CommandType.StoredProcedure, parameters); } public List<VisitorCheckInOut> SelectVisitorCheckInOut(int currentUserType, int deploymentId) { MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("currentUserType", currentUserType), new MySqlParameter("p_deploymentId", deploymentId) }; List<VisitorCheckInOut> VisitorCheckInOutCol = new List<VisitorCheckInOut>(); DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetVisitorCheckInOut", CommandType.StoredProcedure, parameters); VisitorCheckInOut objVisitorCheckInOut = null; foreach (DataRow dr in dt.Rows) { objVisitorCheckInOut = new VisitorCheckInOut(); objVisitorCheckInOut.visitorid = Convert.ToInt32(dr["visitorid"].ToString()); objVisitorCheckInOut.nricid = dr["nricid"].ToString(); objVisitorCheckInOut.passid = dr["passid"] != null && dr["passid"].ToString() != "" ? Convert.ToInt32(dr["passid"].ToString()) : 0; objVisitorCheckInOut.address = dr["address"].ToString(); objVisitorCheckInOut.blockorphone = dr["blockorphone"].ToString(); objVisitorCheckInOut.checkintime = Convert.ToDateTime(dr["checkintime"].ToString()); if (dr["checkouttime"].ToString() != null && dr["checkouttime"].ToString() != "") { objVisitorCheckInOut.checkouttime = Convert.ToDateTime(dr["checkouttime"].ToString()); } objVisitorCheckInOut.eventid = dr["eventid"] != null && dr["eventid"].ToString() != "" ? Convert.ToInt32(dr["eventid"].ToString()) : 0; objVisitorCheckInOut.fromcompany = dr["fromcompany"].ToString(); objVisitorCheckInOut.gateid = dr["gateid"] != null && dr["gateid"].ToString() != "" ? Convert.ToInt32(dr["gateid"].ToString()) : 0; objVisitorCheckInOut.guardname = dr["guardname"].ToString(); objVisitorCheckInOut.keyid = dr["keyid"] != null && dr["keyid"].ToString() != "" ? Convert.ToInt32(dr["keyid"].ToString()) : 0; objVisitorCheckInOut.name = dr["name"].ToString(); objVisitorCheckInOut.persontovisit = dr["persontovisit"].ToString(); objVisitorCheckInOut.remarks = dr["remarks"].ToString(); objVisitorCheckInOut.telno = dr["telno"].ToString(); objVisitorCheckInOut.temp = dr["temp"] != null && dr["temp"].ToString() != "" ? Convert.ToInt32(dr["temp"].ToString()) : 0; //objVisitorCheckInOut.tocompany = Convert.ToInt32(dr["tocompany"].ToString()); objVisitorCheckInOut.snapshotpath = dr["snapshotpath"].ToString(); if (dr["NRICFront"].ToString() != null && dr["NRICFront"].ToString() != "") { objVisitorCheckInOut.NRICFront = ConfigurationManager.AppSettings["GetNRICPath"] + "/" + dr["NRICFront"].ToString(); } if (dr["NRICBack"].ToString() != null && dr["NRICBack"].ToString() != "") { objVisitorCheckInOut.NRICBack = ConfigurationManager.AppSettings["GetNRICPath"] + "/" + dr["NRICBack"].ToString(); } objVisitorCheckInOut.deploymentid = dr["deploymentid"] != null && dr["deploymentid"].ToString() != "" ? Convert.ToInt32(dr["deploymentid"]) : 0; // objVisitorCheckInOut.visitortypeID = Convert.ToInt32(dr["visitortypeID"].ToString()); //objVisitorCheckInOut.visitingcompany = dr["visitingcompany"].ToString(); objVisitorCheckInOut.purpose = dr["purpose"].ToString(); objVisitorCheckInOut.IsBlockGuest = dr["IsBlockGuest"] != null && dr["IsBlockGuest"].ToString() != "" ? Convert.ToInt32(dr["IsBlockGuest"]) : 0; objVisitorCheckInOut.BlockType = dr["BlockType"].ToString(); objVisitorCheckInOut.BlockDays = dr["BlockDays"] != null && dr["BlockDays"].ToString() != "" ? Convert.ToInt32(dr["BlockDays"].ToString()) : 0; objVisitorCheckInOut.BlockRemarks = dr["BlockRemarks"].ToString(); if (dr["BlockedDate"].ToString() != null && dr["BlockedDate"].ToString() != "") { objVisitorCheckInOut.BlockedDate = Convert.ToDateTime(dr["BlockedDate"]); } if (dr["UnblockedDate"].ToString() != null && dr["UnblockedDate"].ToString() != "") { objVisitorCheckInOut.UnblockedDate = Convert.ToDateTime(dr["UnblockedDate"]); } VisitorCheckInOutCol.Add(objVisitorCheckInOut); } dt.Clear(); dt.Dispose(); return VisitorCheckInOutCol; } public List<VisitorCheckInOut> SelectVisitorCheckInOutByFilters(int currentUserType, int deploymentId, int startdate, int startmonth, int startyear, int enddate, int endmonth, int endyear) { MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("currentUserType", currentUserType), new MySqlParameter("p_deploymentId", deploymentId) }; List<VisitorCheckInOut> VisitorCheckInOutCol = new List<VisitorCheckInOut>(); DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetVisitorCheckInOut", CommandType.StoredProcedure, parameters); VisitorCheckInOut objVisitorCheckInOut = null; int i = 1; switch (startmonth) { case 2: if (startdate > 28) { if (startyear % 4 == 0) startdate = 29; else startdate = 28; } break; case 4: case 6: case 9: case 11: if (startdate > 30) startdate = 30; break; default: break; } DateTime startDate = new DateTime(); try { startDate = new DateTime(startyear, startmonth, startdate); } catch (Exception ex) { } switch (endmonth) { case 2: if (enddate > 28) { if (endyear % 4 == 0) enddate = 29; else enddate = 28; } break; case 4: case 6: case 9: case 11: if (enddate > 30) enddate = 30; break; default: break; } DateTime endDate = new DateTime(); try { endDate = new DateTime(endyear, endmonth, enddate); } catch (Exception ex) { } foreach (DataRow dr in dt.Rows) { DateTime dte = Convert.ToDateTime(dr["checkintime"].ToString()); if (dte != null) { //if (startDate == dte || endDate == dte || (startDate < dte && endDate > dte)) if (startDate == dte || endDate == dte || startDate < dte) { objVisitorCheckInOut = new VisitorCheckInOut(); objVisitorCheckInOut.visitorid = Convert.ToInt32(dr["visitorid"].ToString()); objVisitorCheckInOut.nricid = dr["nricid"].ToString(); objVisitorCheckInOut.passid = dr["passid"] != null && dr["passid"].ToString() != "" ? Convert.ToInt32(dr["passid"].ToString()) : 0; objVisitorCheckInOut.address = dr["address"].ToString(); objVisitorCheckInOut.blockorphone = dr["blockorphone"].ToString(); objVisitorCheckInOut.checkintime = Convert.ToDateTime(dr["checkintime"].ToString()); if (dr["checkouttime"].ToString() != null && dr["checkouttime"].ToString() != "") { objVisitorCheckInOut.checkouttime = Convert.ToDateTime(dr["checkouttime"].ToString()); } objVisitorCheckInOut.eventid = dr["eventid"] != null && dr["eventid"].ToString() != "" ? Convert.ToInt32(dr["eventid"].ToString()) : 0; objVisitorCheckInOut.fromcompany = dr["fromcompany"].ToString(); objVisitorCheckInOut.gateid = dr["gateid"] != null && dr["gateid"].ToString() != "" ? Convert.ToInt32(dr["gateid"].ToString()) : 0; objVisitorCheckInOut.guardname = dr["guardname"].ToString(); objVisitorCheckInOut.keyid = dr["keyid"] != null && dr["keyid"].ToString() != "" ? Convert.ToInt32(dr["keyid"]) : 0; objVisitorCheckInOut.name = dr["name"].ToString(); objVisitorCheckInOut.persontovisit = dr["persontovisit"].ToString(); objVisitorCheckInOut.remarks = dr["remarks"].ToString(); objVisitorCheckInOut.telno = dr["telno"].ToString(); objVisitorCheckInOut.temp = dr["temp"] != null && dr["temp"].ToString() != "" ? Convert.ToInt32(dr["temp"].ToString()) : 0; //objVisitorCheckInOut.tocompany = Convert.ToInt32(dr["tocompany"].ToString()); objVisitorCheckInOut.snapshotpath = dr["snapshotpath"].ToString(); objVisitorCheckInOut.deploymentid = dr["deploymentid"] != null && dr["deploymentid"].ToString() != "" ? Convert.ToInt32(dr["deploymentid"]) : 0; //objVisitorCheckInOut.visitingcompany = dr["visitingcompany"].ToString(); objVisitorCheckInOut.purpose = dr["purpose"].ToString(); objVisitorCheckInOut.IsBlockGuest = dr["IsBlockGuest"] != null && dr["IsBlockGuest"].ToString() != "" ? Convert.ToInt32(dr["IsBlockGuest"].ToString()) : 0; objVisitorCheckInOut.BlockType = dr["BlockType"].ToString(); objVisitorCheckInOut.BlockDays = dr["BlockDays"] != null && dr["BlockDays"].ToString() != "" ? Convert.ToInt32(dr["BlockDays"].ToString()) : 0; ; objVisitorCheckInOut.BlockRemarks = dr["BlockRemarks"].ToString(); if (dr["BlockedDate"].ToString() != null && dr["BlockedDate"].ToString() != "") { objVisitorCheckInOut.BlockedDate = Convert.ToDateTime(dr["BlockedDate"]); } if (dr["UnblockedDate"].ToString() != null && dr["UnblockedDate"].ToString() != "") { objVisitorCheckInOut.UnblockedDate = Convert.ToDateTime(dr["UnblockedDate"]); } VisitorCheckInOutCol.Add(objVisitorCheckInOut); i = i + 1; } } } dt.Clear(); dt.Dispose(); return VisitorCheckInOutCol; } public VisitorCheckInOut SelectVisitorCheckInOutByID(String p_NRICID, int p_EventId) { MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("p_nricid", p_NRICID), new MySqlParameter("p_EventId", p_EventId)}; string sqlQuery = "SELECT `nricid`,`name`,`address`,`fromcompany`,`tocompany`,`telno`,`persontovisit`,`eventid`,`temp`,`visitortype`,`keyid`,`passid`,`gateid`,`vehicleplatenumber`,`guardname`,`remarks`,`checkintime`,`checkouttime`,`snapshotpath`,`deploymentid`,`Purpose`,`IsBlockGuest`,`BlockType`,`BlockRemarks`,`BlockDays`,`BlockedDate`,`UnblockedDate` FROM `visitorcheckinout` WHERE `nricid` = '" + p_NRICID + "' AND `eventid` = " + p_EventId + " ORDER BY `checkintime` DESC;"; DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand(sqlQuery, CommandType.Text); //DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetVisitorCheckInOutByID", CommandType.StoredProcedure, parameters); VisitorCheckInOut objVisitorCheckInOut = null; if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; objVisitorCheckInOut = new VisitorCheckInOut(); objVisitorCheckInOut.nricid = dr["nricid"].ToString(); objVisitorCheckInOut.passid = dr["passid"] != null && dr["passid"].ToString() != "" ? Convert.ToInt32(dr["passid"]) : 0; objVisitorCheckInOut.address = dr["address"].ToString(); //objVisitorCheckInOut.blockorphone = dr["blockorphone"].ToString(); objVisitorCheckInOut.checkintime = Convert.ToDateTime(dr["checkintime"].ToString()); if (dr["checkouttime"].ToString() == null && dr["checkouttime"].ToString() == "") { objVisitorCheckInOut.checkouttime = Convert.ToDateTime(dr["checkouttime"].ToString()); } //objVisitorCheckInOut.eventid = Convert.ToInt32(dr["eventid"].ToString()); objVisitorCheckInOut.fromcompany = dr["fromcompany"].ToString(); objVisitorCheckInOut.gateid = dr["gateid"] != null && dr["gateid"].ToString() != "" ? Convert.ToInt32(dr["gateid"]) : 0; objVisitorCheckInOut.guardname = dr["guardname"].ToString(); objVisitorCheckInOut.keyid = dr["keyid"] != null && dr["keyid"].ToString() != "" ? Convert.ToInt32(dr["keyid"]) : 0; objVisitorCheckInOut.name = dr["name"].ToString(); objVisitorCheckInOut.persontovisit = dr["persontovisit"].ToString(); objVisitorCheckInOut.remarks = dr["remarks"].ToString(); objVisitorCheckInOut.telno = dr["telno"].ToString(); objVisitorCheckInOut.temp = dr["temp"] != null && dr["temp"].ToString() != "" ? Convert.ToInt32(dr["temp"].ToString()) : 0; //objVisitorCheckInOut.tocompany = Convert.ToInt32(dr["tocompany"].ToString()); objVisitorCheckInOut.snapshotpath = dr["snapshotpath"].ToString(); objVisitorCheckInOut.deploymentid = dr["deploymentid"] != null && dr["deploymentid"].ToString() != "" ? Convert.ToInt32(dr["deploymentid"]) : 0; objVisitorCheckInOut.visitortypeID = dr["visitortype"] != null && dr["visitortype"].ToString() != "" ? Convert.ToInt32(dr["visitortype"]) : 0; //objVisitorCheckInOut.visitingcompany = dr["visitingcompany"].ToString(); objVisitorCheckInOut.purpose = dr["purpose"].ToString(); objVisitorCheckInOut.IsBlockGuest = dr["IsBlockGuest"] != null && dr["IsBlockGuest"].ToString() != "" ? Convert.ToInt32(dr["IsBlockGuest"]) : 0; objVisitorCheckInOut.BlockType = dr["BlockType"].ToString(); objVisitorCheckInOut.BlockDays = dr["BlockDays"] != null && dr["BlockDays"].ToString() != "" ? Convert.ToInt32(dr["BlockDays"].ToString()) : 0; objVisitorCheckInOut.BlockRemarks = dr["BlockRemarks"].ToString(); if (dr["BlockedDate"].ToString() == null && dr["BlockedDate"].ToString() == "") { objVisitorCheckInOut.BlockedDate = Convert.ToDateTime(dr["BlockedDate"]); } if (dr["UnblockedDate"].ToString() == null && dr["UnblockedDate"].ToString() == "") { objVisitorCheckInOut.UnblockedDate = Convert.ToDateTime(dr["UnblockedDate"]); } } dt.Clear(); dt.Dispose(); return objVisitorCheckInOut; } } }
using System; using System.Text; namespace RulesFakes { public class FakeAgentDisplayRule { public FakeRuleEngine<FakeAgentDisplayRule> RulesEngine; public FakeAgentDisplayRule(FakeMergeData mergeData) { this.mergeData = mergeData; RulesEngine = new FakeRuleEngine<FakeAgentDisplayRule>(); } private FakeMergeData mergeData { get; set; } #region Rule Defined Fields private string _cPLAgentDisplay; public string CPLAgentDisplay { get { if (string.IsNullOrEmpty(_cPLAgentDisplay)) { RulesEngine.ExecuteCPLSpecifications(this, "CPLAgentDisplay"); } return _cPLAgentDisplay; } set { _cPLAgentDisplay = value; } } private string _isOrtisParentOrNational; public string IsOrtisParentOrNational { get { if (string.IsNullOrEmpty(_isOrtisParentOrNational)) { RulesEngine.ExecuteCPLSpecifications(this, "IsOrtisParentOrNational"); } return _isOrtisParentOrNational; } set { _isOrtisParentOrNational = value; } } private string _hideAgentInfoForNJLetter; public string HideAgentInfoForNJLetter { get { if (string.IsNullOrEmpty(_hideAgentInfoForNJLetter)) { RulesEngine.ExecuteCPLSpecifications(this, "HideAgentInfoForNJLetter"); } return _hideAgentInfoForNJLetter; } set { _hideAgentInfoForNJLetter = value; } } #endregion Rule Defined Fields #region CPL Properties public string HideAgentInfoOnLetter { get { return mergeData.ValidatedLetterRequest.HideAgentInfoOnLetter.ToString().ToLower(); } } public string TransactionPropertyState { get { return mergeData.TransactionPropertyState; } } public string IsAgentSelected { get { if (!mergeData.IsForBlanketLetter && mergeData.ClosingAttorney != null && !string.IsNullOrWhiteSpace(mergeData.ClosingAttorney.NameLine1)) { return true.ToString(); } return false.ToString(); } } public string IsForBlanketLetter { get { return mergeData.IsForBlanketLetter.ToString().ToLower(); } } public string IsParent { get { return mergeData.Agent.IsParent.ToString().ToLower(); } } public string IsOrtris { get { return mergeData.Agent.IsORTRIS.ToString().ToLower(); } } public string IsNational { get { return mergeData.Agent.isNational.ToString().ToLower(); } } public string HasClosingAttorney { get { return (mergeData.ClosingAttorney != null && !string.IsNullOrEmpty(mergeData.ClosingAttorney.NameLine1)) .ToString().ToLower(); } } public string TransactionType { get; set; } public string Underwriter { get; } public string LetterType { get { return mergeData.LetterType.Code; } } #endregion CPL Properties public override bool Equals(object obj) { var cpl = obj as FakeAgentDisplayRule; if (cpl == null) { return false; } return LetterType.Equals(cpl.LetterType) && TransactionPropertyState.Equals(cpl.TransactionPropertyState) && TransactionType.Equals(cpl.TransactionType) && Underwriter.Equals(cpl.Underwriter); } public override int GetHashCode() { unchecked { // Choose large primes to avoid hashing collisions const int hashingBase = (int) 2166136261; const int hashingMultiplier = 16777619; int hash = hashingBase; hash = (hash * hashingMultiplier) ^ (!ReferenceEquals(null, LetterType) ? LetterType.GetHashCode() : 0); hash = (hash * hashingMultiplier) ^ (!ReferenceEquals(null, TransactionPropertyState) ? TransactionPropertyState.GetHashCode() : 0); hash = (hash * hashingMultiplier) ^ (!ReferenceEquals(null, TransactionType) ? TransactionType.GetHashCode() : 0); hash = (hash * hashingMultiplier) ^ (!ReferenceEquals(null, Underwriter) ? Underwriter.GetHashCode() : 0); return hash; } } } }
using RetailClientApp.Models.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace RetailClientApp.Provider { public class TransactionProvider : ITransactionProvider { /// <summary> /// Deposits money to someone's account /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<HttpResponseMessage> Deposit(CreateDepositWithdrawViewModel model) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://40.76.130.186"); var response = await client.PostAsJsonAsync("api/transaction/deposit", new { AccountId = model.AccountId, amount = model.Amount }); return response; } } /// <summary> /// Gets all the transactions done by customer /// </summary> /// <param name="CustomerId"></param> /// <returns></returns> public async Task<HttpResponseMessage> GetTransactions(int CustomerId) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://40.76.130.186"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/Json")); var response = await client.GetAsync("api/transaction/gettransactions/" + CustomerId); return response; } } /// <summary> /// Transfers money from one account to another /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<HttpResponseMessage> Transfer(GetTransferViewModel model) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://40.76.130.186"); var response = await client.PostAsJsonAsync("api/transaction/transfer", new { Source_AccountId = model.Source_AccountId, Target_AccountId = model.Target_AccountId, amount = model.amount }); return response; } } /// <summary> /// Withdraws money from an account /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<HttpResponseMessage> Withdraw(CreateDepositWithdrawViewModel model) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://40.76.130.186"); var response = await client.PostAsJsonAsync("api/transaction/withdraw", new { AccountId = model.AccountId, amount = model.Amount }); return response; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief 2D描画。レイヤーリスト。 */ /** NRender2D */ namespace NRender2D { /** LayerList */ public class LayerList { /** レイヤーリスト。 */ private LayerItem[] list; /** constructor */ public LayerList(Transform a_transform_root) { //プレハブ読み込み。 //GameObject t_prefab_camera = Resources.Load<GameObject>(Config.PREFAB_NAME_CAMERA); GameObject t_prefab_canvas = Resources.Load<GameObject>(Config.PREFAB_NAME_CANVAS); GameObject t_prefab_eventsystem = Resources.Load<GameObject>(Config.PREFAB_NAME_EVENTSYSTEM); //イベントシステム。インプットフィールド用。 { GameObject t_gameobject_eventsystem = GameObject.Instantiate(t_prefab_eventsystem,Vector3.zero,Quaternion.identity); t_gameobject_eventsystem.name = "EventSystem"; t_gameobject_eventsystem.transform.parent = a_transform_root; } //描画前処理。 { GameObject t_gameobject_main = new GameObject(); t_gameobject_main.name = "PreDraw"; t_gameobject_main.AddComponent<MonoBehaviour_PreDraw>(); t_gameobject_main.transform.SetParent(a_transform_root); } //レイヤーリスト。 this.list = new LayerItem[Config.MAX_LAYER]; for(int ii=0;ii<this.list.Length;ii++){ this.list[ii] = new LayerItem(); //描画順序。 float t_gl_depth = Config.CAMERADEPTH_START + ii * Config.CAMERADEPTH_STEP + Config.CAMERADEPTH_OFFSET_GL; float t_ui_depth = Config.CAMERADEPTH_START + ii * Config.CAMERADEPTH_STEP + Config.CAMERADEPTH_OFFSET_UI; //カメラ。GL描画。 GameObject t_gameobject_camera_gl = NInstantiate.Instantiate.CreateOrthographicCameraObject("Camera_" + ii.ToString() + "_GL",a_transform_root,t_gl_depth); Camera t_camera_gl = t_gameobject_camera_gl.GetComponent<Camera>(); //カメラ。UI描画。 GameObject t_gameobject_camera_ui = NInstantiate.Instantiate.CreateOrthographicCameraObject("Camera_" + ii.ToString() + "_UI",a_transform_root,t_ui_depth); Camera t_camera_ui = t_gameobject_camera_ui.GetComponent<Camera>(); t_camera_ui.cullingMask = (1 << LayerMask.NameToLayer("UI")); //キャンバス。 GameObject t_gameobject_canvas = GameObject.Instantiate(t_prefab_canvas,Vector3.zero,Quaternion.identity); t_gameobject_canvas.name = "Canvas_" + ii.ToString(); t_gameobject_canvas.transform.SetParent(a_transform_root); Canvas t_canvas = t_gameobject_canvas.GetComponent<Canvas>(); //キャンバス設定。 t_canvas.renderMode = RenderMode.ScreenSpaceCamera; t_canvas.worldCamera = t_camera_ui; //GL描画設定。 this.list[ii].camera_gl = t_gameobject_camera_gl.AddComponent<MonoBehaviour_Camera_GL>(); this.list[ii].camera_gl.index = ii; this.list[ii].camera_gl.mycamera = t_camera_gl; this.list[ii].camera_gl.cameradepth = t_gl_depth; //UIカメラ。 this.list[ii].camera_ui = t_gameobject_camera_ui.AddComponent<MonoBehaviour_Camera_UI>(); this.list[ii].camera_ui.index = ii; this.list[ii].camera_ui.mycamera = t_camera_ui; this.list[ii].camera_ui.cameradepth = t_ui_depth; //キャンバス設定。 this.list[ii].canvas_transform = t_gameobject_canvas.GetComponent<Transform>(); } } /** 描画プライオリティからレイヤーインデックス取得。 */ public int CalcLayerIndexFromDrawPriority(long a_drawpriority) { int t_layerindex = (int)(a_drawpriority / Config.DRAWPRIORITY_STEP); if((0<=t_layerindex)&&(t_layerindex<this.list.Length)){ return t_layerindex; } return -1; } /** 描画プライオリティからレイヤートランスフォーム取得。 */ public Transform GetLayerTransformFromDrawPriority(long a_drawpriority) { int t_layerindex = this.CalcLayerIndexFromDrawPriority(a_drawpriority); if(t_layerindex >= 0){ return this.list[t_layerindex].canvas_transform; } return null; } /** リストサイズ取得。 */ public int GetListMax() { return this.list.Length; } /** GetStartIndex_Sprite */ public int GetStartIndex_Sprite(int a_layerindex) { return this.list[a_layerindex].sprite_index_start; } /** GetLastIndex_Sprite */ public int GetLastIndex_Sprite(int a_layerindex) { return this.list[a_layerindex].sprite_index_last; } /** GetStartIndex_Text */ public int GetStartIndex_Text(int a_layerindex) { return this.list[a_layerindex].text_index_start; } /** GetLastIndex_Text */ public int GetLastIndex_Text(int a_layerindex) { return this.list[a_layerindex].text_index_last; } /** GetStartIndex_InputField */ public int GetStartIndex_InputField(int a_layerindex) { return this.list[a_layerindex].inputfield_index_start; } /** GetLastIndex_InputField */ public int GetLastIndex_InputField(int a_layerindex) { return this.list[a_layerindex].inputfield_index_last; } /** デプスクリアーの設定。 */ public void SetDepthClearGL(int a_layerindex,bool a_flag) { this.list[a_layerindex].camera_gl.SetDepthClear(a_flag); } /** デプスクリアーの設定。 */ public void SetDepthClearUI(int a_layerindex,bool a_flag) { this.list[a_layerindex].camera_ui.SetDepthClear(a_flag); } /** コールバック。設定。 */ public float GetGLCameraDepth(int a_layerindex) { return this.list[a_layerindex].camera_gl.cameradepth; } /** コールバック。設定。 */ public float GetUICameraDepth(int a_layerindex) { return this.list[a_layerindex].camera_ui.cameradepth; } /** インデックス計算。 */ public void CalcIndex(List<Sprite2D> a_sprite_list,List<Text2D> a_text_list,List<InputField2D> a_inputfield_list) { //リセット。 for(int ii=0;ii<this.list.Length;ii++){ this.list[ii].ResetIndex(); } //スプライト。 { int t_calc_mode = 0; int t_calc_layer = 0; int t_calc_index = 0; LayerItem t_calc_layeritem = this.list[t_calc_layer]; while(t_calc_index < a_sprite_list.Count){ int t_layerindex = this.CalcLayerIndexFromDrawPriority(a_sprite_list[t_calc_index].GetDrawPriority()); if(t_calc_layer < this.list.Length){ if(t_calc_mode == 0){ //開始インデックス。 if(t_layerindex < 0){ //除外。 t_calc_index++; }else{ if(t_calc_layer == t_layerindex){ //開始位置発見。 t_calc_layeritem.sprite_index_start = t_calc_index; t_calc_layeritem.sprite_index_last = t_calc_index; t_calc_index++; t_calc_mode = 1; }else{ //再チェック。 t_calc_layeritem.sprite_index_start = -1; t_calc_layeritem.sprite_index_last = -1; t_calc_layer++; t_calc_layeritem = this.list[t_calc_layer]; t_calc_mode = 0; } } }else{ //終了インデックス。 if(t_calc_layer == t_layerindex){ //終了インデックス候補。 t_calc_layeritem.sprite_index_last = t_calc_index; t_calc_index++; }else{ //再チェック。 t_calc_layer++; t_calc_layeritem = this.list[t_calc_layer]; t_calc_mode = 0; } } } } } //テキスト。 { int t_calc_mode = 0; int t_calc_layer = 0; int t_calc_index = 0; LayerItem t_calc_layeritem = this.list[t_calc_layer]; while(t_calc_index < a_text_list.Count){ int t_layerindex = this.CalcLayerIndexFromDrawPriority(a_text_list[t_calc_index].GetDrawPriority()); if(t_calc_layer < this.list.Length){ if(t_calc_mode == 0){ //開始インデックス。 if(t_layerindex < 0){ //除外。 t_calc_index++; }else{ if(t_calc_layer == t_layerindex){ //開始位置発見。 t_calc_layeritem.text_index_start = t_calc_index; t_calc_layeritem.text_index_last = t_calc_index; t_calc_index++; t_calc_mode = 1; }else{ //再チェック。 t_calc_layeritem.text_index_start = -1; t_calc_layeritem.text_index_last = -1; t_calc_layer++; t_calc_layeritem = this.list[t_calc_layer]; t_calc_mode = 0; } } }else{ //終了インデックス。 if(t_calc_layer == t_layerindex){ //終了インデックス候補。 t_calc_layeritem.text_index_last = t_calc_index; t_calc_index++; }else{ //再チェック。 t_calc_layer++; t_calc_layeritem = this.list[t_calc_layer]; t_calc_mode = 0; } } } } } //入力フィールド。 { int t_calc_mode = 0; int t_calc_layer = 0; int t_calc_index = 0; LayerItem t_calc_layeritem = this.list[t_calc_layer]; while(t_calc_index < a_inputfield_list.Count){ int t_layerindex = this.CalcLayerIndexFromDrawPriority(a_inputfield_list[t_calc_index].GetDrawPriority()); if(t_calc_layer < this.list.Length){ if(t_calc_mode == 0){ //開始インデックス。 if(t_layerindex < 0){ //除外。 t_calc_index++; }else{ if(t_calc_layer == t_layerindex){ //開始位置発見。 t_calc_layeritem.inputfield_index_start = t_calc_index; t_calc_layeritem.inputfield_index_last = t_calc_index; t_calc_index++; t_calc_mode = 1; }else{ //再チェック。 t_calc_layeritem.inputfield_index_start = -1; t_calc_layeritem.inputfield_index_last = -1; t_calc_layer++; t_calc_layeritem = this.list[t_calc_layer]; t_calc_mode = 0; } } }else{ //終了インデックス。 if(t_calc_layer == t_layerindex){ //終了インデックス候補。 t_calc_layeritem.inputfield_index_last = t_calc_index; t_calc_index++; }else{ //再チェック。 t_calc_layer++; t_calc_layeritem = this.list[t_calc_layer]; t_calc_mode = 0; } } } } } //ログ。 for(int ii=0;ii<this.list.Length;ii++){ this.list[ii].Log(); } } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace Apix.Sync.YaMarket.Models { public class SearchResult { [JsonProperty(PropertyName = "redirect")] public Redirects Redirects { get; set; } } public class Redirects { [JsonProperty(PropertyName = "content")] public Content Content { get; set; } } public class Content { [JsonProperty(PropertyName = "items")] public List<SearchItem> Items { get; set; } [JsonProperty(PropertyName = "model")] public SearchItem Model { get; set; } } public class SearchItem { [JsonProperty(PropertyName = "type")] public string Type { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "id")] public string Id { get; set; } } }
/** * Created DD/MM/2020 * By: Sharek Khan * Last Modified 26/10/2020 * By: Sharek Khan * * Contributors:Aswad Mirza, Sharek Khan */ using UnityEngine; using UnityEngine.AI; /* * ShootingEnemy handles all the logic, AI and behaviour patterns of the ShootingEnemy GameObject * Code based on Zenva Studios -COMPLETE COURSE Create a Unity FPS Game in 3 hours - https://www.youtube.com/watch?v=UtlAqRyZrUw */ public class ShootingEnemy : Enemy { public int InitialHealth = 10; public AudioSource deathSound; public float shootingInterval = 4f; public float shootingDistance = 3f; public float chasingInterval = 2f; public float chasingDistance = 12f; private Player player; private float shootingTimer; private float chasingTimer; private NavMeshAgent agent; private Vector3 m_lastPlayerLocation = Vector3.zero; // Variables for when the enemy is hit by the melee weapon public float grabDistance=3f; public float grabSpeed = 120f; // Start is called before the first frame update void Start() { this.Health = InitialHealth; player = GameObject.Find("Player").GetComponent<Player>(); agent = GetComponent<NavMeshAgent>(); shootingTimer = Random.Range(0, shootingInterval); agent.SetDestination(player.transform.position); } // Update is called once per frame void Update() { if(player.IsKilled == true) { agent.enabled = false; this.enabled = false; GetComponent<Rigidbody>().isKinematic = true; } /* * Removed since TakeDamage is now a base class function * if (health<=0) { Killed = true; OnKill(); } */ // Shooting Logic shootingTimer -= Time.deltaTime; if(shootingTimer <= 0 && Vector3.Distance(transform.position, player.transform.position) <= shootingDistance) { shootingTimer = shootingInterval; GameObject bullet = ObjectPoolingManager.Instance.GetBullet(false); bullet.transform.position = transform.position; //Problem, shooting the bullet is too slow bullet.transform.forward = (player.transform.position - transform.position).normalized; // Rigidbody rb = bullet.GetComponent<Rigidbody>(); // rb.AddRelativeForce(new Vector3(0,0,2000)); } // Chasing Logic chasingTimer -= Time.deltaTime; if (chasingTimer <= 0 && Vector3.Distance(transform.position, player.transform.position) <= chasingDistance) { chasingTimer = chasingInterval; agent.SetDestination(player.transform.position); } // Grabbed logic Grabbed(); } /* // OnCollisionEnter detects all collisions on entry private void OnCollisionEnter(Collision collision) { if (collision.gameObject.GetComponent<MeleeWeapon>() != null) { isGrabbed = true; } } */ // OnKill handles the logic for when the ShootingEnemy dies, in this case it calls the base class function and falls over protected override void OnKill() { base.OnKill(); deathSound.Play(); // agent.enabled = false; this.enabled = false; transform.localEulerAngles = new Vector3(10, transform.localEulerAngles.y, transform.localEulerAngles.z); } // Grabbed handles the behaviour of the ShootingEnemy reacts when grabbed by the Player through MeleeWeapon [Added By: Aswad Mirza] protected override void Grabbed() { if (IsGrabbed) { Debug.Log("Grabbed"); if (m_lastPlayerLocation.Equals(Vector3.zero)) { Debug.Log("Going to the last Player location"); m_lastPlayerLocation = player.transform.position; } if (Vector3.Distance(transform.position, m_lastPlayerLocation) > grabDistance) { transform.position = CalculateDirection(transform.position, m_lastPlayerLocation, grabSpeed); } else { IsGrabbed = false; m_lastPlayerLocation = Vector3.zero; Debug.Log("not grabbed anymore"); } } } }
using System.Threading.Tasks; namespace Executor.Console.Job { public interface Job<TResult> { Task<TResult> Execute(); } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Atari { public class BasePage { public WebDriverWait Wait { get; set; } public IWebDriver Driver { get; set; } public BasePage(IWebDriver webDriver) { Wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(60)); Driver =webDriver; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NBTM.Common { public class EnumUtils { public class EnumNameValuePair { public string Text { get; set; } public int Value { get; set; } } public static IEnumerable<T> GetValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } public static IEnumerable<EnumNameValuePair> GetNameValuePairForEnums_Short<T>() { var values = GetValues<T>(); return values.Select(e => new EnumNameValuePair { Text = TextRepresentation.GetDescriptionOf(e), Value = (short) Enum.Parse(typeof (T), e.ToString()) }).ToList(); //return Enum.GetValues(typeof(T)).Select(name => new EnumNameValuePair //{ // Text = TextRepresentation.GetDescriptionOf(name), // Value = (short)Enum.Parse(typeof(T), name) //}).ToList(); } public static IEnumerable<EnumNameValuePair> GetNameValuePairForEnums_Int<T>() { return Enum.GetNames(typeof(T)).Select(name => new EnumNameValuePair { Text = name, Value = (int)Enum.Parse(typeof(T), name) }).ToList(); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> public class Enum<T> where T : struct { /// <summary> /// /// </summary> /// <param name="array"></param> /// <returns></returns> public static int[] Convert(T[] array) { var newArray = new int[array.Length]; for (int i = 0; i < array.Length; i++) { newArray[i] = (int)System.Convert.ChangeType(array[i], typeof(int)); } return newArray; } /// <summary> /// /// </summary> private static void EnsureTypeIsEnum() { if (typeof(T).BaseType != typeof(Enum)) { throw new ArgumentException("T must be of type System.Enum."); } } /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static T Parse(string value) { // Ensure that T is of type Enum. EnsureTypeIsEnum(); // Determine whether the given value in an integer. In the case of parsing a string value, // depending on the source, it may be either an int or a string. Handle both situations. int enumInt; bool isInteger = int.TryParse(value, out enumInt); // Extract the appropriate enum value. T enumValue; if (isInteger) { enumValue = (T)Enum.ToObject(typeof(T), enumInt); } else { enumValue = (T)Enum.Parse(typeof(T), value); } // Ensure that the value we are parsing exists within the enumeration. if (!Enum.IsDefined(typeof(T), enumValue)) { throw new ApplicationException("Value " + value + " does not exist in the " + typeof(T).FullName + " enumeration."); } // Return the parsed Enum value. return (T)Enum.Parse(typeof(T), value); } /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static T Parse(int value) { // Ensure that T is of type Enum. EnsureTypeIsEnum(); // Extract enum value from int value. var enumValue = (T)Enum.ToObject(typeof(T), value); // Ensure that the value we are parsing exists within the enumeration. if (!Enum.IsDefined(typeof(T), enumValue)) { throw new ApplicationException("Value " + value + " does not exist in the " + typeof(T).FullName + " enumeration."); } // Return parsed enum value. return enumValue; } ///// <summary> ///// Get an array of list items containing the text represenation and values for an enumeration. Used to populate drop-down lists. ///// </summary> ///// <typeparam name="T">The type of enumeration to convert</typeparam> ///// <returns><see cref="System.Web.UI.WebControls.ListItem"/> array</returns> //public static ListItem[] ToListItems() //{ // EnsureTypeIsEnum(); // return (from n in Enum.GetNames(typeof(T)).Where(n => n != "Null" && n != "Default") // let v = (T)Enum.Parse(typeof(T), n) // select new ListItem(TextRepresentation.GetDescriptionOf(v), v.ToString())).ToArray(); //} } /// <summary> /// /// </summary> public class TextRepresentationAttribute : Attribute { public readonly string Text; public TextRepresentationAttribute(string text) { Text = text; } } /// <summary> /// /// </summary> public class TextRepresentation { public static string GetDescriptionOf<T>(T enumType) { string enumDescription = ""; MemberInfo[] memberInfo = enumType.GetType().GetMember(enumType.ToString()); if (memberInfo != null && memberInfo.Length == 1) { object[] customAttributes = memberInfo[0].GetCustomAttributes(typeof(TextRepresentationAttribute), false); if (customAttributes.Length == 1) { enumDescription = ((TextRepresentationAttribute)customAttributes[0]).Text; } } if (enumDescription.Length == 0) return enumType.ToString(); return enumDescription; } } } }
using System; using System.Collections.Generic; #nullable disable namespace API.Models { public partial class Monhoc { public Monhoc() { Ctdtmonhocs = new HashSet<Ctdtmonhoc>(); } public string MaMonHoc { get; set; } public string TenMonHoc { get; set; } public int? SoTinChi { get; set; } public int? SoTinChiLiThuyet { get; set; } public int? SoTinChiThucHanh { get; set; } public string KhaiQuatChung { get; set; } public string NhomTuChon { get; set; } public string Link { get; set; } public DateTime? CreatedDate { get; set; } public string CreatedBy { get; set; } public DateTime? ModifiedDate { get; set; } public string ModifiedBy { get; set; } public virtual ICollection<Ctdtmonhoc> Ctdtmonhocs { get; set; } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_JointLimits : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { JointLimits jointLimits = default(JointLimits); LuaObject.pushValue(l, true); LuaObject.pushValue(l, jointLimits); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_min(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); LuaObject.pushValue(l, true); LuaObject.pushValue(l, jointLimits.get_min()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_min(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); float min; LuaObject.checkType(l, 2, out min); jointLimits.set_min(min); LuaObject.setBack(l, jointLimits); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_max(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); LuaObject.pushValue(l, true); LuaObject.pushValue(l, jointLimits.get_max()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_max(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); float max; LuaObject.checkType(l, 2, out max); jointLimits.set_max(max); LuaObject.setBack(l, jointLimits); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_bounciness(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); LuaObject.pushValue(l, true); LuaObject.pushValue(l, jointLimits.get_bounciness()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_bounciness(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); float bounciness; LuaObject.checkType(l, 2, out bounciness); jointLimits.set_bounciness(bounciness); LuaObject.setBack(l, jointLimits); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_bounceMinVelocity(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); LuaObject.pushValue(l, true); LuaObject.pushValue(l, jointLimits.get_bounceMinVelocity()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_bounceMinVelocity(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); float bounceMinVelocity; LuaObject.checkType(l, 2, out bounceMinVelocity); jointLimits.set_bounceMinVelocity(bounceMinVelocity); LuaObject.setBack(l, jointLimits); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_contactDistance(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); LuaObject.pushValue(l, true); LuaObject.pushValue(l, jointLimits.get_contactDistance()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_contactDistance(IntPtr l) { int result; try { JointLimits jointLimits; LuaObject.checkValueType<JointLimits>(l, 1, out jointLimits); float contactDistance; LuaObject.checkType(l, 2, out contactDistance); jointLimits.set_contactDistance(contactDistance); LuaObject.setBack(l, jointLimits); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.JointLimits"); LuaObject.addMember(l, "min", new LuaCSFunction(Lua_UnityEngine_JointLimits.get_min), new LuaCSFunction(Lua_UnityEngine_JointLimits.set_min), true); LuaObject.addMember(l, "max", new LuaCSFunction(Lua_UnityEngine_JointLimits.get_max), new LuaCSFunction(Lua_UnityEngine_JointLimits.set_max), true); LuaObject.addMember(l, "bounciness", new LuaCSFunction(Lua_UnityEngine_JointLimits.get_bounciness), new LuaCSFunction(Lua_UnityEngine_JointLimits.set_bounciness), true); LuaObject.addMember(l, "bounceMinVelocity", new LuaCSFunction(Lua_UnityEngine_JointLimits.get_bounceMinVelocity), new LuaCSFunction(Lua_UnityEngine_JointLimits.set_bounceMinVelocity), true); LuaObject.addMember(l, "contactDistance", new LuaCSFunction(Lua_UnityEngine_JointLimits.get_contactDistance), new LuaCSFunction(Lua_UnityEngine_JointLimits.set_contactDistance), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_JointLimits.constructor), typeof(JointLimits), typeof(ValueType)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Aspit.StudentReg.Entities; using Aspit.StudentReg.DataAccess; namespace Aspit.StudentReg.GUI.Terminal { /// <summary> /// Interaction logic for StartScreenUserControl.xaml /// </summary> /// public partial class StartScreenUserControl : UserControl { private MainWindow parent; public StartScreenUserControl(MainWindow parentArg) { parent = parentArg; InitializeComponent(); StudentsRepository studentsRepository = new StudentsRepository(RepositoryBase.RetrieveConnectionString()); //Populate StudentListbox with all students StudentListbox.DisplayMemberPath = Name; StudentListbox.ItemsSource = studentsRepository.GetAll(); } private void StudentListbox_SelectionChanged(object sender, SelectionChangedEventArgs e) { //Set usercontrol to CheckInOrOutPromt with the selcted student Student student = StudentListbox.SelectedItem as Student; parent.Content = new CheckInOrOutPromt(student, parent); } } }