text
stringlengths
13
6.01M
using processKR; using PRM.UC; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PRM { #region delegate 선언 public delegate void AddKillProcessOkEvent(string data); #endregion public partial class fmList : Form { #region 선언부 public AddKillProcessOkEvent DataSendE; ucCon ucList; FrMain frmMainInList; string slogPro = ""; string sProcessName = ""; string sListPath = Environment.CurrentDirectory + @"\KList.ini"; #endregion public fmList() { InitializeComponent(); } #region 폼로딩 private void FrmList_Load(object sender, EventArgs e) { ucList = new ucCon(); frmMainInList = new FrMain(); frmMainInList.PrmIcon.Visible = false; //아이콘 중복 비활성 frmMainInList.Close(); //중복 실행 방지 FrmList_Load_Process(); } public void FrmList_Load_Process() { AddKListChBox.Items.Clear(); Process[] processes = Process.GetProcesses(); // 모든 프로세스 추출 foreach (Process process in processes) { // foreach 루프 수행 AddKListChBox.Items.Add(process.ProcessName + "\n"); } } #endregion #region 버튼 클릭 private void AddKBtn_Click(object sender, EventArgs e) // 추가버튼 클릭 { int nCnt = CIni.Load("PROCESS", "CNT", 0, sListPath); //카운트 if (nCnt > 0) { int nColnum = nCnt; foreach (string obj in AddKListChBox.CheckedItems) { int nCount = 1; for (int i = 1; i <= nCnt; i++) { sProcessName = CIni.Load("PROCESS", (i).ToString(), "", sListPath); try { if (sProcessName == obj.Substring(0, obj.LastIndexOf(""))) { nCount = 2; } } catch (Exception ex) { Debug.WriteLine(ex); } } if (nCount == 1) { CIni.Save("PROCESS", "CNT", (nColnum + 1).ToString(), sListPath); CIni.Save("PROCESS", (nColnum + 1).ToString(), obj.ToString(), sListPath); slogPro = CIni.Load("PROCESS", (nColnum + 1).ToString(), "", sListPath); try { if (slogPro != "") { DataSendE(slogPro + " 추가"); } else DataSendE(""); } catch (Exception ex) { Debug.WriteLine(ex); } nColnum++; } } } else { int nCount = 1; foreach (string obj in AddKListChBox.CheckedItems) { CIni.Save("PROCESS", "CNT", (nCount).ToString(), sListPath); sProcessName = CIni.Load("PROCESS", (nCount).ToString(), "", sListPath); CIni.Save("PROCESS", (nCount).ToString(), obj.ToString(), sListPath); slogPro = CIni.Load("PROCESS", (nCount).ToString(), "", sListPath); try { if (slogPro != "") { DataSendE(slogPro + " 추가"); } else DataSendE(""); } catch (Exception ex) { Debug.WriteLine(ex); } nCount++; } } for(int i = 1; i < AddKListChBox.Items.Count; i++) { AddKListChBox.SetItemChecked(i, false); } Hide(); } private void CancelKBtn_Click(object sender, EventArgs e) //취소 버튼 클릭 { Hide(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Contoso.Spa.Flow.Cache { public class RequestedFlowStage { public string InitialModule { get; set; } public int TargetModule { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class SkyTimeManager : MonoBehaviour { TextMeshPro uiText; // UIText コンポーネント float totalTime; // Start is called before the first frame update void Start() { totalTime = TimeManagerUnder.get_nextime(); // Textコンポーネント取得 uiText = GetComponent<TextMeshPro>(); } // Update is called once per frame void Update() { //とりあえず-20より時間は下がらない if (totalTime <= -20.0f) { return; } totalTime -= Time.deltaTime; uiText.text = totalTime.ToString("F2"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShootOnTouch : MonoBehaviour { public GameObject projectile; public Vector3[] spawnOffsets; public Vector3[] extraSpawnOffstes; private int touchCount; // Use this for initialization void Start () { touchCount = Input.touchCount; } // Update is called once per frame void Update () { if (Input.touchCount > touchCount || Input.GetKey("space")){ foreach (Vector3 offset in spawnOffsets){ Instantiate(projectile, transform.position + transform.rotation * offset, transform.rotation); } } if (ScoreKeeping.score > 200) { if (Input.touchCount > touchCount || Input.GetKey("space")) { foreach (Vector3 offset in extraSpawnOffstes) { Instantiate(projectile, transform.position + transform.rotation * offset, transform.rotation); } } } touchCount = Input.touchCount; } }
using System.Collections.Generic; using System.Security.Permissions; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Drawing; using System; namespace Pryda.Common { public delegate void ProjectChanged(string projectName); public delegate void RunTests(string filter, bool debug); public delegate void StopTests(); public delegate void GoToTestCode(string testcase, string testname); public delegate void ViewTestResults(List<string> tests); /// <summary> /// Summary description for MyControl. /// </summary> public partial class ctlTestList : UserControl { public ProjectChanged notifyProjectChanged; public RunTests notifyRunTests; public StopTests notifyStopTests; public GoToTestCode notifyGoToTestCode; public ViewTestResults notifyViewResults; public const string RESULT_IN_PROGRESS = "In Progress"; public const string RESULT_PENDING = "Pending"; public const string RESULT_ABORTED = "Aborted"; public const string RESULT_FAILED = "Failed"; public const string RESULT_PARTIAL_FAILED = "Partial Failed"; public const string RESULT_PASSED = "Passed"; public bool shuffleTests = false; public bool disabledTests = false; public bool breakOnFailure = false; public bool throwOnFailure = false; public bool catchExceptions = true; private bool _DebuggingToolsEnabled = true; public bool DebuggingToolsEnabled { get { return _DebuggingToolsEnabled; } set { _DebuggingToolsEnabled = value; if (!_DebuggingToolsEnabled) { // remove debugging menu/toolbar items. debugSelectionToolStripMenuItem.Visible = false; debugSelectionToolStripMenuItem.Enabled = false; } } } private ListViewColumnSorter lvwColumnSorter; public ctlTestList() { InitializeComponent(); lvwColumnSorter = new ListViewColumnSorter(); listTests.ListViewItemSorter = lvwColumnSorter; } public string CurrentProjectName { get { return toolStripProjects.Text; } set { if (value == null || value == "") { //toolStripProjects.SelectedIndex toolStripProjects.SelectedItem = null; } else { int index = toolStripProjects.FindString(value); if (index != -1) { toolStripProjects.SelectedIndex = index; } } if (notifyProjectChanged != null) notifyProjectChanged(this.CurrentProjectName); } } public int RandomSeed { get { int Value = 0; try { Value = Int32.Parse(toolStripRandomSeed.Text); } catch (System.FormatException ex) { } catch (System.ArgumentNullException ex) { } catch (System.OverflowException ex) { } return Value; } set { toolStripRandomSeed.Text = value.ToString(); } } public int RepeatCount { get { int repeatCount = 0; try { repeatCount = System.Int32.Parse(toolStripTextRepeat.Text); } catch (System.FormatException ex) { } catch (System.ArgumentNullException ex) { } catch (System.OverflowException ex) { } return repeatCount; } set { toolStripTextRepeat.Text = value.ToString(); } } public int AddProject(string projectName) { if (projectName.Equals("Solution Items") || projectName.Equals("Miscellaneous Files")) return -1; int index = toolStripProjects.FindString(projectName); if (index == -1) index = toolStripProjects.Items.Add(projectName); return index; } public void RemoveProject(string projectName) { int index = toolStripProjects.FindString(projectName); if (index == -1) return; if (toolStripProjects.SelectedIndex == index) CurrentProjectName = null; object item = toolStripProjects.Items[index]; toolStripProjects.Items.Remove(item); } public void ClearProjects() { toolStripProjects.Items.Clear(); if (notifyProjectChanged != null) notifyProjectChanged(this.CurrentProjectName); } /// <summary> /// Let this control process the mnemonics. /// </summary> [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)] protected override bool ProcessDialogChar(char charCode) { // If we're the top-level form or control, we need to do the mnemonic handling if (charCode != ' ' && ProcessMnemonic(charCode)) { return true; } return base.ProcessDialogChar(charCode); } /// <summary> /// Enable the IME status handling for this control. /// </summary> protected override bool CanEnableIme { get { return true; } } public int findListViewItem(string testcase, string unittest) { foreach (ListViewItem lvi in listTests.Items) { if (lvi.SubItems[1].Text == testcase) { if (lvi.SubItems[2].Text == unittest) return lvi.Index; } } return -1; } public void cls() { foreach (ListViewItem lvi in listTests.Items) { lvi.SubItems[3].Text = ""; lvi.SubItems[4].Text = ""; } listTests.Refresh(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] private void toolStripProjects_Click(object sender, System.EventArgs e) { // combo changed.. if (notifyProjectChanged != null) notifyProjectChanged(toolStripProjects.Text); } public bool isTestEnabled(ListViewItem lvi) { return (!lvi.SubItems[0].Text.Equals("true")) ? false : true; } public void setTestEnabled(ListViewItem lvi, bool Enabled) { if (Enabled) lvi.SubItems[0].Text = "true"; else lvi.SubItems[0].Text = "false"; } public string getEnabledTestsFilter() { string filter = ""; bool allEnabled = true; string filterEnabled = ""; string filterDisabled = ""; foreach (ListViewItem lvi in listTests.Items) { if (!isTestEnabled(lvi)) { allEnabled = false; //if (filterDisabled.Length > 0) filterDisabled += ":"; //filterDisabled += "-" + getItemTestCaseName(lvi.Index); } else { if (filterEnabled.Length > 0) filterEnabled += ":"; filterEnabled += getItemTestCaseName(lvi.Index); } } if (!allEnabled) { if (filterEnabled.Length == 0) return filter; // use the shortest lengthed string.. //filter = (filterEnabled.Length < filterDisabled.Length) ? filterEnabled : filterDisabled; filter = filterEnabled; } return filter; } public string getItemTestCaseName(int index) { ListViewItem lvi = listTests.Items[index]; string testCaseName = lvi.SubItems[1].Text + "." + lvi.SubItems[2].Text; return testCaseName; } public string getSelectedTestsFilter() { string filter = ""; foreach (ListViewItem lvi in listTests.SelectedItems) { filter += getItemTestCaseName(lvi.Index); if (lvi != listTests.SelectedItems[listTests.SelectedItems.Count - 1]) filter += ":"; } return filter; } private void listTests_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (sender == listTests) { } } //private void toolStipBrowse_Click(object sender, System.EventArgs e) //{ // DialogResult r = openFileDialog1.ShowDialog(); // if (DialogResult.OK == r) // { // toolStripProjects.Text = openFileDialog1.FileName; // toolStripProjects.Items.Add(openFileDialog1.FileName); // notifyProjectChanged(toolStripProjects.Text); // } //} private void toolStripRefresh_Click(object sender, System.EventArgs e) { if (notifyProjectChanged != null) notifyProjectChanged(toolStripProjects.Text); } private void runSelected(string filter) { if (notifyRunTests != null) notifyRunTests(filter, false); } private void debugSelected(string filter) { if (notifyRunTests != null) notifyRunTests(filter, true); } private void listTests_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) { Graphics g = e.Graphics; Rectangle rect = e.Bounds; if (e.ColumnIndex == 0) { bool isChecked = e.Item.SubItems[0].Text.Equals("true"); CheckBoxRenderer.DrawCheckBox(g, new Point( rect.Left + 3, rect.Top + 3), isChecked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal); } else //if (e.ColumnIndex == 1 || e.ColumnIndex == 3) { e.DrawBackground(); Color fore = e.SubItem.ForeColor; // Unless the item is selected, draw the standard // background to make it stand out from the gradient. if (e.Item.Selected) { if (listTests.Focused) { g.FillRectangle(SystemBrushes.Highlight, rect); fore = SystemColors.HighlightText; } else g.FillRectangle(SystemBrushes.ButtonFace, rect); } int iconIndex = -1; if (e.ColumnIndex == 3) { switch (e.Item.SubItems[3].Text) { case RESULT_PASSED: iconIndex = imageList1.Images.IndexOfKey("passed"); break; case RESULT_IN_PROGRESS: iconIndex = imageList1.Images.IndexOfKey("inprogress"); break; case RESULT_PENDING: iconIndex = imageList1.Images.IndexOfKey("pending"); break; case RESULT_PARTIAL_FAILED: case RESULT_ABORTED: case RESULT_FAILED: iconIndex = imageList1.Images.IndexOfKey("failed"); break; } } else if (e.ColumnIndex == 1) { iconIndex = imageList1.Images.IndexOfKey("test"); } if (iconIndex != -1) { imageList1.Draw(g, new Point(rect.Left + 2, rect.Top), iconIndex); rect.X += imageList1.ImageSize.Width + 4; } if (e.ColumnIndex != 0) { TextRenderer.DrawText(e.Graphics, e.SubItem.Text, listTests.Font, rect, fore, TextFormatFlags.GlyphOverhangPadding | TextFormatFlags.VerticalCenter); } if (e.Item.Focused) e.DrawFocusRectangle(rect); } } private void listTests_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) { e.DrawDefault = true; } private void listTests_MouseClick(object sender, MouseEventArgs e) { ListViewHitTestInfo hitinfo = listTests.HitTest(e.X, e.Y); ListViewItem.ListViewSubItem subItem = hitinfo.SubItem; int colindex = hitinfo.Item.SubItems.IndexOf(subItem); if (colindex == 0) { foreach (ListViewItem item in listTests.SelectedItems) { item.SubItems[0].Text = (item.SubItems[0].Text.Equals("true")) ? "false" : "true"; } listTests.Invalidate(); } } private void listTests_MouseDoubleClick(object sender, MouseEventArgs e) { ListViewItem listItem = listTests.HitTest(e.X, e.Y).Item; if (notifyGoToTestCode != null) notifyGoToTestCode(listItem.SubItems[1].Text, listItem.SubItems[2].Text); } private void listTests_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A && e.Control) { listTests.MultiSelect = true; foreach (ListViewItem item in listTests.Items) { item.Selected = true; } } } private void clearResultsToolStripMenuItem_Click(object sender, System.EventArgs e) { cls(); } private void shuffleTestsToolStripMenuItem_Click(object sender, System.EventArgs e) { shuffleTests = !shuffleTests;} private void runDisabledTestsToolStripMenuItem_Click(object sender, System.EventArgs e) { disabledTests = !disabledTests; } private void contextMenuRunSelected_Click(object sender, System.EventArgs e) { runSelected(getSelectedTestsFilter()); } private void debugSelectedTestsToolStripMenuItem_Click(object sender, System.EventArgs e) { debugSelected(getSelectedTestsFilter()); } private void runSelectionToolStripMenuItem_Click(object sender, System.EventArgs e) { runSelected(getEnabledTestsFilter()); } private void debugSelectionToolStripMenuItem_Click(object sender, System.EventArgs e) { debugSelected(getEnabledTestsFilter()); } private void toolStripButtonStop_Click(object sender, System.EventArgs e) { if (notifyStopTests != null) notifyStopTests(); } private void listTests_ColumnClick(object sender, ColumnClickEventArgs e) { // Determine if clicked column is already the column that is being sorted. if (e.Column == lvwColumnSorter.SortColumn) { // Reverse the current sort direction for this column. if (lvwColumnSorter.Order == SortOrder.Ascending) { lvwColumnSorter.Order = SortOrder.Descending; } else { lvwColumnSorter.Order = SortOrder.Ascending; } } else { // Set the column number that is to be sorted; default to ascending. lvwColumnSorter.SortColumn = e.Column; lvwColumnSorter.Order = SortOrder.Ascending; } // Perform the sort with these new sort options. listTests.Sort(); } private void ctlTestList_Load(object sender, System.EventArgs e) { } private void toolStripResultsReport_Click_1(object sender, System.EventArgs e) { if (notifyViewResults != null) notifyViewResults(null); } private void showSelectionResultsToolStripMenuItem_Click(object sender, System.EventArgs e) { List<string> tests = null; if (listTests.SelectedItems.Count > 0) { tests = new List<string>(); foreach (ListViewItem lvi in listTests.SelectedItems) { string testname = lvi.SubItems[1].Text + "." + lvi.SubItems[2].Text; tests.Add(testname); } } if (notifyViewResults != null) notifyViewResults(tests); } private void openTestToolStripMenuItem_Click(object sender, System.EventArgs e) { if (listTests.SelectedItems.Count == 1) { ListViewItem listItem = listTests.SelectedItems[0]; if (listItem == null) return; if (notifyGoToTestCode != null) notifyGoToTestCode(listItem.SubItems[1].Text, listItem.SubItems[2].Text); } } private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e) { if (listTests.SelectedItems.Count > 0) { runSelectedTestsToolStripMenuItem.Enabled = true; debugSelectedTestsToolStripMenuItem.Enabled = true; showSelectionResultsToolStripMenuItem.Enabled = true; } else { runSelectedTestsToolStripMenuItem.Enabled = false; debugSelectedTestsToolStripMenuItem.Enabled = false; showSelectionResultsToolStripMenuItem.Enabled = false; } openTestToolStripMenuItem.Enabled = (listTests.SelectedItems.Count == 1) ? true : false; clearResultsToolStripMenuItem.Enabled = (listTests.Items.Count > 0) ? true : false; if (!_DebuggingToolsEnabled) { openTestToolStripMenuItem.Visible = false; openTestToolStripMenuItem.Enabled = false; debugSelectedTestsToolStripMenuItem.Visible = false; debugSelectedTestsToolStripMenuItem.Enabled = false; toolStripMenuItem1.Visible = false; } } private void randomSeedToolStripMenuItem_Click(object sender, System.EventArgs e) { } private void toolStripDropDownButton1_DropDownOpening(object sender, EventArgs e) { randomSeedToolStripMenuItem.Enabled = shuffleTests; runDisabledTestsToolStripMenuItem.Checked = disabledTests; breakOnFailureToolStripMenuItem.Checked = breakOnFailure; catchExceptionsToolStripMenuItem.Checked = catchExceptions; throwOnFailureToolStripMenuItem.Checked = throwOnFailure; shuffleTestsToolStripMenuItem.Checked = shuffleTests; } private void breakOnFailureToolStripMenuItem_Click(object sender, EventArgs e) { breakOnFailure = !breakOnFailure; } private void catchExceptionsToolStripMenuItem_Click(object sender, EventArgs e) { catchExceptions = !catchExceptions; } private void throwOnFailureToolStripMenuItem_Click(object sender, EventArgs e) { throwOnFailure = !throwOnFailure; } } }
using System; using UnityEngine; namespace Script { public class TetrisBlockSimulationModel : MonoBehaviour { public TetrisBoardViewModel boardViewModel; public TetrisNextPieceViewModel nextPieceViewModel; private TetrisFieldState _fieldState; private TetrisPiece _nextPiece; private int _autoMoveDownFrameCount; private int _deleteDelayFrameCount; private int _gameOverDelayFrameCount; private bool _isNeedPacking; private bool _isGameOver; private void Start() { _nextPiece = TetrisPiece.Factory.CreateRandomPiece(); _fieldState = new TetrisFieldState { CurrentPiece = TetrisPiece.Factory.CreateRandomPiece() }; _autoMoveDownFrameCount = 0; _deleteDelayFrameCount = 0; _gameOverDelayFrameCount = 0; // ViewModel Bindings boardViewModel.FieldState = _fieldState; //FIXME nextPieceViewModel.PieceData = _nextPiece; } private void GameOver(int count) { var field = _fieldState.CurrentField; var y = field.GetLength(0) - count - 1; if (y < 0) return; for (var j = 0; j < field.GetLength(1); j++) { if (field[y, j] != 0) { field[y, j] = 8; } } } private void Update() { if (_isGameOver) { if (_gameOverDelayFrameCount > 60) { // 新規ゲーム設定 UpdatePiece(); _fieldState.Clear(); _isGameOver = false; _gameOverDelayFrameCount = 0; return; } // 下からグレーアウト GameOver(_gameOverDelayFrameCount / 2); _gameOverDelayFrameCount++; return; } if (_isNeedPacking) { if (++_deleteDelayFrameCount > 10) { //削除した行を詰める PackLine(); _isNeedPacking = false; } } // 一定フレームごとに下に移動 if (++_autoMoveDownFrameCount > 24) { _autoMoveDownFrameCount = 0; if (!MoveDown()) { //次のピースに入れ替え UpdatePiece(); //ゲームオーバーチェック if (_fieldState.CurrentField[0, TetrisConstants.PositionSpawnX] != 0 || _fieldState.CurrentField[0, TetrisConstants.PositionSpawnX + 1] != 0 || _fieldState.CurrentField[0, TetrisConstants.PositionSpawnX + 2] != 0) { _isGameOver = true; } } } } public void UpdatePiece() { //ピースの位置を確定し、現在の状態を固定 _fieldState.UpdateAndFixCurrentField(); //削除処理 if (DeleteFilledLine()) { _isNeedPacking = true; _autoMoveDownFrameCount = 0; } _fieldState.CurrentPiece = _nextPiece; _nextPiece = TetrisPiece.Factory.CreateRandomPiece(); nextPieceViewModel.PieceData = _nextPiece; } private bool DeleteFilledLine() { var field = _fieldState.CurrentField; var isNeedPacking = false; for (var i = 0; i < field.GetLength(0); i++) { //ラインが埋まっているかチェック var isFilled = true; for (var j = 0; j < field.GetLength(1); j++) { if (field[i, j] != 0) { continue; } isFilled = false; break; } //ラインが埋まっている場合ラインをクリア if (isFilled) { for (var j = 0; j < field.GetLength(1); j++) { field[i, j] = 0; } isNeedPacking = true; } } return isNeedPacking; } private void PackLine() { var field = _fieldState.CurrentField; var packedField = new int[TetrisConstants.PositionMaxY, TetrisConstants.PositionMaxX]; var y = field.GetLength(0) - 1; for (var i = field.GetLength(0) - 1; i >= 0; i--) { //ラインにブロックが存在するかチェック var isExistBlock = false; for (var j = 0; j < field.GetLength(1); j++) { if (field[i, j] != 0) { isExistBlock = true; break; } } //ブロックが存在する場合ラインを詰めてコピー if (isExistBlock) { for (var j = 0; j < field.GetLength(1); j++) { packedField[y, j] = field[i, j]; } y--; } } // パッキングを適用 Array.Copy(packedField, _fieldState.CurrentField, _fieldState.CurrentField.Length); } public void FrameCountGrace(int count) { _autoMoveDownFrameCount -= count; } public bool RotateLeft() { var currentPiece = _fieldState.CurrentPiece; //タイプOは無条件でtrue if (currentPiece.Type == TetrisConstants.PieceTypeO) { return true; } var rotatedData = currentPiece.GetRotateLeftData(); var currentAngle = currentPiece.Angle; //https://tetris.wiki/Super_Rotation_System int[,] wallKickData; int nextAngle; if (currentPiece.Type == TetrisConstants.PieceTypeI) { switch (currentAngle) { case TetrisConstants.Angle0: //0->L wallKickData = new[,] {{0, 0}, {-1, 0}, {+2, 0}, {-1, +2}, {+2, -1}}; nextAngle = TetrisConstants.Angle270; break; case TetrisConstants.Angle90: //R->0 wallKickData = new[,] {{0, 0}, {+2, 0}, {-1, 0}, {+2, +1}, {-1, -2}}; nextAngle = TetrisConstants.Angle0; break; case TetrisConstants.Angle180: //2->R wallKickData = new[,] {{0, 0}, {+1, 0}, {-2, 0}, {+1, -2}, {-2, +1}}; nextAngle = TetrisConstants.Angle90; break; default: //L->2 wallKickData = new[,] {{0, 0}, {-2, 0}, {+1, 0}, {-2, -1}, {+1, +2}}; nextAngle = TetrisConstants.Angle180; break; } } else { switch (currentAngle) { case TetrisConstants.Angle0: //0->L wallKickData = new[,] {{0, 0}, {1, 0}, {1, 1}, {0, -2}, {1, -2}}; nextAngle = TetrisConstants.Angle270; break; case TetrisConstants.Angle90: //R->0 wallKickData = new[,] {{0, 0}, {1, 0}, {1, -1}, {0, 2}, {1, 2}}; nextAngle = TetrisConstants.Angle0; break; case TetrisConstants.Angle180: //2->R wallKickData = new[,] {{0, 0}, {-1, 0}, {-1, 1}, {0, -2}, {-1, -2}}; nextAngle = TetrisConstants.Angle90; break; default: //L->2 wallKickData = new[,] {{0, 0}, {-1, 0}, {-1, -1}, {0, 2}, {-1, 2}}; nextAngle = TetrisConstants.Angle180; break; } } for (var i = 0; i < 5; i++) { var offsetX = wallKickData[i, 0]; var offsetY = - wallKickData[i, 1]; if (CheckAndApplyRotate(rotatedData, currentPiece, offsetX, offsetY)) { currentPiece.Pos.X += offsetX; currentPiece.Pos.Y += offsetY; currentPiece.Angle = nextAngle; return true; } } return false; } public bool RotateRight() { var currentPiece = _fieldState.CurrentPiece; //タイプOは無条件でtrue if (currentPiece.Type == TetrisConstants.PieceTypeO) { return true; } var rotatedData = currentPiece.GetRotateRightData(); var currentAngle = currentPiece.Angle; //https://tetris.wiki/Super_Rotation_System int[,] wallKickData; int nextAngle; if (currentPiece.Type == TetrisConstants.PieceTypeI) { switch (currentAngle) { case TetrisConstants.Angle0: //0->R wallKickData = new[,] {{0, 0}, {-2, 0}, {+1, 0}, {-2, -1}, {+1, +2}}; nextAngle = TetrisConstants.Angle90; break; case TetrisConstants.Angle90: //R->2 wallKickData = new[,] {{0, 0}, {-1, 0}, {+2, 0}, {-1, +2}, {+2, -1}}; nextAngle = TetrisConstants.Angle180; break; case TetrisConstants.Angle180: //2->L wallKickData = new[,] {{0, 0}, {+2, 0}, {-1, 0}, {+2, +1}, {-1, -2}}; nextAngle = TetrisConstants.Angle270; break; default: //L->0 wallKickData = new[,] {{0, 0}, {+1, 0}, {-2, 0}, {+1, -2}, {-2, +1}}; nextAngle = TetrisConstants.Angle0; break; } } else { switch (currentAngle) { case TetrisConstants.Angle0: //0->R wallKickData = new[,] {{0, 0}, {-1, 0}, {-1, 1}, {0, -2}, {-1, -2}}; nextAngle = TetrisConstants.Angle90; break; case TetrisConstants.Angle90: //R->2 wallKickData = new[,] {{0, 0}, {1, 0}, {1, -1}, {0, 2}, {1, 2}}; nextAngle = TetrisConstants.Angle180; break; case TetrisConstants.Angle180: //2->L wallKickData = new[,] {{0, 0}, {1, 0}, {1, 1}, {0, -2}, {1, -2}}; nextAngle = TetrisConstants.Angle270; break; default: //L->0 wallKickData = new[,] {{0, 0}, {-1, 0}, {-1, -1}, {0, 2}, {-1, 2}}; nextAngle = TetrisConstants.Angle0; break; } } for (var i = 0; i < 5; i++) { var offsetX = wallKickData[i, 0]; var offsetY = - wallKickData[i, 1]; if (CheckAndApplyRotate(rotatedData, currentPiece, offsetX, offsetY)) { currentPiece.Pos.X += offsetX; currentPiece.Pos.Y += offsetY; currentPiece.Angle = nextAngle; return true; } } return false; } private bool CheckAndApplyRotate(int[,] rotatedData, TetrisPiece currentPiece, int offsetX, int offsetY) { // 回転後にブロックと衝突するか for (var i = 0; i < rotatedData.GetLength(0); i++) { for (var j = 0; j < rotatedData.GetLength(1); j++) { var block = rotatedData[i, j]; if (block == 0) continue; var x = currentPiece.Pos.X + j + offsetX; var y = currentPiece.Pos.Y + i + offsetY; if (x < 0 || x >= TetrisConstants.PositionMaxX || y < 0 || y >= TetrisConstants.PositionMaxY || _fieldState.CurrentField[y, x] != 0) { // 衝突する場合は回転を適用しない return false; } } } // 回転を適用 Array.Copy(rotatedData, currentPiece.Data, currentPiece.Data.Length); return true; } public bool MoveLeft() { var currentPiece = _fieldState.CurrentPiece; var left = currentPiece.GetLeft(); var posX = currentPiece.Pos.X; var posY = currentPiece.Pos.Y; // はみ出し判定 if (posX + left <= 0) { return false; } // 左にブロックがあるか for (var i = 0; i < currentPiece.Data.GetLength(0); i++) { for (var j = 0; j < currentPiece.Data.GetLength(1); j++) { var block = currentPiece.Data[i, j]; if (block == 0) continue; var x = currentPiece.Pos.X + j - 1; var y = currentPiece.Pos.Y + i; if (x >= 0 && x < TetrisConstants.PositionMaxX && y >= 0 && y < TetrisConstants.PositionMaxY && _fieldState.CurrentField[y, x] != 0) { return false; } } } currentPiece.Pos.X -= 1; return true; } public bool MoveRight() { var currentPiece = _fieldState.CurrentPiece; var right = currentPiece.GetRight(); // はみ出し判定 if (currentPiece.Pos.X + right >= TetrisConstants.PositionMaxX - 1) { return false; } // 右にブロックがあるか for (var i = 0; i < currentPiece.Data.GetLength(0); i++) { for (var j = 0; j < currentPiece.Data.GetLength(1); j++) { var block = currentPiece.Data[i, j]; if (block == 0) continue; var x = currentPiece.Pos.X + j + 1; var y = currentPiece.Pos.Y + i; if (x >= 0 && x < TetrisConstants.PositionMaxX && y >= 0 && y < TetrisConstants.PositionMaxY && _fieldState.CurrentField[y, x] != 0) { return false; } } } currentPiece.Pos.X += 1; return true; } public bool MoveDown() { var currentPiece = _fieldState.CurrentPiece; var bottom = currentPiece.GetBottom(); // はみ出し判定 if (currentPiece.Pos.Y + bottom >= TetrisConstants.PositionMaxY - 1) { return false; } // 下にブロックがあるか for (var i = 0; i < currentPiece.Data.GetLength(0); i++) { for (var j = 0; j < currentPiece.Data.GetLength(1); j++) { var block = currentPiece.Data[i, j]; if (block == 0) continue; var x = currentPiece.Pos.X + j; var y = currentPiece.Pos.Y + i + 1; if (x >= 0 && x < TetrisConstants.PositionMaxX && y >= 0 && y < TetrisConstants.PositionMaxY && _fieldState.CurrentField[y, x] != 0) { return false; } } } currentPiece.Pos.Y += 1; return true; } } }
using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Yandex.Dialogs.Models.Interfaces; namespace Yandex.Dialogs.Models { [JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class OutputModel { public Response Response { get; set; } public Analytics.Analytics Analytics { get; set; } public AccountLinking StartAccountLinking { get; set; } public Session Session { get; set; } public State SessionState { get; set; } public State UserStateUpdate { get; set; } public State ApplicationState { get; set; } public string Version { get; set; } public void AddToSessionState(string key, object value) { if (SessionState == null) { SessionState = new State(); } SessionState.Add(key, value); } public void AddToUserState(string key, object value) { if (UserStateUpdate == null) { UserStateUpdate = new State(); } UserStateUpdate.Add(key, value); } public void AddToApplicationState(string key, object value) { if (ApplicationState == null) { ApplicationState = new State(); } ApplicationState.Add(key, value); } public void RequestAccountLinking() { StartAccountLinking = new AccountLinking(); } public void InitRequestGeolocation() { Response?.InitRequestGeolocation(); } public void AddAnalyticsEvent(string name, IDictionary<string, object> value) { if (Analytics == null) { Analytics = new Analytics.Analytics(); } Analytics.AddEvent(name, value); } } }
using Serenity; using Serenity.Data; using Serenity.Services; using System; using System.Data; using MyRequest = Serenity.Services.ListRequest; using MyResponse = Serenity.Services.ListResponse<ARLink.Default.CustomerRow>; using MyRow = ARLink.Default.CustomerRow; namespace ARLink.Default { public interface ICustomerListHandler : IListHandler<MyRow, MyRequest, MyResponse> {} public class CustomerListHandler : ListRequestHandler<MyRow, MyRequest, MyResponse>, ICustomerListHandler { public CustomerListHandler(IRequestContext context) : base(context) { } } }
using System.Windows.Controls; namespace LogUrFace.Views { /// <summary> /// Interaction logic for LogSheet /// </summary> public partial class LogSheet : UserControl { public LogSheet() { InitializeComponent(); } } }
using Jieshai.Cache.CacheIndexes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Jieshai.Cache.CacheManagers { public class ByGuidCacheManager<T> : CacheManager<T> where T : class, IGuidProvider { public ByGuidCacheManager() { } protected ByGuidCacheIndex<T> DicByGuid { private set; get; } protected override List<CacheIndex<T>> CreateCacheIndexes() { this.DicByGuid = new ByGuidCacheIndex<T>(this); return new List<CacheIndex<T>>() { this.DicByGuid }; } public virtual T GetByGuid(string guid) { return this.DicByGuid.GetByKey(guid); } public virtual bool ContainsGuid(string guid) { return this.DicByGuid.ContainsKey(guid); } public int GetByGuidCacheCount() { return this.DicByGuid.GetCacheCount(); } } }
using LineEditor.Properties; using System; using System.IO; using System.Linq; namespace LineEditor { /* * I didn't use oop style patterns like 'commands' and factory of commands * because there is no necessary to make queue and interactions between commands like powershell '|'. * Solution looks simple because task was simple */ class Program { static void Main(string[] args) { if (!args.Any()) { Console.WriteLine(Resources.FilePathEmpty); return; } var path = args.First(); if (!File.Exists(path)) { Console.WriteLine(Resources.FileNotFound); return; } ProcessDialog(path); } static void ProcessDialog(string path) { var lines = File.ReadAllLines(path); if (!lines.Any()) { Console.WriteLine(Resources.FileEmpty); return; } while (true) { var command = Console.ReadLine(); if (string.IsNullOrEmpty(command)) { Console.WriteLine(Resources.CommandEmpty); continue; } switch (command) { case "quit": return; case "save": try { File.WriteAllLines(path, lines); } catch(Exception ex) { Console.WriteLine($"{ex.GetType()} thrown: {ex.Message}"); } continue; case "list": for (var i = 0; i < lines.Length; i++) Console.WriteLine($"{i+1}: {lines[i]}"); continue; default: break; } var result = TryParseInsertDelete(lines, command); if (result == null) { Console.WriteLine(Resources.WrongCommand); continue; } lines = result; } } static string[] TryParseInsertDelete(string[] lines, string command) { var lineNumber = ParseLineNumber(command); if (!lineNumber.HasValue || lineNumber < 1 || lineNumber > lines.Length) return null; var newLines = lines.ToList(); if (command.StartsWith("ins ")) { newLines.Insert(lineNumber.Value, "new line"); return newLines.ToArray(); } else if (command.StartsWith("del ")) { newLines.RemoveAt(lineNumber.Value); return newLines.ToArray(); } return null; } static int? ParseLineNumber(string command) { var parts = command.Split(' '); if (!string.IsNullOrEmpty(parts[1]) && int.TryParse(parts[1], out int result)) return result - 1; return null; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MageLeftClick : Ability { protected string projectilePrefabPath1; protected GameObject projectilePrefab1; protected string projectilePrefabPath2; protected GameObject projectilePrefab2; protected string projectilePrefabPath3; protected GameObject projectilePrefab3; protected string projectilePrefabPath4; protected GameObject projectilePrefab4; private float speed; private float range; private bool canShootInCycle; private bool readyToShoot; private bool isPressed; private float classicDamage; private float classicHeal; private float fireDamage; private float fireHeal; private float iceDamage; private float iceHeal; private float iceSlowPercent; private float iceSlowDuration; private float lightDamage; private float lightHeal; private float horizontalSpeedPercentOnLeftClickActive; private Vector3 lastMousePosition; private MageMagic selectedMagic; private MageLeftClick() { baseCooldown = 1; cooldown = baseCooldown; horizontalSpeedPercentOnLeftClickActive = 0f; speed = 14; range = 35; classicDamage = 35; classicHeal = 10; fireDamage = 50; fireHeal = 0; iceDamage = 35; iceHeal = 0; iceSlowPercent = 0.4f; iceSlowDuration = 2; lightDamage = 0; lightHeal = 35; ChangeType((int)MageMagic.Classic); IsHoldDownAbility = true; projectilePrefabPath1 = "ProjectilePrefabs/MageClassicBasicAttack"; projectilePrefabPath2 = "ProjectilePrefabs/MageFireBasicAttack"; projectilePrefabPath3 = "ProjectilePrefabs/MageIceBasicAttack"; projectilePrefabPath4 = "ProjectilePrefabs/MageLightBasicAttack"; } protected override void Awake() { base.Awake(); LoadPrefabs(); } private void LoadPrefabs() { projectilePrefab1 = Resources.Load<GameObject>(projectilePrefabPath1); projectilePrefab2 = Resources.Load<GameObject>(projectilePrefabPath2); projectilePrefab3 = Resources.Load<GameObject>(projectilePrefabPath3); projectilePrefab4 = Resources.Load<GameObject>(projectilePrefabPath4); } public override bool IsAvailable() { return base.IsAvailable() && !player.PlayerMovementManager.PlayerIsMovingVertically(); } protected override void UseAbilityEffect(Vector3 mousePosition, bool isPressed, bool forceAbility = false) { if (this.isPressed != isPressed && !IsOnCooldown) { player.PlayerMovementManager.ChangeHorizontalSpeed(isPressed ? horizontalSpeedPercentOnLeftClickActive : 1); player.PlayerMovementManager.SetCanJump(!isPressed); } this.isPressed = isPressed; lastMousePosition = mousePosition; } public override void UseAbility(Vector3 mousePosition, bool isPressed, bool forceAbility = false) { UseAbilityEffect(mousePosition, isPressed, forceAbility); } public override void UseAbilityOnNetwork(Vector3 mousePosition, bool isPressed, bool forceAbility) { base.UseAbilityOnNetwork(mousePosition, isPressed, forceAbility); if (isPressed) { StartCoroutine(ShootOnNetwork()); } } private IEnumerator ShootOnNetwork() { cooldownRemaining = cooldown; yield return null; while (cooldownRemaining > cooldown * 0.5f) { cooldownRemaining -= Time.deltaTime; yield return null; } ShootProjectile(); isPressed = false; player.PlayerMovementManager.ChangeHorizontalSpeed(isPressed ? horizontalSpeedPercentOnLeftClickActive : 1); player.PlayerMovementManager.SetCanJump(!isPressed); } public override void ChangeType(int magic) { if (magic == (int)MageMagic.Classic) { selectedMagic = MageMagic.Classic; } else if (magic == (int)MageMagic.Fire) { selectedMagic = MageMagic.Fire; } else if (magic == (int)MageMagic.Ice) { selectedMagic = MageMagic.Ice; } else { selectedMagic = MageMagic.Light; } } private void Update() { if (player.PhotonView.isMine) { if (isPressed && !IsOnCooldown) { StartCooldown(); } else if (IsOnCooldown && readyToShoot) { readyToShoot = false; ShootProjectile(); isPressed = false; player.PlayerMovementManager.ChangeHorizontalSpeed(isPressed ? horizontalSpeedPercentOnLeftClickActive : 1); player.PlayerMovementManager.SetCanJump(!isPressed); } } } protected override IEnumerator PutAbilityOffCooldown() { IsOnCooldown = true; cooldownRemaining = cooldown; canShootInCycle = true; yield return null; //player.AbilityUIManager.SetAbilityOnCooldown(AbilityCategory, ID, IsBlocked); while (cooldownRemaining > 0) { cooldownRemaining -= Time.deltaTime; if (canShootInCycle && cooldownRemaining <= cooldown * 0.5f) { canShootInCycle = false; readyToShoot = true; } //player.AbilityUIManager.UpdateAbilityCooldown(AbilityCategory, ID, cooldownOnStart, cooldownRemaining); yield return null; } //player.AbilityUIManager.SetAbilityOffCooldown(AbilityCategory, ID, UsesResource, IsEnabled, IsBlocked); IsOnCooldown = false; } private void ShootProjectile() { Vector3 diff = lastMousePosition - transform.position; diff.Normalize(); float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg; Projectile projectile = Instantiate(GetProjectilePrefab(), transform.position + Vector3.back, Quaternion.Euler(0f, 0f, rot_z)).GetComponent<Projectile>(); projectile.transform.position += projectile.transform.right * projectile.transform.localScale.x * 0.55f; projectile.ShootProjectile((int)selectedMagic, speed, range); projectile.OnProjectileHit += OnProjectileHit; projectile.OnProjectileReachedEnd += OnProjectileReachedEnd; } private GameObject GetProjectilePrefab() { if (selectedMagic == MageMagic.Classic) { return projectilePrefab1; } else if (selectedMagic == MageMagic.Fire) { return projectilePrefab2; } else if (selectedMagic == MageMagic.Ice) { return projectilePrefab3; } else { return projectilePrefab4; } } private float GetDamage(int magic) { if (magic == (int)MageMagic.Classic) { return classicDamage; } else if (magic == (int)MageMagic.Fire) { return fireDamage; } else if (magic == (int)MageMagic.Ice) { return iceDamage; } else { return lightDamage; } } private float GetHeal(int magic) { if (magic == (int)MageMagic.Classic) { return classicHeal; } else if (magic == (int)MageMagic.Fire) { return fireHeal; } else if (magic == (int)MageMagic.Ice) { return iceHeal; } else { return lightHeal; } } private void OnProjectileHit(Projectile projectile, int magic, GameObject targetHit) { if (player.PhotonView.isMine) { if (targetHit.tag == "Player") { targetHit.GetComponent<Health>().Restore(GetHeal(magic)); } else if (targetHit.tag == "Enemy") { targetHit.GetComponent<Health>().Reduce(GetDamage(magic) * damageAmplification); } } if (targetHit.tag == "Enemy" && magic == (int)MageMagic.Ice) { targetHit.GetComponent<EnemyMovementManager>().SetSlow(this, iceSlowDuration, iceSlowPercent); } } private void OnProjectileReachedEnd(Projectile projectile) { Destroy(projectile.gameObject); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetworkLibrary.Core; namespace Shooter { class GameScreen : IScreen { Game _game; public GameScreen(Game game) { _game = game; } public IScreen Start() { if (Game.Network != null) Game.Network.RegisterEvent((int)PacketCode.ClearBullet, ClearBullet); Console.Clear(); while (Console.KeyAvailable) Console.ReadKey(true); _game.InitialiseGame(); int numPlayers = _game.NumberOfPlayers; if (_game.InStoryMode) { Menu m; if (_game.StoryLevel == 0) { m = new Menu("Tutorial", Label.CreateLabelArrayFromText( "\nFirst time player? Here is some info you might\nwant to know:\n\n" + "Weapons:\n p = Pistol (Ammo: 7, Speed: slow, Damage: 15hp)\n" + " m = Machine gun (Ammo: 50, Speed: fast, Damage: 5hp)\n" + "Other:\n D = Door\n X = Locked door, need a key to open\n k = Key, need to open locked doors\n\n e = Enemies, shoot them\n")); m.Start(-1, 5); m.Clear(); } _game.Board.ParseMapText(); m = new Menu(Label.CreateLabelArrayFromText("\n" + _game.Board.Map.MapText)); m.Start(-1, 3); m.Clear(); } Console.CursorVisible = false; _game.Board.DrawBase(); int alive = 0; do { if (Game.Network != null && !Game.Network.NetworkConnection.Connected) return new Main(); if (!_game.InCutSchene) _game.Board.Update(); _game.Board.Draw(); System.Threading.Thread.Sleep(10); alive = 0; for (int i = 0; i < _game.Players.Length; i++) if (_game.Players[i] != null) if (_game.Players[i].Unit.Health > 0) alive++; if (alive == 1 && numPlayers > 1 && !_game.Board.Coop) _game.Won = true; } while (!Game.KeyIsDown((int)System.Windows.Forms.Keys.Escape) && !_game.Won && alive > 0); while (Console.KeyAvailable) Console.ReadKey(true); if (alive == 0) { Menu m = new Menu("Game Over", Label.CreateLabelArrayFromText( "You lost the game. ")); m.Start(-1, 5); System.Threading.Thread.Sleep(1000); m.Clear(); } if (_game.Won) { _game.Won = false; if (_game.InStoryMode) { if (_game.LoadStoryMode()) { Menu m = new Menu("You won", Label.CreateLabelArrayFromText( "Congratulations, you just won the game!")); m.Start(-1, 5); System.Threading.Thread.Sleep(2000); m.Clear(); } else { _game.Board = null; return new Shop(_game); } } else { if (_game.Board.Coop) { Menu m = new Menu("You won", Label.CreateLabelArrayFromText( "Congratulations, you people won the level!")); m.Start(-1, 5); System.Threading.Thread.Sleep(2000); m.Clear(); } else { string name = ""; for (int i = 0; i < _game.Players.Length; i++) if (_game.Players[i] != null) if (_game.Players[i].Unit.Health > 0) { name = _game.Players[i].Name; break; } Menu m = new Menu(name + " won", Label.CreateLabelArrayFromText( "Congratulations " + name + ", you are the winner!")); m.Start(-1, 5); System.Threading.Thread.Sleep(2000); m.Clear(); } } } return new Main(); } private void ClearBullet(object sender, NetworkEventArgs args) { (args.Data as Shot).Clear(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MPD.Entities.Domain { public partial class AcceptedQuote { public Guid AcceptedQuoteId { get; set; } public Guid JobQuoteId { get; set; } [Required] [Column("PONumber")] [StringLength(50)] public string Ponumber { get; set; } [Required] [Column("PODocument")] [StringLength(500)] public string Podocument { get; set; } [Column(TypeName = "smalldatetime")] public DateTime CreatedDate { get; set; } [ForeignKey("JobQuoteId")] [InverseProperty("AcceptedQuote")] public JobQuote JobQuote { get; set; } } }
using System.Collections.Generic; using PrincessApollo.Controls; using UnityEngine; public class DefaultKeys { [RuntimeInitializeOnLoadMethod] static void OnLoad() { Controls.DefaultScheme = new ControlScheme(new Dictionary<string, string>(){ {"PlayerOne-Forward", nameof(KeyCode.W)}, {"PlayerOne-Back", nameof(KeyCode.S)}, {"PlayerOne-Left", nameof(KeyCode.A)}, {"PlayerOne-Right", nameof(KeyCode.D)}, {"PlayerOne-Punch", nameof(KeyCode.Space)}, {"PlayerOne-Block", nameof(KeyCode.V)}, {"PlayerOne-Dash", nameof(KeyCode.LeftShift)}, {"PlayerTwo-Forward", nameof(KeyCode.UpArrow)}, {"PlayerTwo-Back", nameof(KeyCode.DownArrow)}, {"PlayerTwo-Left", nameof(KeyCode.LeftArrow)}, {"PlayerTwo-Right", nameof(KeyCode.RightArrow)}, {"PlayerTwo-Punch", nameof(KeyCode.Return)}, {"PlayerTwo-Block", nameof(KeyCode.RightShift)}, {"PlayerTwo-Dash", nameof(KeyCode.LeftControl)}, }); /* Sätter default schemet i Controlls bc Controls is in another assembly se paketet "se.princessapollo.ControlScheme" eller https://github.com/FredrikAlHam/UnityControlSchemeFromJson. Eftersom repon är public så finns alla dess kommentarer här. se.princessapollo.ControlScheme skapar en json file som ger keycodes namn, på runtime så skapar den antingen en ny efter DefaultScheme eller läser en från hårdisken från en fil som heter controls.ctrl i data foldern av spelet // Fredrik (Author of se.princessapollo.ControlScheme) P.S. Unity Package Manager är en ****** */ } }
using System; using System.Collections.Generic; using System.Text; namespace API.Omorfias.Domain.Base.Configuration { public static class Configuration { private static Dictionary<string, string> _tabelaValores = new Dictionary<string, string>(); public static T ObterValor<T>(string chave) { if (_tabelaValores.ContainsKey(chave)) { return (T)Convert.ChangeType(_tabelaValores[chave], typeof(T)); } return default(T); } public static void InserirRegistro(KeyValuePair<string, string> registro) { _tabelaValores[registro.Key] = registro.Value; } public static void InserirRegistros(IEnumerable<KeyValuePair<string, string>> registros) { foreach (KeyValuePair<string, string> _registro in registros) { _tabelaValores.Add(_registro.Key, _registro.Value); } } public static void LimparRegistros() { _tabelaValores.Clear(); } } }
using Whale.DAL.Abstraction; namespace Whale.DAL.Models { public class Achivement : BaseEntity { public string Label { get; set; } public int Rarity { get; set; } } }
using System; using FluentValidator; namespace PbStore.Domain.Pedidos { public abstract class Entidade : Notifiable { protected Entidade() { Id = Guid.NewGuid(); } public Guid Id { get; private set; } } }
void FillArray (int[] collection) { int length = collection.Length; int index = 0; while(index< length) { collection[index] = new Random().Next(1,10); index++; } } void PrintArray (int[] col) { int count = col.Length; int position = 0; while (position< count) { Console.WriteLine(col[position]); position++; } } int IndexOf (int [] collection, int find) { int count = collection.Length; int index = 0; int position = 0; while (index<count) { if (collection[index]== find) { position = index; } index++; } return position; } int [] array = new int [10]; FillArray (array); PrintArray (array); Console.WriteLine(); int pos = IndexOf (array, 4); Console.WriteLine(pos);
using Application.Contract.RepositoryInterfaces; using Application.Contract.Requests; using Application.CQRS.Commands; using Application.CQRS.Validations; using Domain.Models; using FakeItEasy; using FluentValidation.TestHelper; using Xunit; namespace Application.Test.CQRS.Validations { public class AddCryptoCurrencyValidationTest { private readonly AddCryptoCurrencyValidation _testee; private readonly ICryptoCurrencyRepository _cryptoCurrencyRepository; public AddCryptoCurrencyValidationTest() { _cryptoCurrencyRepository = A.Fake<ICryptoCurrencyRepository>(); _testee = new AddCryptoCurrencyValidation(_cryptoCurrencyRepository); } [Theory] [InlineData("")] [InlineData("a")] [InlineData("bvbdd")] [InlineData("ASDF")] [InlineData("1231wee")] public async void Code_WhenNullOrNotThreeCharachter_ShouldHaveValidationError(string code) { A.CallTo(() => _cryptoCurrencyRepository.GetCryptoCurrencyByCodeAsync(code, default)).Returns<CryptoCurrency>(null); var request = new CryptoCurrencyAddRequest() { Code = code }; await _testee.ShouldHaveValidationErrorForAsync(x => x.Code, new AddCryptoCurrencyCommand(request)); } [Theory] [InlineData("aaa")] [InlineData("123")] [InlineData("APa")] [InlineData("FeD")] [InlineData("1AD")] [InlineData("kLO")] public async void Code_WhenAllThreeCharachtersAreNotUpperCaseLetters_ShouldHaveValidationError(string code) { A.CallTo(() => _cryptoCurrencyRepository.GetCryptoCurrencyByCodeAsync(code, default)).Returns<CryptoCurrency>(null); var request = new CryptoCurrencyAddRequest() { Code = code }; (await _testee.ShouldHaveValidationErrorForAsync(x => x.Code, new AddCryptoCurrencyCommand(request))) .WithErrorMessage("The 'Code' must be 3 upper case letters"); } [Theory] [InlineData("BTC")] [InlineData("AAA")] [InlineData("ADG")] public async void Code_WhenAllThreeCharachtersAreUpperCaseLetters_ShouldNotHaveValidationError(string code) { A.CallTo(() => _cryptoCurrencyRepository.GetCryptoCurrencyByCodeAsync(code, default)).Returns<CryptoCurrency>(null); var request = new CryptoCurrencyAddRequest() { Code = code }; await _testee.ShouldNotHaveValidationErrorForAsync(x => x.Code, new AddCryptoCurrencyCommand(request)); } [Theory] [InlineData("BTC")] [InlineData("AAA")] [InlineData("ADG")] public async void Code_WhenThreIsInDataBase_ShouldHaveValidationError(string code) { var respone = new CryptoCurrency() { Code = code }; A.CallTo(() => _cryptoCurrencyRepository.GetCryptoCurrencyByCodeAsync(code, default)).Returns(respone); var request = new CryptoCurrencyAddRequest() { Code = code }; (await _testee.ShouldHaveValidationErrorForAsync(x => x.Code, new AddCryptoCurrencyCommand(request))) .WithErrorMessage("The 'Code' already exist!"); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Radzen; using Radzen.Blazor; using Microsoft.AspNetCore.Components; using CryptobotUi.Client.Model; using CryptobotUi.Models.Shared; namespace CryptobotUi.Pages { public partial class DashboardComponent { [Inject] protected AppState AppState { get; set; } [Inject] protected DashboardServiceClient DashboardServiceClient { get; set; } protected DashboardFilter Filter { get; set; } = new DashboardFilter(); protected DashboardData Data { get; set; } = new DashboardData(); protected string[] PositionTypes => Enum.GetNames<PositionTypes>(); protected async Task LoadDashboard() { try { AppState.IsBusy = true; Data = await DashboardServiceClient.GetDashboardData(Filter); } catch (Exception ex) { NotificationService.Notify( new NotificationMessage { Severity = NotificationSeverity.Error, Summary = $"Error", Detail = $"Unable to load dashboard: {ex.Message}" }); JSRuntime.Log($"Error: {ex}"); } finally { AppState.IsBusy = false; Reload(); } } } }
using System; using LibCurl; namespace Samples { class BookPost { public void Perform() { try { using (Curl curl = new Curl()) { //Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); curl.OnWriteCallback = new Curl.GenericCallbackDelegate(OnWriteData); curl.SetWriteData(null); // simple post - with a string curl.SetPost(); curl.SetPostFields("url=index%3Dstripbooks&field-keywords=Topology&Go.x=10&Go.y=10"); curl.SetUserAgent("Mozilla 4.0 (compatible; MSIE 6.0; Win32"); curl.SetFollowLocation(true); curl.SetUrl("http://www.amazon.com/exec/obidos/search-handle-form/002-5928901-6229641"); curl.Perform(); } } catch (Exception ex) { Console.WriteLine(ex); } } int OnWriteData(byte[] buf, int size, object userdata) { Console.Write(System.Text.Encoding.UTF8.GetString(buf)); return size; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Homework_Theme_01 { /// <summary> /// Организация хранения данных. /// </summary> class Repository { /// <summary> /// База данных работников (записная книжка в конкретном случае), в которой хранятся /// Имя, возраст, рост, баллы по русскому, истории и математике /// </summary> public List<Employee> Employees { get; set; } /// <summary> /// Конструктор /// </summary> public Repository() { this.Employees = new List<Employee>(); } /// <summary> /// Метод добавления сотрудника в репозиторий /// </summary> /// <param name="employee">Сотрудник. Объект класса Employee</param> public void Save(Employee employee) { this.Employees.Add(employee); } /// <summary> /// Форматированный вывод данных из репозитория /// </summary> /// <param name="message"></param> public void Print(string message) { Console.WriteLine(message); string pattern = "Имя: {0}\nВозраст: {1}\nРост: {2}\nРусский(балл): {3}\nИстория(балл): {4}\nМатематика(балл): {5}\nСредний(балл): {6}"; foreach (Employee employee in this.Employees) { Console.WriteLine(pattern, employee.Name, employee.Age, employee.Height, employee.RussianScores, employee.HistoryScores, employee.MathScores, Math.Round(employee.AverageScore, 2)); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; namespace RMAT3.Models { public class Appointment { public Appointment() { Appointment1 = new List<Appointment>(); } public Guid AppointmentId { get; set; } public string AddedByUserId { get; set; } public DateTime AddTs { get; set; } public string UpdatedByUserId { get; set; } public DateTime UpdatedTs { get; set; } public bool IsActiveInd { get; set; } public string Annotation { get; set; } public string Description { get; set; } public DateTime EndTs { get; set; } public bool? IsAllDayInd { get; set; } public Guid? RecurrenceParentId { get; set; } public string RecurrenceRuleTxt { get; set; } public string Reminder { get; set; } public DateTime StartTs { get; set; } public string Title { get; set; } public int UserId { get; set; } public virtual ICollection<Appointment> Appointment1 { get; set; } public virtual Appointment Appointment2 { get; set; } public virtual AppUser AppUser { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Irish_Poker { class StartScreen : GameScreen { SpriteFont spriteFont; public StartScreen(Game game, SpriteBatch spriteBatch, SpriteFont spriteFont) : base(game, spriteBatch) { this.spriteFont = spriteFont; } public override void Draw(GameTime gameTime) { base.Draw(gameTime); spriteBatch.DrawString(spriteFont, "Math Battle!", new Vector2(175, 75), Color.Black); } public override void Update(GameTime gameTime) { base.Update(gameTime); } public override void Initialize() { base.Initialize(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace AnimalDB { public partial class GyvunaiAdd : System.Web.UI.Page { public List<Lytis> lytysList = new List<Lytis>(); public List<Savininkas> savininkaiList = new List<Savininkas>(); public List<Isvaizda> isvaizdaList = new List<Isvaizda>(); public List<Mikro> mikrosList = new List<Mikro>(); public List<Registracija> regList = new List<Registracija>(); public List<Sveikata> sveikList = new List<Sveikata>(); public List<Veisle> veislList = new List<Veisle>(); public string conString = @"Data Source=localhost;port=3306;Initial catalog=animal; User Id= root; password=''"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Kontekstas test = new Kontekstas(conString); #region lytys lytysList = test.GetLytis(); Dictionary<int, string> lytys = new Dictionary<int, string>(); foreach (Lytis lytis in lytysList) { lytys.Add(lytis.id, lytis.name); } DropDownList1.DataSource = lytys; DropDownList1.DataTextField = "Value"; DropDownList1.DataValueField = "Key"; DropDownList1.DataBind(); #endregion #region savininkai savininkaiList = test.GetSavininkas(); List<long> savId = new List<long>(); foreach (Savininkas sav in savininkaiList) { savId.Add(sav.id); } DropDownList2.DataSource = savId; DropDownList2.DataBind(); #endregion #region isvaizda isvaizdaList = test.GetIsvaizda(); List<int> isvId = new List<int>(); foreach (Isvaizda isv in isvaizdaList) { isvId.Add(isv.id); } DropDownList3.DataSource = isvId; DropDownList3.DataBind(); #endregion #region mikroschema mikrosList = test.GetMikro(); List<int> mikroList = new List<int>(); foreach (Mikro mik in mikrosList) { mikroList.Add(mik.numeris); } DropDownList5.DataSource = mikroList; DropDownList5.DataBind(); #endregion #region registracija regList = test.GetRegistracija(); List<int> registNr = new List<int>(); foreach (Registracija reg in regList) { registNr.Add(reg.numeris); } DropDownList6.DataSource = registNr; DropDownList6.DataBind(); #endregion #region sveikata sveikList = test.GetSveikata(); List<DateTime> datuList = new List<DateTime>(); foreach (Sveikata sveik in sveikList) { datuList.Add(sveik.Vizito_data.Date); } DropDownList4.DataSource = datuList; DropDownList4.DataBind(); #endregion #region veisle veislList = test.GetVeisle(); List<string> veisles = new List<string>(); foreach (Veisle veis in veislList) { veisles.Add(veis.pavadinimas); } DropDownList7.DataSource = veisles; DropDownList7.DataBind(); #endregion } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { } protected void Main_Click(object sender, EventArgs e) { Server.Transfer("HomePage.aspx"); } protected void Klasės_Click1(object sender, EventArgs e) { Server.Transfer("KlaseList.aspx"); } protected void Gyvunai_Click(object sender, EventArgs e) { Server.Transfer("GyvunaiList.aspx"); } protected void Savininkai_Click(object sender, EventArgs e) { Server.Transfer("SavininkaiList.aspx"); } protected void Veisle_Click(object sender, EventArgs e) { Server.Transfer("VeisleList.aspx"); } protected void Registracijos_Click(object sender, EventArgs e) { Server.Transfer("GegistracijosList.aspx"); } protected void Button1_Click(object sender, EventArgs e) { try { Kontekstas test = new Kontekstas(conString); if (String.IsNullOrEmpty(TextBox_Vardas.Text)) { throw new Exception("Tuscias vardo laukelis"); } string vardas = TextBox_Vardas.Text; if (String.IsNullOrEmpty(TextBox1.Text)) { throw new Exception("Tuscias datos laukelis"); } DateTime db = Convert.ToDateTime(TextBox1.Text).Date; int lytis = int.Parse(DropDownList1.SelectedValue); long savininkas = long.Parse(DropDownList2.SelectedValue); int isvaizda = int.Parse(DropDownList3.SelectedValue); DateTime vizitoData = DateTime.Parse(DropDownList4.SelectedValue).Date; int mikro = int.Parse(DropDownList5.SelectedValue); int reg = int.Parse(DropDownList6.SelectedValue); string veisle = DropDownList7.SelectedValue; test.AddGyvunas(vardas, db, lytis, savininkas, isvaizda, veisle, vizitoData, mikro, reg); } catch(Exception exception) { Label8.Text = exception.Message; return; } Server.Transfer("GyvunaiList.aspx"); } protected void Button2_Click(object sender, EventArgs e) { Server.Transfer("Ataskaitos.aspx"); } } }
using System; using Entities; namespace Services { public class UserService { private User currentUser; private static UserService userService; protected UserService() { currentUser = new User(); } public void addEntity(Entity ent) { } public void updateEntity(Entity ent) { } public void deleteEntity(Entity ent) { } public void addTransaction(Transaction trn) { } public void logOut() { } public void search() { } public static UserService getInstance() { if (userService == null) { userService = new UserService(); } return userService; } } }
using System; using KompasKeyboardPlugin; using NUnit.Framework; using Kompas6API5; namespace UnitTests.KompasKeyboardPlugin { /// <summary> /// Модульное тестирование класса BoardCreator. /// </summary> [TestFixture] public class BordCreatorTest { /// <summary> /// Тестирование метода Build. /// </summary> [Test] [TestCase(TestName = "Тест с передачей null объекта")] public void BuildTestNegative() { KeyboardParametersStorage keyboardDataNull = null; ksDocument3D document3DNull = null; var obj = new BoardCreator(); Assert.Throws<NullReferenceException>(() => obj.Build(document3DNull, keyboardDataNull)); } } }
using Arcanoid.Context; using Arcanoid.GameObjects.Interfaces; using SFML.Graphics; using SFML.System; namespace Arcanoid.GameObjects { internal class Ball : Transformable, IGameObject { private Vector2f position = new Vector2f(0.0f, 0.0f); private Vector2f direction = new Vector2f(1.0f, -1.0f); private readonly Sprite image; public Ball(Sprite image, GameContext context) { this.image = image; position = context.Ball.Position; direction = new Vector2f(context.Ball.Speed, -context.Ball.Speed); } public void Invoke(GameContext context) { var diametr = context.Ball.diametr; if (context.Ball.BrickTouchX) { direction.X *= -1; context.Ball.BrickTouchX = false; } if (context.Ball.BrickTouchY) { direction.Y *= -1; context.Ball.BrickTouchY = false; } position.X += direction.X; position.Y += direction.Y; if (position.X + diametr > context.World.Scale.X || position.X < 0) { direction.X = direction.X * -1.0f; } if (position.Y + diametr > context.World.Scale.Y || position.Y < 0) { direction.Y = direction.Y * -1.0f; } if (position.Y + diametr > context.Board.Position.Y && position.X > context.Board.Position.X && position.X < context.Board.Position.X + context.Board.Scale.X) { direction.Y *= -1; } context.Ball.Position = position; } public void Draw(RenderTarget target, RenderStates states) { image.Position = position; states.Transform *= Transform; target.Draw(image); } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("GeneralStoreContent")] public class GeneralStoreContent : MonoBehaviour { public GeneralStoreContent(IntPtr address) : this(address, "GeneralStoreContent") { } public GeneralStoreContent(IntPtr address, string className) : base(address, className) { } public bool AnimateEntranceEnd() { return base.method_11<bool>("AnimateEntranceEnd", Array.Empty<object>()); } public bool AnimateEntranceStart() { return base.method_11<bool>("AnimateEntranceStart", Array.Empty<object>()); } public bool AnimateExitEnd() { return base.method_11<bool>("AnimateExitEnd", Array.Empty<object>()); } public bool AnimateExitStart() { return base.method_11<bool>("AnimateExitStart", Array.Empty<object>()); } public void FireBundleChangedEvent() { base.method_8("FireBundleChangedEvent", Array.Empty<object>()); } public NoGTAPPTransactionData GetCurrentGoldBundle() { return base.method_14<NoGTAPPTransactionData>("GetCurrentGoldBundle", Array.Empty<object>()); } public Network.Bundle GetCurrentMoneyBundle() { return base.method_14<Network.Bundle>("GetCurrentMoneyBundle", Array.Empty<object>()); } public string GetMoneyDisplayOwnedText() { return base.method_13("GetMoneyDisplayOwnedText", Array.Empty<object>()); } public bool HasBundleSet() { return base.method_11<bool>("HasBundleSet", Array.Empty<object>()); } public bool IsContentActive() { return base.method_11<bool>("IsContentActive", Array.Empty<object>()); } public bool IsPurchaseDisabled() { return base.method_11<bool>("IsPurchaseDisabled", Array.Empty<object>()); } public void OnBundleChanged(NoGTAPPTransactionData goldBundle, Network.Bundle moneyBundle) { object[] objArray1 = new object[] { goldBundle, moneyBundle }; base.method_8("OnBundleChanged", objArray1); } public void OnCoverStateChanged(bool coverActive) { object[] objArray1 = new object[] { coverActive }; base.method_8("OnCoverStateChanged", objArray1); } public void OnRefresh() { base.method_8("OnRefresh", Array.Empty<object>()); } public void PostStoreFlipIn(bool animatedFlipIn) { object[] objArray1 = new object[] { animatedFlipIn }; base.method_8("PostStoreFlipIn", objArray1); } public void PostStoreFlipOut() { base.method_8("PostStoreFlipOut", Array.Empty<object>()); } public void PreStoreFlipIn() { base.method_8("PreStoreFlipIn", Array.Empty<object>()); } public void PreStoreFlipOut() { base.method_8("PreStoreFlipOut", Array.Empty<object>()); } public void Refresh() { base.method_8("Refresh", Array.Empty<object>()); } public void SetContentActive(bool active) { object[] objArray1 = new object[] { active }; base.method_8("SetContentActive", objArray1); } public void SetCurrentGoldBundle(NoGTAPPTransactionData bundle) { object[] objArray1 = new object[] { bundle }; base.method_8("SetCurrentGoldBundle", objArray1); } public void SetCurrentMoneyBundle(Network.Bundle bundle, bool force) { object[] objArray1 = new object[] { bundle, force }; base.method_8("SetCurrentMoneyBundle", objArray1); } public void SetParentStore(GeneralStore parentStore) { object[] objArray1 = new object[] { parentStore }; base.method_8("SetParentStore", objArray1); } public void StoreHidden(bool isCurrent) { object[] objArray1 = new object[] { isCurrent }; base.method_8("StoreHidden", objArray1); } public void StoreShown(bool isCurrent) { object[] objArray1 = new object[] { isCurrent }; base.method_8("StoreShown", objArray1); } public NoGTAPPTransactionData m_currentGoldBundle { get { return base.method_3<NoGTAPPTransactionData>("m_currentGoldBundle"); } } public Network.Bundle m_currentMoneyBundle { get { return base.method_3<Network.Bundle>("m_currentMoneyBundle"); } } public bool m_isContentActive { get { return base.method_2<bool>("m_isContentActive"); } } public GeneralStore m_parentStore { get { return base.method_3<GeneralStore>("m_parentStore"); } } } }
using System; namespace OCP.FullTextSearch.Model { /** * @since 16.0.0 * * Interface ISearchOption * * @package OCP\FullTextSearch\Model */ interface ISearchOption { /** * @since 16.0.0 */ const CHECKBOX = 'checkbox'; /** * @since 16.0.0 */ const INPUT = 'input'; /** * @since 16.0.0 */ const INPUT_SMALL = 'small'; /** * Set the name/key of the option. * The string should only contains alphanumerical chars and underscore. * The key can be retrieve when using ISearchRequest::getOption * * @see ISearchRequest::getOption * * @since 16.0.0 * * @param string name * * @return ISearchOption */ public function setName(string name): ISearchOption; /** * Get the name/key of the option. * * @since 16.0.0 * * @return string */ public function getName(): string; /** * Set the title/display name of the option. * * @since 16.0.0 * * @param string title * * @return ISearchOption */ public function setTitle(string title): ISearchOption; /** * Get the title of the option. * * @since 16.0.0 * * @return string */ public function getTitle(): string; /** * Set the type of the option. * type can be ISearchOption::CHECKBOX or ISearchOption::INPUT * * @since 16.0.0 * * @param string type * * @return ISearchOption */ public function setType(string type): ISearchOption; /** * Get the type of the option. * * @since 16.0.0 * * @return string */ public function getType(): string; /** * In case of Type is INPUT, set the size of the input field. * Value can be ISearchOption::INPUT_SMALL or not defined. * * @since 16.0.0 * * @param string size * * @return ISearchOption */ public function setSize(string size): ISearchOption; /** * Get the size of the INPUT. * * @since 16.0.0 * * @return string */ public function getSize(): string; /** * In case of Type is , set the placeholder to be displayed in the input * field. * * @since 16.0.0 * * @param string placeholder * * @return ISearchOption */ public function setPlaceholder(string placeholder): ISearchOption; /** * Get the placeholder. * * @since 16.0.0 * * @return string */ public function getPlaceholder(): string; } }
// Copyright 2020 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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; namespace NtApiDotNet.Win32.Security.Authenticode { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public enum ImageEnclavePolicyFlags { None = 0, Debuggable = 1, } public enum ImageEnclaveFlag { None = 0, PrimaryImage = 1, } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member [StructLayout(LayoutKind.Sequential)] internal struct IMAGE_ENCLAVE_CONFIG { public int Size; public int MinimumRequiredConfigSize; public ImageEnclavePolicyFlags PolicyFlags; public int NumberOfImports; public int ImportList; public int ImportEntrySize; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] FamilyID; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] ImageID; public int ImageVersion; public int SecurityVersion; public IntPtr EnclaveSize; public int NumberOfThreads; public ImageEnclaveFlag EnclaveFlags; } /// <summary> /// Class to represent a VSM enclave configuration. /// </summary> public sealed class EnclaveConfiguration { /// <summary> /// Minimum required configuration size. /// </summary> public int MinimumRequiredConfigSize { get; } /// <summary> /// Policy flags. /// </summary> public ImageEnclavePolicyFlags PolicyFlags { get; } /// <summary> /// List of enclave imports. /// </summary> public IReadOnlyList<EnclaveImport> Imports { get; } /// <summary> /// Family ID. /// </summary> public byte[] FamilyID { get; } /// <summary> /// Image ID. /// </summary> public byte[] ImageID { get; } /// <summary> /// Image version. /// </summary> public int ImageVersion { get; } /// <summary> /// Security version. /// </summary> public int SecurityVersion { get; } /// <summary> /// Size of the enclave. /// </summary> public long EnclaveSize { get; } /// <summary> /// Number of threads for the enclave. /// </summary> public int NumberOfThreads { get; } /// <summary> /// Enclave flags. /// </summary> public ImageEnclaveFlag Flags { get; } /// <summary> /// Is the enclave debuggable. /// </summary> public bool Debuggable => PolicyFlags.HasFlagSet(ImageEnclavePolicyFlags.Debuggable); /// <summary> /// Is this a primary image. /// </summary> public bool PrimaryImage => Flags.HasFlagSet(ImageEnclaveFlag.PrimaryImage); /// <summary> /// Path to the image file. /// </summary> public string ImagePath { get; } /// <summary> /// Name of the image file. /// </summary> public string Name => Path.GetFileName(ImagePath); /// <summary> /// ToString method. /// </summary> /// <returns>The object as a string.</returns> public override string ToString() { return $"{Name} - Primary Image {PrimaryImage}"; } internal EnclaveConfiguration(string path, IMAGE_ENCLAVE_CONFIG config, IEnumerable<EnclaveImport> imports) { MinimumRequiredConfigSize = config.MinimumRequiredConfigSize; PolicyFlags = config.PolicyFlags; Imports = imports.ToList().AsReadOnly(); FamilyID = config.FamilyID; ImageID = config.ImageID; ImageVersion = config.ImageVersion; SecurityVersion = config.SecurityVersion; EnclaveSize = config.EnclaveSize.ToInt64(); NumberOfThreads = config.NumberOfThreads; Flags = config.EnclaveFlags; ImagePath = path; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ANNXOR { class InputNode { public InputNode(double input, double weight) { Input = input; Weight = weight; } public double Input; public double Weight; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace VirtualDisk { /// <summary> /// Cmd命令拆分等操作工具 /// </summary> class CmdStrTool { /// <summary> /// 将命令参数拆分成路径参数和附加参数 /// </summary> public static void SplitParam(string param, string[] supportAddParam, out string path, out string addParam) { string[] p1 = SplitStringHasSpace(param); if (p1.Length > 0) { foreach (string item in supportAddParam) { if (item == p1[0]) { addParam = item; if (p1.Length > 1) { //path = p1[1]; //path.Replace("/", "\\"); StringBuilder ssb = new StringBuilder(); for (int i = 1; i < p1.Length; i++) { if (i != 1) ssb.Append(" "); ssb.Append(p1[i]); } ssb.Replace("/", "\\"); path = ssb.ToString(); } else { path = ""; } return; } } //path = p1.; StringBuilder sb = new StringBuilder(); for (int i = 0; i < p1.Length; i++) { if(i != 0) sb.Append(" "); sb.Append(p1[i]); } sb.Replace("/", "\\"); path = sb.ToString(); addParam = ""; } else { path = ""; addParam = ""; } } /// <summary> /// 将路径参数拆分成多个路径 /// </summary> public static string[] SplitPathParamToPathList(string pathParam) { string[] pathlist = pathParam.Split(' '); return pathlist; } /// <summary> /// 将路径拆分成namelist /// </summary> public static string[] SplitPathToNameList(string path) { string[] namelist = path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); return namelist; } ///使用空格切分,但路径可能有空格时候的拆分 static string[] SplitStringHasSpace(string path) { bool backing = false; char tmp = '_'; char[] chars = path.ToCharArray(); for (int i = 0; i < chars.Length; i++) { if(chars[i] == '\"') { if (backing) //双引号末尾了 { backing = false; } else //双引号开始 { backing = true; } } else { if (backing) //检查 { if(chars[i] == ' ') { chars[i] = tmp; } } else //下一个 { continue; } } } string str = new string(chars); string[] pathlist = str.Split(' '); //foreach (string item in pathlist) //{ // item.Replace("_", "&nbsp;"); //} return pathlist; } /// <summary> /// 通配符转正则 处理 ? * /// </summary> public static String WildCardToRegex(string rex) { return "^" + Regex.Escape(rex).Replace("\\?", ".").Replace("\\*", ".*") + "$"; } public static bool NameIsGood(string name) { return name.Contains("\\") || name.Contains("*") || name.Contains("/") || name.Contains("_") || name.Contains("?") || name.Contains(":") || name.Contains("\""); } //------------其他方法------------- public static void ShowTips(int tip) { Console.WriteLine(Tips[tip]); } readonly static Dictionary<int, string> Tips = new Dictionary<int, string> { {1, "命令格式不正确"}, {2, "命令格式不正确或路径不正确"}, {3, "不可以修改根结点"}, {4, "已经存在此结点" }, {5, "文件名不合规范还有非法字符"}, {6, "找不到系统磁盘路径或加载文件格式错误"}, {7, "保存文件失败"} }; } }
using System.Collections.Generic; using System.Diagnostics; namespace SnippetBoy { public static partial class Permutations { /// <summary> /// Generates (non-recursive) an lexicographic ordered sequence of permutations /// on a set of integers 0 to n-1 using Ord-Smith's algorithm (1968). /// </summary> /// <param name="n"> /// The number of integers in the set. /// </param> /// <returns> /// An IEnumerable&lt;int[]&gt; that contains the permutations. /// </returns> public static IEnumerable<int[]> OrdSmith(int n) { Debug.Assert(n > 0); int[] a = new int[n]; int[] d = new int[n]; bool first = true, od = false; int i, j, tmp; for (i = 0; i < n; a[i] = i, i++) ; void next() { if (first) { first = false; od = true; for (i = n - 1; i > 0; d[i--] = 0) ; } if (od) { od = false; tmp = a[n - 1]; a[n - 1] = a[n - 2]; a[n - 2] = tmp; } else { od = true; d[j = 1]++; while (d[j] > j + 1) { d[j++] = 0; d[j]++; } if (j >= n - 1) { first = true; } else { i = n - d[j]; tmp = a[n - j - 2]; a[n - j - 2] = a[i]; a[i] = tmp; i = 0; do { tmp = a[n - i - 1]; a[n - i - 1] = a[n - j - 1]; a[n - j - 1] = tmp; } while (++i < --j); } } } yield return a; if (n > 1) { for (next(); !first; next()) { yield return a; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameController_Demo : MonoBehaviour { public GameObject enemy; // enemy public GameObject Player; // player object public float spawnRate; // how often to spawn enemy public float startWait; // how long to wait before initially spawning // seven spawning possibilities in semi-circle around player private Vector3[] spawnPossibilities = new Vector3[3]; private Vector3 spawnPosition; // location of enemy spawn private float nextSpawn; // what time to spawn next enemy private GameObject enemyClone; // clone of initial enemy private int[] spawnLocations = new int[2]; // Use this for initialization void Start () { // spawn enemies when game starts StartCoroutine (SpawnEnemies ()); } // void SpawnEnemies () { IEnumerator SpawnEnemies () { // start spawning enemies after wait time yield return new WaitForSeconds (startWait); // 3 possible locations for enemy, relative to player spawnPossibilities[0] = new Vector3(-5,0,8); spawnPossibilities[1] = new Vector3(5,0,8); spawnPossibilities[2] = new Vector3(0,0,8); while(true){ // get player position Vector3 playerPosition = GameObject.FindGameObjectWithTag ("Player").transform.position; // get random value in spawn possibilities int rand = Random.Range (0, 3); if (rand == spawnLocations [0] && rand == spawnLocations [1]) while (rand == spawnLocations [0]) rand = Random.Range (0, 3); spawnLocations [0] = spawnLocations [1]; spawnLocations [1] = rand; spawnPosition = playerPosition + spawnPossibilities [rand]; // set rotation of enemy Quaternion spawnRotation = Quaternion.identity; spawnRotation.y = 180; // spawn enemy! GameObject clone = Instantiate (enemy, spawnPosition, spawnRotation); clone.SetActive (true); Debug.Log ("enemy spawned!!"); // set time for next spawn // only spawn enemy after specified time interval yield return new WaitForSeconds (spawnRate); } } } // // array to keep previous spawn locations // private int[] spawnLocations = new int[2]; // // filter randomness; no number can be repeated 3 times in a row // if (spawnLocations [0] == rand && spawnLocations [1] == rand) { // while(rand == spawnLocations[0]) // rand = Random.Range (0, 3); // } // spawnLocations [0] = spawnLocations [1]; // spawnLocations [1] = rand;
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Collections.Generic; #endregion namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { /// ----------------------------------------------------------------------------- /// <summary> /// InstallConfig - A class that represents DotNetNuke.Install.Config XML configuration file /// TODO This class may not capture all the details from the config file /// </summary> /// ----------------------------------------------------------------------------- public class InstallConfig { public IList<string> Scripts { get; set; } public string Version { get; set; } public string InstallCulture { get; set; } public SuperUserConfig SuperUser { get; set; } public ConnectionConfig Connection { get; set; } public LicenseConfig License { get; set; } public IList<PortalConfig> Portals { get; set; } public IList<HostSettingConfig> Settings { get; set; } public string FolderMappingsSettings { get; set; } public bool SupportLocalization { get; set; } public InstallConfig() { Portals = new List<PortalConfig>(); Scripts = new List<string>(); Settings = new List<HostSettingConfig>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Core.EF; //'using Core.Models; using Microsoft.AspNetCore.Mvc; namespace Core.Controllers { //public class HomeController : Controller public class ContentNegotiationController : Controller { private IEmployeeRepository _emp; public ContentNegotiationController(IEmployeeRepository employeeRepository) { _emp = employeeRepository; } //JSON result public JsonResult Emp() { return Json(_emp.GetEmployee(1)); } //JSON result public JsonResult JSON() { return Json(new { ID = 1, Name = "Selvan" }); } //Dynamic result public ObjectResult JSONorXML() { return new ObjectResult(new { ID = 1, Desc = "ObjectResult" }); } //Dynamic result public ViewResult ReturnView() { return View(); } public ObjectResult Index() { return new ObjectResult(_emp.GetEmployee(2)); //return new ObjectResult(new { ID = 1, Desc = "ObjectResult" }); } } }
using System; class MainClass { static void Main() { //Generate sample points Point3D pointA = new Point3D(1, 1, 1); Point3D pointB = new Point3D(2, 2, 2); ////Print points info and distance Console.WriteLine("Point A has coordinates {0}", pointA.ToString()); Console.WriteLine("Point B has coordinates {0}", pointB.ToString()); Console.WriteLine("The distance between point A and point B is {0:F4}", Distance.CalculateDistanceIn3D(pointA, pointB)); Console.WriteLine(); //Generate sample path and add a few points Path pathA = new Path(pointA, pointB); pathA.Add(new Point3D(3, 3, 3)); pathA.Add(new Point3D(3, 3, 3)); pathA.Add(new Point3D(5, 5, 5)); //Test path methods pathA.Remove(pointB); pathA.RemoveAt(2); //Point B and one of the points with coordinates (3,3,3) must be gone Console.WriteLine("PathA"); pathA.ListPoints(); //Saving path PathStorage.SavePath(pathA); Console.WriteLine(); //Loading path Console.WriteLine("Default save file is \"save.txt\""); Console.Write("Insert file path to save file: "); string filePath = Console.ReadLine(); Path pathB = PathStorage.LoadPath(filePath); //Checking pathB - must be the same as pathA Console.WriteLine(); Console.WriteLine("PathB"); pathB.ListPoints(); } }
using HangoutsDbLibrary.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.ViewModels; namespace WebAPI.Mappers { public interface IPlanMapper { Plan FromPlanViewModelToPlan(PlanViewModel planViewModel); PlanViewModel FromPlanToPlanViewModel(Plan plan); } }
namespace IronMan.Core { public interface IMissile { } }
using System.Collections.Generic; using System.Linq; using System.Windows.Media; using WMagic.Brush.Basic; namespace WMagic.Brush.Shape { public class GPoly : AShape { #region 变量 // 粗细 private int thick; // 颜色 private Color color; // 填充 private Color stuff; // 样式 private GLinear style; // 路径 private List<GPoint> route; #endregion #region 属性方法 public int Thick { get { return this.thick; } set { this.thick = value; } } public Color Color { get { return this.color; } set { this.color = value; } } public Color Stuff { get { return this.stuff; } set { this.stuff = value; } } public GLinear Style { get { return this.style; } set { this.style = value; } } public List<GPoint> Route { get { return this.route; } set { this.route = value; } } #endregion #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="graph">图元画板</param> public GPoly(MagicGraphic graph) : base(graph, new DrawingVisual()) { this.thick = 1; this.color = Colors.Red; this.style = GLinear.SOLID; this.stuff = Colors.Transparent; this.route = new List<GPoint>(); } #endregion #region 函数方法 /// <summary> /// 多边形渲染 /// </summary> protected sealed override void Render() { int count = !MatchUtils.IsEmpty(this.route) ? this.route.Distinct(new GPoint.Comparer()).Count() : 0; if (count < 2) { this.Earse(); } else { // 配置画笔 Pen pen = this.InitPen(this.style, this.color, this.thick); if (pen != null) { // 配置填充 SolidColorBrush fill = this.InitStuff(this.stuff); if (fill != null) { // 配置多边形 Geometry geom = count.Equals(2) ? ( (new GParse()).M(this.route[0]).L(this.route.Skip(1).ToArray()).P() ) : ( (new GParse()).M(this.route[0]).L(this.route.Skip(1).ToArray()).Z().P() ); if (geom != null) { // 绘制图形 using (DrawingContext dc = this.Brush.RenderOpen()) { if (!this.Matte) { dc.DrawGeometry(fill, pen, geom); } } } } } } } #endregion } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_AnimationPlayMode : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.AnimationPlayMode"); LuaObject.addMember(l, 0, "Stop"); LuaObject.addMember(l, 1, "Queue"); LuaObject.addMember(l, 2, "Mix"); LuaDLL.lua_pop(l, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SolidPrinciples.SRP { class PrintSalary { public void PrintSal(double amount) { Console.WriteLine("Salary: " + amount); } } }
using UnityEngine; using System.Collections; using System; namespace xy3d.tstd.lib.assetManager{ public class MusicPlay{ private static MusicPlay _Instance; public static MusicPlay Instance{ get{ if(_Instance == null){ _Instance = new MusicPlay(); } return _Instance; } } private GameObject musicPlayer; private AudioSource audioSource; public MusicPlay(){ musicPlayer = new GameObject(); musicPlayer.name = "MusicPlayer"; audioSource = musicPlayer.AddComponent<AudioSource>(); audioSource.mute = true; } public void Play(string _path,bool _loop){ Action<AudioClip> callBack = delegate(AudioClip obj) { GetClip(obj,_loop); }; AssetManager.Instance.GetAsset<AudioClip>(_path,callBack); } private void GetClip(AudioClip _clip,bool _loop){ audioSource.clip = _clip; audioSource.loop = _loop; audioSource.Play(); } } }
using System; using Com.Spotify.Sdk.Android.Player; namespace Liddup.Droid { internal class OperationCallbackDelegate : Java.Lang.Object, IPlayerOperationCallback { private readonly Action _onSuccess; private readonly Action<Error> _onError; public OperationCallbackDelegate(Action onSuccess, Action<Error> onError) { _onSuccess = onSuccess; _onError = onError; } public void OnError(Error error) { _onError(error); } public void OnSuccess() { _onSuccess(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayAudioTrack : MonoBehaviour { private AudioManager audioManager; public int newTrackID; public bool playOnStart; private void Start() { audioManager = FindObjectOfType<AudioManager>(); if (playOnStart) { audioManager.PlayNewTrack(newTrackID); } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using AgentStoryComponents; using AgentStoryComponents.core; namespace AgentStoryHTTP.screens { public partial class login : LoginBase { public string PageTitle { get { return config.Orginization + " - login"; } } public string ClubName { get { return config.logoText; } } protected void Page_Load(object sender, EventArgs e) { string msg = Request.QueryString["msg"]; //pass login to base try { base.Page_Load(sender, e, this.divToolBarAttachPoint, this.divFooter); } catch (Exception exp) { msg += exp.Message; } var m = string.Empty; m += config.defaultLoginMessage; if (msg != null && msg.Trim().Length > 0) { m += string.Format("<div style='color:red;font-size:10;font-weight:bolder;'>{0}</div>", msg); Response.Write("<div class='clsLoginMsg'>" + m + "</div>"); } else { Response.Write("<div class='clsLoginMsg'>" + config.defaultLoginMessage + "</div>"); } } } }
using AutoMapper; using ImmedisHCM.Data.Entities; using ImmedisHCM.Services.Models.Core; namespace ImmedisHCM.Services.Mapping { public class EmployeeMapping : Profile { public EmployeeMapping() { CreateMap<Employee, EmployeeServiceModel>() //.ForPath(x => x.Manager.Manager, opts => opts.Ignore()) //.ForPath(x => x.Department.Manager, opts => opts.Ignore()) .ReverseMap(); } } }
namespace SharpPcap.Util { public class IPSubnet : IPAddressRange { virtual public System.String NetworkAddress { get { return IPUtil.IpToString(getNetwork(net, mask)); } } virtual public System.String BroadcastAddress { get { return IPUtil.IpToString(getBroadcast(net, mask)); } } protected internal long net; protected internal long mask; private static long getBroadcast(long net, long mask) { long m = ~mask; m = m & 0xFFFFFFFFL; return net | m; } private static long getNetwork(long net, long mask) { return net & mask; } public IPSubnet(long net, int maskBits) : this(net, IPUtil.MaskToLong(maskBits)) { } public IPSubnet(System.String net, int maskBits) : this(IPUtil.IpToLong(net), IPUtil.MaskToLong(maskBits)) { } public IPSubnet(System.String dottedNet, System.String dottedMask) : this(IPUtil.IpToLong(dottedNet), IPUtil.MaskToLong(dottedMask)) { } public IPSubnet(System.String ipAndMaskBits) : this(IPUtil.ExtractIp(ipAndMaskBits), IPUtil.ExtractMaskBits(ipAndMaskBits)) { } public IPSubnet(long net, long mask) : this(getNetwork(net, mask) + 1, getBroadcast(net, mask) - 1, true, getNetwork(net, mask), getBroadcast(net, mask)) { this.net = net; this.mask = mask; } private IPSubnet(long min, long max, bool isRandom, long totalMin, long totalMax) : base(min, max, isRandom, totalMin, totalMax) { } public virtual void includeBroadcastAddress(bool shouldInclude) { if (shouldInclude) { base.Max = getBroadcast(net, mask); } else { base.Max = getBroadcast(net, mask) + 1; } } public virtual void includeNetworkAddress(bool shouldInclude) { if (shouldInclude) { base.Min = getNetwork(net, mask); } else { base.Min = getNetwork(net, mask) - 1; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task2Console { public class Book : IComparable<Book> { public int Year { get; } public string Title { get; } public Book(string title, int year) { Title = title; Year = year; } public int CompareTo(Book other) { return String.CompareOrdinal(Title, other.Title); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Video; public class VideoPopup : MonoBehaviour { private VideoPlayer videoPlayerSc; private string videoURL = ""; private bool bPlay = false; // Start is called before the first frame update void Start() { videoPlayerSc = this.transform.GetComponent<VideoPlayer>(); videoPlayerSc.targetCamera = FindObjectOfType<Camera>(); } // Update is called once per frame void Update() { if(true == videoPlayerSc.isPlaying) { bPlay = true; Debug.Log("state: " + videoPlayerSc.isPlaying); } if(true == bPlay) { if (false == videoPlayerSc.isPlaying) { videoPlayerSc.Stop(); Debug.Log("state: " + videoPlayerSc.isPlaying); } } } public void VideoPlayButtonEvent() // button event... { StartCoroutine(PlayVideoPlayer()); } IEnumerator PlayVideoPlayer() { WaitForSeconds waitTime = new WaitForSeconds(0.1f); //videoPlayerSc.url = videoURL; while (!videoPlayerSc.isPrepared) { yield return waitTime; break; } videoPlayerSc.Play(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Samples { class Program { static void Main(string[] args) { //BookPost bp = new BookPost(); //bp.Perform(); PostCallback pcb = new PostCallback(); pcb.Perform(); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.Services.FileSystem.Internal { public interface IDirectory { void Delete(string path, bool recursive); bool Exists(string path); string[] GetDirectories(string path); string[] GetFiles(string path); void Move(string sourceDirName, string destDirName); void CreateDirectory(string path); } }
using ConsumirAPI.DTO; using ConsumirAPI.Interface; using Newtonsoft.Json; using System; using System.Configuration; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ConsumirAPI.Service { public class PessoaService : IPessoaService { private readonly PessoaService _pessoaService; private string appSettingsUrlApi; public PessoaService() { appSettingsUrlApi = ConfigurationSettings.AppSettings["UrlApi"]; } public async Task<string> GetURI() { var response = string.Empty; var u = new Uri($"{appSettingsUrlApi}API/values/GetGenerico"); using (var client = new HttpClient()) { HttpResponseMessage result = await client.GetAsync(u); if (result.IsSuccessStatusCode) { response = await result.Content.ReadAsStringAsync(); } } return response; } public async Task<string> PostURI(PessoaDTO obj) { var response = string.Empty; Uri u = new Uri($"{appSettingsUrlApi}API/values"); HttpContent c = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { HttpResponseMessage result = await client.PostAsync(u, c); if (result.IsSuccessStatusCode) { response = result.StatusCode.ToString(); } } return response; } } }
using UnityEngine; using System.Collections; public class CarController : MonoBehaviour { public WheelCollider[] wheels; public float enginePower; public float steeringAngle; void Start () { } // Update is called once per frame void FixedUpdate () { //wheels 0 and 1 is front, wheels 2 and 3 is rear wheels [2].motorTorque = Input.GetAxis ("Vertical") * enginePower; wheels [3].motorTorque = Input.GetAxis ("Vertical") * enginePower; wheels [0].steerAngle = Input.GetAxis ("Horizontal") * steeringAngle; wheels [1].steerAngle = Input.GetAxis ("Horizontal") * steeringAngle; } }
namespace ns20 { using System; internal enum Enum18 { None, Success, Overflow, Invalid } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace Journal { public partial class EncyclopediaArcanaView : ContentPage { public EncyclopediaArcanaView() { InitializeComponent(); BindingContext = new EncyclopediaArcanaViewModel(); } } }
using Autofac; using MVC.Samples.BLL.Interfaces.Guru; using MVC.Samples.BLL.Services.Guru; namespace MVC.Samples.Web.Areas.Guru { public static class GuruDataManager { public static void AddDepandancies(ContainerBuilder builder) { builder.RegisterType<RegistrationService>().As(typeof(IRegistration)).InstancePerRequest(); } } }
using System; using Prism.Commands; using Prism.Navigation; using fictionalbroccoli.Services; using fictionalbroccoli.Models; using Xamarin.Forms; using Plugin.Media.Abstractions; using System.Diagnostics; namespace fictionalbroccoli.ViewModels { public class BrocoRegisterAddViewModel : ViewModelBase { public INavigationService _navigationService; public IRegisterService _registerService; public IPictureService _pictureService; public IMapService _mapService; public IDialogService _dialogService; public string _name; public string Name { get { return _name; } set { SetProperty(ref _name, value); } } public string _description; public string Description { get { return _description; } set { SetProperty(ref _description, value); } } public string _tag; public string Tag { get { return _tag; } set { SetProperty(ref _tag, value); } } public Registration _registration; public Registration Registration { get { return _registration; } set { SetProperty(ref _registration, value); } } public DelegateCommand CommandAdd { get; private set; } public DelegateCommand CommandTakePicture { get; private set; } public ImageSource _imageSrc; public ImageSource ImageSrc { get { return _imageSrc; } set { SetProperty(ref _imageSrc, value); } } public BrocoRegisterAddViewModel( INavigationService navigationService, IRegisterService registerService, IPictureService pictureService, IMapService mapService, IDialogService dialogService) : base(navigationService) { Title = "Nouveau"; _registerService = registerService; _navigationService = navigationService; _pictureService = pictureService; _mapService = mapService; _dialogService = dialogService; CommandAdd = new DelegateCommand(HandleAdd, CanHandleAdd) .ObservesProperty(() => Name) .ObservesProperty(() => Description) .ObservesProperty(() => Tag); CommandTakePicture = new DelegateCommand(HandleTakePicture); Registration = new Registration(); } private void HandleAdd() { _dialogService.ShowMessage("Attention", "Êtes-vous sûr de vouloir ajouter cet item ?", async (res) => { if (res) { await _mapService.RequestLocationPermission(); Registration.Name = Name; Registration.Description = Description; Registration.Tag = Tag; Registration.Date = DateTime.Now; var position = await _mapService.GetCurrentLocation(); Registration.Latitude = position.Latitude; Registration.Longitude = position.Longitude; var address = await _mapService.GetCurrentAddress(position); Debug.WriteLine(address); Registration.Address = address; _registerService.Add(Registration); await _navigationService.NavigateAsync("/AppliMenu/NavigationPage/BrocoRegister"); } }); } private Boolean CanHandleAdd() { Debug.WriteLine(string.IsNullOrEmpty(Name)); return !string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Description) && !string.IsNullOrEmpty(Tag); } private async void HandleTakePicture() { MediaFile file = await _pictureService.PickOrTakePhotoAsync(); ImageSrc = ImageSource.FromStream(file.GetStream); Registration.ImagePath = file.Path; } } }
using System; using System.ComponentModel.DataAnnotations; namespace starkdev.spreadrecon.model { public class ImportacaoPlanilha { [Display(Name = "Cód.")] public long id { get; set; } [Required(ErrorMessage = "Tipo da planilha da importação é obrigatório")] public long idTipoPlanilha { get; set; } [Required(ErrorMessage = "Usuário da importação é obrigatório")] public long idUsuarioImportacao { get; set; } [Display(Name = "Início")] [Required(ErrorMessage = "Data/hora início do processamento da importação é obrigatório")] public DateTime dataInicioProcessamento { get; set; } [Display(Name = "Fim")] public DateTime? dataFimProcessamento { get; set; } [Required(ErrorMessage = "Status da importação é obrigatório")] public long idStatus { get; set; } [Display(Name = "Sucesso")] public int qtdImportacaoSucesso { get; set; } [Display(Name = "Erros")] public int qtdImportacaoIgnorada { get; set; } [Required(ErrorMessage = "Loja da importação é obrigatório")] public long idLoja { get; set; } [Display(Name = "Arquivo")] public string nomeArquivoOriginal { get; set; } public string nomeArquivoProcessado { get; set; } public string nomeArquivoErro { get; set; } #region relacionamentos public TipoPlanilha tipoPlanilha { get; set; } public Usuario usuarioImportacao { get; set; } public Loja loja { get; set; } public Status status { get; set; } #endregion #region Campos Auxiliares public string _diretorioPendente { get; set; } public string _diretorioProcessado { get; set; } public string _diretorioLog { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NewsPortalLogic; namespace NewsPortal.Controllers { public class NewsController : Controller { private NewsManager _news; public NewsController(NewsManager newsManager) { _news = newsManager; } public IActionResult Index(int id) { var single = _news.Get(id); return View(single); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class Calculator { public int Add(string number1, string number2) { return Convert.ToInt32(number1+number2); } } }
using System; using System.Collections.Generic; using System.Text; namespace Peppy.AutoIoc { public enum LifeCycle { Scoped = 0x1, Singleton = 0x2, Transient = 0x3, } }
using System; using HW2; namespace Task_1._2 { class Program { static void Main(string[] args) { Account[] accounts = new Account[1000000]; for (int i = 0; i < accounts.Length; i++) { accounts[i] = new Account("UAH"); } foreach (var item in accounts) { Console.WriteLine(item.id); } GetSortedAccounts(accounts); Console.WriteLine("First 10 accounts are:"); for (int i = 0; i < 10; i++) { Console.WriteLine(accounts[i].id); } Console.WriteLine("Last 10 accounts are:"); for (int i = accounts.Length - 11; i < accounts.Length; i++) { Console.WriteLine(accounts[i].id); } } public static void GetSortedAccounts(Account[] accounts) { bool isSorted = false; Account temp; while (isSorted == false) { isSorted = true; for (int i = accounts.Length - 1; i > 0; i--) { if (accounts[i].id < accounts[i - 1].id) { temp = accounts[i]; accounts[i] = accounts[i - 1]; accounts[i - 1] = temp; isSorted = false; } } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyAI : MonoBehaviour { [SerializeField] private float _speed = 3.0f; [SerializeField] private int _health = 3; [SerializeField] private GameObject _enemyExplosionPrefab; private UIManager _uiManager; //[SerializeField] //private AudioClip _clipDestroy; //private Animator _enemyAnimations; void Start () { _speed = 3.0f; _health = 3; //_enemyAnimations = GetComponent<Animator>(); _uiManager = GameObject.Find("Canvas").GetComponent<UIManager>(); transform.position = new Vector3(Random.Range(8.12f, -8.12f), 6.0f, 0); } void Update () { transform.Translate(Vector3.down * Time.deltaTime * _speed); if (transform.position.y < -6.0f) { //float randomX = Random.Range(8.12f, -8.12f); transform.position = new Vector3(Random.Range(8.12f, -8.12f), 6.0f, 0); } } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Laser") { Destroy(other.gameObject); this._health -= 1; if (_health < 1) { Instantiate(_enemyExplosionPrefab, transform.position, Quaternion.identity); //_enemyAnimations.SetInteger("State", 1); _uiManager.UpdateScore(3); //AudioSource.PlayClipAtPoint(_clipDestroy, Camera.main.transform.position); Destroy(this.gameObject); } } else if (other.tag == "Player") { Player player = other.GetComponent<Player>(); if (player != null) { player.Damage(_health); } Instantiate(_enemyExplosionPrefab, transform.position, Quaternion.identity); //_enemyAnimations.SetInteger("State", 1); _uiManager.UpdateScore(3); //AudioSource.PlayClipAtPoint(_clipDestroy, Camera.main.transform.position); Destroy(this.gameObject); } } }
using System; using System.Globalization; using Gerenciamento_Conta_Bancaria.Entitites; using Gerenciamento_Conta_Bancaria.Entitites.Exceptions; namespace Gerenciamento_Conta_Bancaria { class Program { static void Main(string[] args) { Conta conta = new Conta(); Console.WriteLine("Entre com os dados da Conta"); Console.Write("Número da conta : "); int numero = int.Parse(Console.ReadLine()); Console.Write("Nome do titular da conta : "); string titular = Console.ReadLine(); Console.Write("Digite o deposito inicial : "); double deposito = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); conta.Depositar(deposito); Console.Write("Limite máximo de saque : "); double limite_Saque = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); conta = new Conta(numero, titular, limite_Saque, deposito); Console.WriteLine(); Console.WriteLine(); Console.Write("Entre com o valor que deseja sacar : "); double saque = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); try { conta.Sacar(saque); Console.WriteLine(conta); } catch (Domain_Exception e) { Console.WriteLine("Erro no saque : "+e.Message); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class NewPausedMenu : MonoBehaviour { public GameObject pausedUI; private bool isPaused; public Slider Volume; public GameObject inventory; public GameObject helpMenu; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { inventory.SetActive(false); helpMenu.SetActive(false); isPaused = !isPaused; } if (isPaused) { Time.timeScale = 0; ActivateMenu(); } else { Time.timeScale = 1f; DeactiveMenu(); } AkSoundEngine.SetRTPCValue("Master_Volume_Control", Volume.value * 100); Debug.Log("currentvolume" + Volume.value); if (Input.GetKeyDown(KeyCode.T)) { if (inventory.activeSelf == true) { inventory.SetActive(false); } else { inventory.SetActive(true); } } if(Input.GetKeyDown(KeyCode.P)) { if (helpMenu.activeSelf == true) { helpMenu.SetActive(false); } else { helpMenu.SetActive(true); } } } public void ActivateMenu() { pausedUI.SetActive(true); } public void DeactiveMenu() { pausedUI.SetActive(false); isPaused = false; } }
using System; using System.Collections.Generic; using System.Text; namespace FXBLOOM.SharedKernel { public static class Utility { public static readonly int DefaultPageSize = 20; public static readonly int DefaultPageNumber = 1; public static readonly int MaxPageSize = 100; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tasks.Services.Domain.Results; namespace Tasks.Services.Domain { public interface IUserService { Task<CreateUserResult> CreateAsync(string email, string password); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using VasilyWebDemo.Entity; using Microsoft.AspNetCore.Mvc; using Vasily.Driver; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace VasilyWebDemo.Controllers { /// <summary> /// 广告类型路由 /// </summary> [Route("api/[controller]")] public class TypeController :VasilyController<AdType> { /// <summary> /// 构造函数 /// </summary> public TypeController():base("AdSql") { } /// <summary> /// 获取整个类型集合 /// </summary> /// <returns>实例集合</returns> [HttpGet("get_all")] public ReturnResult Get() { return Result(SqlHandler.Get()); } /// <summary> /// 根据主键Id获取类型实例 /// </summary> /// <param name="id">主键id</param> /// <returns>分类实例</returns> [HttpGet("get/{id}")] public ReturnResult Get(int id) { return Result(SqlHandler.GetByPrimaryKey(new { tid = id })); } /// <summary> /// 增加一个分类实例 /// </summary> /// <param name="value">分类实例表单</param> [HttpPost("add")] public ReturnResult Add([FromBody]AdType value) { //校验模型 if (ModelState.IsValid) { return Result(SqlHandler.Add(value)); } else { return Result(); } } /// <summary> /// 根据主键id删除一个分类实例 /// </summary> /// <param name="id">主键id</param> [HttpGet("delete/{id}")] public ReturnResult Delete(int id) { return Result(SqlHandler.Delete(new { tid = id })); } /// <summary> /// 修改一个分类实例 /// </summary> /// <param name="value">分类实例表单</param> [HttpPost("modify")] public ReturnResult Modeify([FromBody]AdType value) { if (ModelState.IsValid) { return Result(SqlHandler.Modify(value)); } else { return Result(); } } /* // <summary> /// 根据gid查询一组广告 /// </summary> /// <param name="id">广告位id</param> /// <returns>广告集合</returns> [HttpGet("get_gid/{id}")] public ReturnResult GetGid(int id) { return Result(SqlHandler.GetCache("GetByGid", new { gid = id })); } /// <summary> /// 通过标题进行模糊查询 /// </summary> /// <param name="key">关键字</param> /// <returns>广告集合</returns> [HttpGet("get_subject/{key}")] public ReturnResult GetSubject(string key) { return Result(SqlHandler.GetCache("fuzzyQuery", new { subject = key })); } */ } }
using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; namespace Koek { public static class ExtensionsForPipe { public static async Task CopyToUntilCanceledOrCompletedAsync(this PipeReader reader, PipeWriter writer, CancellationToken cancel) { using var cancelRegistration = cancel.Register(delegate { // If we get canceled, indicate operation cancellation on both pipes to break out of the loop. // The purpose of this here is to avoid throwing exceptions for cancellation, instead using the graceful signal. // Just because exceptions cost extra CPU time that we want to avoid when handling load spikes (such as mass disconnects). reader.CancelPendingRead(); writer.CancelPendingFlush(); }); // We copy until we encounter either a read cancellation (upstream reached end of stream) or a write // completion (downstream reached end of stream) or a write cancellation (downstream requested graceful stop). while (true) { var readResult = await reader.ReadAsync(CancellationToken.None); if (readResult.IsCanceled) break; try { if (!readResult.Buffer.IsEmpty) { foreach (var segment in readResult.Buffer) { var memory = writer.GetMemory(segment.Length); segment.CopyTo(memory); writer.Advance(segment.Length); } var flushResult = await writer.FlushAsync(CancellationToken.None); if (flushResult.IsCanceled || flushResult.IsCompleted) break; } if (readResult.IsCompleted) break; } finally { reader.AdvanceTo(readResult.Buffer.End); } } } public static void CancelPendingFlushEvenIfClosed(this PipeWriter writer) { // CancelPendingFlush() will throw if the pipe is already closed. // This behavior is not useful to us, so eat the exception. try { writer.CancelPendingFlush(); } catch { } } public static void CancelPendingReadEvenIfClosed(this PipeReader reader) { // CancelPendingRead() will throw if the pipe is already closed. // This behavior is not useful to us, so eat the exception. try { reader.CancelPendingRead(); } catch { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PDTech.OA.Model { /// <summary> /// 在线考试 /// </summary> public class TestOnline { /// <summary> /// 试卷名称 /// </summary> public string TestName { get; set; } /// <summary> /// 试题总数 /// </summary> public decimal TestCount { get; set; } /// <summary> /// 试卷总分 /// </summary> public decimal TestScore { get; set; } /// <summary> /// 试卷题目列表 /// </summary> public List<Question> QuestionCollection { get; set; } /// <summary> /// 作答时间 /// </summary> public DateTime? ReplyTime { get; set; } } /// <summary> /// 试题 /// </summary> public class Question { /// <summary> /// 试题ID /// </summary> public string QuestionID { get; set; } /// <summary> /// 题目 /// </summary> public string Title { get; set; } /// <summary> /// 选项A /// </summary> public string OptionA { get; set; } /// <summary> /// 选项B /// </summary> public string OptionB { get; set; } /// <summary> /// 选项C /// </summary> public string OptionC { get; set; } /// <summary> /// 选项D /// </summary> public string OptionD { get; set; } /// <summary> /// 正确答案 /// </summary> public string CorrectResult { get; set; } /// <summary> /// 分值 /// </summary> public decimal QuestionValue { get; set; } /// <summary> /// 选择的答案 /// </summary> public string SelectValue { get; set; } /// <summary> /// 得分 /// </summary> public decimal Score { get; set; } } }
using Everest.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace Everest.Repository.Interfaces { public interface IImagenRepository { Task<List<ImagenEntity>> ConsultarPorAnuncioAsync(int id); Task<ImagenEntity> ConsultarAsync(int id); Task<int> CrearImagenAsync(ImagenEntity entity); Task<bool> EliminarImagenAsync(int id); } }
using Microsoft.AspNetCore.Mvc.ModelBinding; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestApplicationDomain.DynamicQuery; namespace TestApplication { public class DataDescriptorModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); if (!bindingContext.HttpContext.Request.Headers.TryGetValue("x-descriptor", out var header)) { bindingContext.Result = ModelBindingResult.Failed(); return Task.CompletedTask; } bindingContext.Result = ModelBindingResult.Success(JsonConvert.DeserializeObject<DataDescriptor>(header.ToString())); return Task.CompletedTask; } } public class ModelBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context.Metadata.ModelType == typeof(DataDescriptor)) return new DataDescriptorModelBinder(); return null; } } }
/* .-' '--./ / _.---. '-, (__..-` \ \ . | `,.__. ,__.--/ '._/_.'___.-` FREE WILLY */ using System; using System.Timers; namespace Automatisation.Model { public class Attenuator : BaseModel { #region fields private bool _isPowered = false; private string _label = "No device"; private uint _devID = 0; private int _serialNumber = 0; private string _model; private int _deviceStatus; private int _attenuation = 0; private int _attenuationStep = 2; private int _attenuationMin; private double _attenuationMinDB; private int _attenuationMax; private double _attenuationMaxDB; private int _rampStart = 0; private int _rampEnd = 0; private int _dwellTime = 1000; private int _idleTime = 0; private bool _rf_on = true; private bool _isRampModeRepeat = false; private bool _isRampDirectionUp = true; private Timer _tmrRefreshAttenuation; #endregion fields #region properties /// <summary> /// Set to true if the device has been found /// </summary> public bool IsEnabled { get { return _isPowered; } set { if (value != _isPowered) { _isPowered = value; OnPropertyChanged("IsEnabled"); } } } /// <summary> /// Labeled according to label numbers on the device for easy recognition /// </summary> public string Label { get { return _label; } set { if (value != _label) { _label = value; OnPropertyChanged("Label"); } } } /// <summary> /// Device number being used for every command /// </summary> public uint DeviceNumber { get { return _devID; } set { if (value != _devID) { _devID = value; OnPropertyChanged("DeviceNumber"); } } } public int SerialNumber { get { return _serialNumber; } set { if (value != _serialNumber) { _serialNumber = value; OnPropertyChanged("SerialNumber"); } } } public string Model { get { return _model; } set { if (value != _model) { _model = value; OnPropertyChanged("Model"); } } } /// <summary> /// Used to store flags /// </summary> public int DeviceStatus { get { return _deviceStatus; } set { if (value != _deviceStatus) { _deviceStatus = value; OnPropertyChanged("DeviceStatus"); } } } /// <summary> /// Attenuation in db (0.25 * value retrieved from attenuator) /// </summary> public double Attenuation { get { return _attenuation * 0.25; } set { if ((int)value * 4 != _attenuation) { if (CheckMinMaxDB((int)value * 4)) { _attenuation = (int)value * 4; Libs.VNX_Atten.SetAttenuation(_devID, _attenuation); OnPropertyChanged("Attenuation"); } } } } /// <summary> /// AttenuationStep in db (0.25 * value retrieved from attenuator) /// </summary> public double AttenuationStep { get { return _attenuationStep * 0.25; } set { if ((int)value * 4 != _attenuationStep) { _attenuationStep = (int)(value * 4); Libs.VNX_Atten.SetAttenuationStep(_devID,_attenuationStep); OnPropertyChanged("AttenuationStep"); } } } /// <summary> /// Every attenuator series has a minimum dB value, being 0 for our devices. /// </summary> public int AttenuationMin { get { return _attenuationMin; } set { if (value != _attenuationMin) { _attenuationMin = value; AttenuationMinDB = value * 0.25; OnPropertyChanged("AttenuationMin"); } } } public double AttenuationMinDB { get { return _attenuationMinDB; } set { if (value != _attenuationMinDB) { _attenuationMinDB = value; OnPropertyChanged("AttenuationMinDB"); } } } /// <summary> /// Every attenuator series has a maximum dB value, being 63 for our devices. /// </summary> public int AttenuationMax { get { return _attenuationMax; } set { if (value != _attenuationMax) { _attenuationMax = value; AttenuationMaxDB = value * 0.25; OnPropertyChanged("AttenuationMax"); } } } public double AttenuationMaxDB { get { return _attenuationMaxDB; } set { if (value != _attenuationMaxDB) { _attenuationMaxDB = value; OnPropertyChanged("AttenuationMaxDB"); } } } public double RampStart { get { return _rampStart * 0.25; } set { if ((int)value * 4 != _rampStart) { if (CheckMinMaxDB((int) value*4)) { _rampStart = (int)value * 4; IsSweepUp(); Libs.VNX_Atten.SetRampStart(_devID, _rampStart); OnPropertyChanged("RampStart"); } } } } /// <summary> /// RampEnd in db (0.25 * value retrieved from attenuator) /// </summary> public double RampEnd { get { return _rampEnd * 0.25; } set { if ((int)value * 4 != _rampEnd) { if (CheckMinMaxDB((int) value*4)) { _rampEnd = (int)value * 4; IsSweepUp(); Libs.VNX_Atten.SetRampEnd(_devID, _rampEnd); OnPropertyChanged("RampEnd"); } } } } /// <summary> /// DwellTime in ms /// </summary> public int DwellTime { get { return _dwellTime; } set { if (value != _dwellTime) { _dwellTime = value; Libs.VNX_Atten.SetDwellTime(_devID, _dwellTime); OnPropertyChanged("DwellTime"); } } } /// <summary> /// IdleTime in ms /// </summary> public int IdleTime { get { return _idleTime; } set { if (value != _idleTime) { _idleTime = value; Libs.VNX_Atten.SetIdleTime(_devID, _idleTime); OnPropertyChanged("IdleTime"); } } } public bool IsRFOn { get { return _rf_on; } set { if (value != _rf_on) { _rf_on = value; Libs.VNX_Atten.SetRFOn(_devID, _rf_on); OnPropertyChanged("IsRFOn"); } } } /// <summary> /// Set to off to complete the sweep once. To true to do another sweep after IdleTime has passed. /// </summary> public bool IsRampModeRepeat { get { return _isRampModeRepeat; } set { if (value != _isRampModeRepeat) { _isRampModeRepeat = value; Libs.VNX_Atten.SetRampMode(_devID, _isRampModeRepeat); OnPropertyChanged("IsRampMode"); } } } /// <summary> /// Checks if ramp should add or substract attenuationStep. Set up to true when rampEnd > start /// </summary> public bool IsRampDirectionUp { get { return _isRampDirectionUp; } set { if (value != _isRampDirectionUp) { _isRampDirectionUp = value; Libs.VNX_Atten.SetRampMode(_devID, _isRampDirectionUp); OnPropertyChanged("IsRampDirectionUp"); } } } #endregion properties #region constructor public Attenuator(uint devid) { this.DeviceNumber = devid; GetSettings(); _tmrRefreshAttenuation = new Timer(); _tmrRefreshAttenuation.Elapsed += _tmrRefreshAttenuation_Elapsed; } public Attenuator(uint devid, int serialnumber) { this.DeviceNumber = devid; this.SerialNumber = serialnumber; GetSettings(); _tmrRefreshAttenuation = new Timer(); _tmrRefreshAttenuation.Elapsed += _tmrRefreshAttenuation_Elapsed; } #endregion constructor #region events /// <summary> /// Get the new attenuation value after each interval during a sweep/ramp /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _tmrRefreshAttenuation_Elapsed(object sender, ElapsedEventArgs e) { int getAtt = Libs.VNX_Atten.GetAttenuation(_devID); double getAttDouble = getAtt * 0.25; Attenuation = getAttDouble; Console.WriteLine("ticked: _att: " + _label + ":" + _devID + " - " +getAtt + " - " + getAttDouble); } #endregion events public void RefreshAttenuation() { this.Attenuation = Libs.VNX_Atten.GetAttenuation(_devID) * 0.25; } public void GetSettings() { if (_devID != 0) { this.Model = GetModel(); this.SerialNumber = Libs.VNX_Atten.GetSerialNumber(_devID); this.Attenuation = Libs.VNX_Atten.GetAttenuation(_devID)*0.25; this.AttenuationMin = Libs.VNX_Atten.GetMinAttenuation(_devID); this.AttenuationMax = Libs.VNX_Atten.GetMaxAttenuation(_devID); this.AttenuationStep = Libs.VNX_Atten.GetAttenuationStep(_devID)*0.25; this.DwellTime = Libs.VNX_Atten.GetDwellTime(_devID); this.IdleTime = Libs.VNX_Atten.GetIdleTime(_devID); this.RampEnd = Libs.VNX_Atten.GetRampEnd(_devID)*0.25; this.RampStart = Libs.VNX_Atten.GetRampStart(_devID)*0.25; this.IsRFOn = (Libs.VNX_Atten.GetRFOn(_devID) == 1) ? true : false; } } public void ZeroSettings() { if (_devID != 0) { this.IsEnabled = false; //this.Label = "No device"; //this._devID = 0; //this.SerialNumber = 0; //this.Model = "No device"; this.Attenuation = 0; this.AttenuationStep = 2; this.RampStart = 0; this.RampEnd = 0; this.DwellTime = 1000; this.IdleTime = 0; this.IsRampModeRepeat = false; this.IsRFOn = true; } } public void StartConnection() { if (_devID != 0) { Libs.VNX_Atten.InitDevice(_devID); IsEnabled = true; } } public void CloseConnection() { if (_devID != 0) { Libs.VNX_Atten.CloseDevice(_devID); IsEnabled = false; } } public void SaveCurrentSettingsAsDefault() { if (_devID != 0) Libs.VNX_Atten.SaveSettings(_devID); } public string GetModel() { if (_devID != 0) { char[] model = new char[32]; Libs.VNX_Atten.GetModelName(_devID, model); return new string(model); } return "No Device Found"; } private bool CheckMinMaxDB(int val) { if (val < _attenuationMin ) { //Messenger.Default.Send(new NotificationMessage(Messages.Messages.ATT_LTMIN)); return false; } else if (val > _attenuationMax) { //Messenger.Default.Send(new NotificationMessage(Messages.Messages.ATT_GTMAX)); return false; } else { return true; } } private void IsSweepUp() { _isRampDirectionUp = (_rampEnd > _rampStart) ? true : false; Libs.VNX_Atten.SetRampDirection(_devID, _isRampDirectionUp); } /// <summary> /// Start the timer to check if attenuation value has changed during a sweep/ramp /// </summary> /// <param name="interval">in ms</param> public void StartRefreshAttTimer(double interval) { _tmrRefreshAttenuation.Interval = interval; _tmrRefreshAttenuation.Enabled = true; } /// <summary> /// Stop the timer to check if attenuation value has changed during a sweep/ramp /// </summary> public void StopRefreshAttTimer() { _tmrRefreshAttenuation.Enabled = false; } } }
using System; using System.IO; namespace ConsoleApp23 { class Program { static void Sort(int[] a)//сортировка методом пузырька(можно воспользоваться интерфейсом IComparer) { int temp; for (int i = 0; i < a.Length - 1; ++i) { for (int j = a.Length - 1; j > i; --j) { if (a[j] < a[j - 1]) { temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; } } } } static bool Find(int[] a, int key)//функция для поиска, значени для поиска вводится в консоль { bool found = false; int i = 0; while (!found && i < a.Length) { if (a[i] == key) { found = true; } else { ++i; } } if (found) { return true; } else { return false; } } static void Main() { string str = Console.ReadLine(); string[] line = str.Split(" "); int[] number = new int[line.Length]; for (int i = 0; i < line.Length; ++i) { number[i] = int.Parse(line[i]); } Console.Write("Введите значени для поиска: "); int k = int.Parse(Console.ReadLine()); Sort(number); Console.WriteLine("Содержится ли число {0} в массиве: {1}", k, Find(number, k)); Console.WriteLine("Отсортированный миссив:"); foreach (int elem in number) { Console.WriteLine("{0}", elem); } Console.ReadLine(); } } }
//----------------------------------------------------------------------- // <copyright file="TQData.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultAE.Data { using Microsoft.Extensions.Logging; using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.Logs; /// <summary> /// TQData is used to store information about reading and writing the data files in TQ. /// </summary> public class TQDataService : ITQDataService { public const int BEGIN_BLOCK_VALUE = -1340212530; public const int END_BLOCK_VALUE = -559038242; public int BeginBlockValue => BEGIN_BLOCK_VALUE; public int EndBlockValue => END_BLOCK_VALUE; private readonly ILogger Log; internal static readonly Encoding Encoding1252 = Encoding.GetEncoding(1252); internal static readonly Encoding EncodingUnicode = Encoding.Unicode; public TQDataService(ILogger<TQDataService> log) { this.Log = log; } /// <summary> /// Validates that the next string is a certain value and throws an exception if it is not. /// </summary> /// <param name="value">value to be validated</param> /// <param name="reader">BinaryReader instance</param> public void ValidateNextString(string value, BinaryReader reader) { string label = ReadCString(reader); if (!label.ToUpperInvariant().Equals(value.ToUpperInvariant())) { var ex = new ArgumentException(string.Format( CultureInfo.InvariantCulture, "Error reading file at position {2}. Expecting '{0}'. Got '{1}'", value, label, reader.BaseStream.Position - label.Length - 4)); Log.ErrorException(ex); throw ex; } } public bool MatchNextString(string value, BinaryReader reader) { long readerPosition = reader.BaseStream.Position; string label = ReadCString(reader); reader.BaseStream.Position = readerPosition; if (!label.ToUpperInvariant().Equals(value.ToUpperInvariant())) return false; return true; } /// <summary> /// Writes a string along with its length to the file. /// </summary> /// <param name="writer">BinaryWriter instance</param> /// <param name="value">string value to be written.</param> public void WriteCString(BinaryWriter writer, string value) { // Convert the string to ascii // Vorbis' fix for extended characters in the database. Encoding ascii = Encoding.GetEncoding(1252); byte[] rawstring = ascii.GetBytes(value); // Write the 4-byte length of the string writer.Write(rawstring.Length); // now write the string writer.Write(rawstring); } /// <summary> /// Reads a string from the binary stream. /// Expects an integer length value followed by the actual string of the stated length. /// </summary> /// <param name="reader">BinaryReader instance</param> /// <returns>string of data that was read</returns> public string ReadCString(BinaryReader reader) { // first 4 bytes is the string length, followed by the string. int len = reader.ReadInt32(); // Convert the next len bytes into a string // Vorbis' fix for extended characters in the database. Encoding ascii = Encoding.GetEncoding(1252); byte[] rawData = reader.ReadBytes(len); char[] chars = new char[ascii.GetCharCount(rawData, 0, len)]; ascii.GetChars(rawData, 0, len, chars, 0); string ans = new string(chars); return ans; } /// <summary> /// Reads a string from the binary stream. /// Expects an integer length value followed by the actual string of the stated length. /// </summary> /// <param name="reader">BinaryReader instance</param> /// <returns>string of data that was read</returns> public string ReadUTF16String(BinaryReader reader) { // first 4 bytes is the string length, followed by the string. int len = reader.ReadInt32(); len *= 2;// 2 byte chars var rawData = reader.ReadBytes(len); //convert bytes string return (UnicodeEncoding.Unicode.GetString(rawData)); } public (int indexOf, int valueOffset, int nextOffset, byte[] valueAsByteArray, int valueAsInt) WriteIntAfter(byte[] playerFileContent, string keyToLookFor, int newValue, int offset = 0) { var found = ReadIntAfter(playerFileContent, keyToLookFor, offset); if (found.indexOf != -1) { var newValueBytes = BitConverter.GetBytes(newValue); Array.ConstrainedCopy(newValueBytes, 0, playerFileContent, found.valueOffset, sizeof(int)); } return found; } public (int indexOf, int valueOffset, int nextOffset, byte[] valueAsByteArray, float valueAsFloat) WriteFloatAfter(byte[] playerFileContent, string keyToLookFor, float newValue, int offset = 0) { var found = ReadFloatAfter(playerFileContent, keyToLookFor, offset); if (found.indexOf != -1) { var newValueBytes = BitConverter.GetBytes(newValue); Array.ConstrainedCopy(newValueBytes, 0, playerFileContent, found.valueOffset, sizeof(float)); } return found; } static byte[] Empty = new byte[0]; public (int indexOf, int valueOffset, int nextOffset, byte[] valueAsByteArray, float valueAsFloat) ReadFloatAfter(byte[] playerFileContent, string keyToLookFor, int offset = 0) { var idx = BinaryFindKey(playerFileContent, keyToLookFor, offset); byte[] value = Empty; if (idx.indexOf == -1)// Not found return (idx.indexOf, idx.nextOffset, idx.nextOffset, value, 0); value = new ArraySegment<byte>(playerFileContent, idx.nextOffset, sizeof(float)).ToArray(); return (idx.indexOf, idx.nextOffset, idx.nextOffset + sizeof(float), value, BitConverter.ToSingle(value, 0)); } public (int indexOf, int valueOffset, int nextOffset, byte[] valueAsByteArray, int valueAsInt) ReadIntAfter(byte[] playerFileContent, string keyToLookFor, int offset = 0) { var idx = BinaryFindKey(playerFileContent, keyToLookFor, offset); byte[] value = Empty; if (idx.indexOf == -1)// Not found return (idx.indexOf, idx.nextOffset, idx.nextOffset, value, 0); value = new ArraySegment<byte>(playerFileContent, idx.nextOffset, sizeof(int)).ToArray(); return (idx.indexOf, idx.nextOffset, idx.nextOffset + sizeof(int), value, BitConverter.ToInt32(value, 0)); } public (int indexOf, int valueOffset, int nextOffset, int valueLen, byte[] valueAsByteArray, string valueAsString) ReadCStringAfter(byte[] playerFileContent, string keyToLookFor, int offset = 0) { var idx = BinaryFindKey(playerFileContent, keyToLookFor, offset); byte[] value = Empty; if (idx.indexOf == -1)// Not found return (idx.indexOf, idx.nextOffset, idx.nextOffset, 0, Empty, ""); var len = BitConverter.ToInt32(new ArraySegment<byte>(playerFileContent, idx.nextOffset, sizeof(int)).ToArray(), 0); var stringArray = new ArraySegment<byte>(playerFileContent, idx.nextOffset + sizeof(int), len).ToArray(); return (idx.indexOf, idx.nextOffset, idx.nextOffset + sizeof(int) + len, len, stringArray, Encoding1252.GetString(stringArray)); } public (int indexOf, int valueOffset, int nextOffset, int valueLen, byte[] valueAsByteArray, string valueAsString) ReadUnicodeStringAfter(byte[] playerFileContent, string keyToLookFor, int offset = 0) { var idx = BinaryFindKey(playerFileContent, keyToLookFor, offset); byte[] value = Empty; if (idx.indexOf == -1)// Not found return (idx.indexOf, idx.nextOffset, idx.nextOffset, 0, Empty, ""); var len = BitConverter.ToInt32(new ArraySegment<byte>(playerFileContent, idx.nextOffset, sizeof(int)).ToArray(), 0); var stringArray = new ArraySegment<byte>(playerFileContent, idx.nextOffset + sizeof(int), len * 2).ToArray(); return (idx.indexOf, idx.nextOffset, idx.nextOffset + sizeof(int) + len * 2, len, stringArray, EncodingUnicode.GetString(stringArray)); } public (int indexOf, int nextOffset) BinaryFindKey(byte[] dataSource, string key, int offset = 0) { // Add the length of the key to help filter out unwanted hits. byte[] keyWithLen = BitConverter.GetBytes(key.Length).Concat(Encoding1252.GetBytes(key)).ToArray(); var result = BinaryFindKey(dataSource, keyWithLen, offset); // compensate the added length before returning the value return result.indexOf == -1 // not found ? (result.indexOf, offset) : (result.indexOf + sizeof(int), result.nextOffset); } public (int indexOf, int nextOffset) BinaryFindKey(byte[] dataSource, byte[] key, int offset = 0) { // adapted From https://www.codeproject.com/Questions/479424/C-23plusbinaryplusfilesplusfindingplusstrings int i = offset, j = 0; for (; i <= (dataSource.Length - key.Length); i++) { if (dataSource[i] == key[0]) { j = 1; for (; j < key.Length && dataSource[i + j] == key[j]; j++) ; if (j == key.Length) goto found; } } // Not found return (-1, 0); found: return (i, i + key.Length); } /// <summary> /// Find the "end_block" of <paramref name="keyToLookFor"/> /// </summary> /// <param name="playerFileContent"></param> /// <param name="keyToLookFor"></param> /// <param name="offset"></param> /// <returns></returns> public (int indexOf, int valueOffset, int nextOffset, byte[] valueAsByteArray, int valueAsInt) BinaryFindEndBlockOf(byte[] playerFileContent, string keyToLookFor, int offset = 0) { int level = 0; var keybegin_block = "begin_block"; var keyend_block = "end_block"; var noMatch = (-1, 0, 0, new byte[] { }, 0); var startPoint = BinaryFindKey(playerFileContent, keyToLookFor, offset); if (startPoint.indexOf == -1) return noMatch; offset = startPoint.nextOffset; recurse: // Try to find next "end_block" var nextend_block = ReadIntAfter(playerFileContent, keyend_block, offset); // No more end_block left if (nextend_block.indexOf == -1) return noMatch; // Try to find next "begin_block" var nextbegin_block = ReadIntAfter(playerFileContent, keybegin_block, offset); // No more begin_block left if (nextbegin_block.indexOf == -1) return nextend_block; // found // next end_block is closer => found it if (nextend_block.indexOf < nextbegin_block.indexOf && level == 0) return nextend_block; else if (nextend_block.indexOf < nextbegin_block.indexOf && level > 0) { level--; offset = nextend_block.nextOffset; goto recurse; } else { level++; offset = nextbegin_block.nextOffset; goto recurse; } } public bool RemoveCStringValueAfter(ref byte[] playerFileContent, string keyToLookFor, int offset = 0) { var found = ReadCStringAfter(playerFileContent, keyToLookFor, offset); if (found.indexOf == -1) return false; // Remove CString value var keyBytes = Encoding1252.GetBytes(keyToLookFor); playerFileContent = new[] { playerFileContent.Take(found.indexOf - sizeof(int)).ToArray(),// start content BitConverter.GetBytes(keyToLookFor.Length),// KeyLen keyBytes,// Key BitConverter.GetBytes(0),// ValueLen playerFileContent.Skip(found.nextOffset).ToArray(),// end content }.SelectMany(a => a).ToArray(); return true; } public bool ReplaceUnicodeValueAfter(ref byte[] playerFileContent, string keyToLookFor, string replacement, int offset = 0) { var found = ReadUnicodeStringAfter(playerFileContent, keyToLookFor, offset); if (found.indexOf == -1) return false; // Replace Unicode String value var keyBytes = Encoding1252.GetBytes(keyToLookFor); playerFileContent = new[] { playerFileContent.Take(found.indexOf - sizeof(int)).ToArray(),// start content BitConverter.GetBytes(keyToLookFor.Length),// KeyLen keyBytes,// Key BitConverter.GetBytes(replacement.Length),// ValueLen EncodingUnicode.GetBytes(replacement),// Value playerFileContent.Skip(found.nextOffset).ToArray(),// end content }.SelectMany(a => a).ToArray(); return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class NavMeshMotor : MonoBehaviour { public NavMeshAgent navMeshAgent; void Start() { navMeshAgent = GetComponent<NavMeshAgent>(); } public void GoToDestination(Vector3 targetPosition) { if (gameObject.activeSelf) { navMeshAgent.destination = targetPosition; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; using System.Xml.Linq; public class Parsing { // Get all the faction from xml file public static IEnumerable<XElement> ParseCatalog() { XDocument file = new XDocument(); file = XDocument.Load("Resources\\catalog\\factionList.xml"); IEnumerable<XElement> factions = new List<XElement>(); factions = file.Descendants("faction"); return factions; } // Get all the character from the given xml file public static IEnumerable<XElement> ParseFaction(string path) { XDocument file = new XDocument(); file = XDocument.Load(path); IEnumerable<XElement> faction = new List<XElement>(); faction = file.Descendants("character"); return faction; } }
namespace TeamBuilder.App.Core.Commands { using Data; using Models; using System; using System.Linq; using Utilities; public class DeleteUserCommand { public string Execute(string[] inputArgs) { Check.CheckLength(0, inputArgs); AuthenticationManager.Authorize(); User currentUser = AuthenticationManager.GetCurrentUser(); DeleteUser(currentUser); AuthenticationManager.Logout(); return $"User {currentUser.Username} was deleted successfully!"; } private void DeleteUser(User currentUser) { using (TeamBuilderContext context = new TeamBuilderContext()) { context.Users.SingleOrDefault(u => u.Id == currentUser.Id).IsDeleted = true; context.SaveChanges(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mirror; using UnityEngine.SceneManagement; using System; public class RTSNetworkManager : NetworkManager { [SerializeField] private GameObject townHallPref; [SerializeField] private GameOverHandler gameOverHandlerPrefab; private bool isGameInProgress = false; public static event Action ClientOnConnected; public static event Action ClientOnDisconnected; public List<RtsPlayer> Getplayers { get; } = new List<RtsPlayer>(); #region Client public override void OnClientConnect() { base.OnClientConnect(); ClientOnConnected?.Invoke(); } public override void OnClientDisconnect() { base.OnClientDisconnect(); ClientOnDisconnected?.Invoke(); } public override void OnStopClient() { Getplayers.Clear(); } #endregion #region Server public override void OnServerConnect(NetworkConnectionToClient conn) { if (!isGameInProgress) { return; } conn.Disconnect(); } public override void OnServerDisconnect(NetworkConnectionToClient conn) { RtsPlayer player = conn.identity.GetComponent<RtsPlayer>(); Getplayers.Remove(player); } public override void OnStopServer() { Getplayers.Clear(); isGameInProgress = false; } public void StartGame() { // cant start if less than 2 player if (Getplayers.Count < 2) {return;} isGameInProgress = true; ServerChangeScene("Mp1"); } public override void OnServerAddPlayer(NetworkConnectionToClient conn) { base.OnServerAddPlayer(conn); RtsPlayer player = conn.identity.GetComponent<RtsPlayer>(); Getplayers.Add(player); player.SetDisplayName($"Player {Getplayers.Count}"); player.SetTeamColor( new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f))); player.SetPartyOwner(Getplayers.Count == 1); } public override void OnServerSceneChanged(string sceneName) { // Utilisation du UnityEngine.SceneManagement pour cette section if (SceneManager.GetActiveScene().name.StartsWith("Mp")) { GameOverHandler gameOverHandlerInstance = Instantiate(gameOverHandlerPrefab); NetworkServer.Spawn(gameOverHandlerInstance.gameObject); foreach (RtsPlayer player in Getplayers) { GameObject baseInstance = Instantiate(townHallPref, GetStartPosition().position, Quaternion.identity); NetworkServer.Spawn(baseInstance,player.connectionToClient); } } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Business.Helper; using Model.DataEntity; using Model.Locale; using Model.Security.MembershipManagement; using Uxnet.Web.Module.Common; using Utility; using Uxnet.Web.WebUI; namespace eIVOGo.Module.SAM { public partial class ExceptionLogList : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { initializeData(); } else tblAction.Visible = true; } private void initializeData() { } protected override void OnInit(EventArgs e) { base.OnInit(e); this.PreRender += new EventHandler(MemberManager_PreRender); dsLog.Select += new EventHandler<DataAccessLayer.basis.LinqToSqlDataSourceEventArgs<ExceptionLog>>(dsLog_Select); } void dsLog_Select(object sender, DataAccessLayer.basis.LinqToSqlDataSourceEventArgs<ExceptionLog> e) { if (!String.IsNullOrEmpty(btnQuery.CommandArgument)) { Expression<Func<ExceptionLog, bool>> queryExpr = g => true; if (DateFrom.HasValue) { queryExpr = queryExpr.And(g => g.LogTime >= DateFrom.DateTimeValue); } if (DateTo.HasValue) { queryExpr = queryExpr.And(g => g.LogTime < DateTo.DateTimeValue.AddDays(1)); } if (DocumentType.SelectedIndex > 0) { queryExpr = queryExpr.And(g => g.TypeID == int.Parse(DocumentType.SelectedValue)); } if (!String.IsNullOrEmpty(SellerID.SelectedValue)) { queryExpr = queryExpr.And(g => g.CompanyID == int.Parse(SellerID.SelectedValue)); } e.Query = dsLog.CreateDataManager().EntityList.Where(queryExpr).OrderByDescending(g => g.LogID); } else { e.QueryExpr = u => false; } } protected void PageIndexChanged(object source, PageChangedEventArgs e) { gvEntity.PageIndex = e.NewPageIndex; gvEntity.DataBind(); } void MemberManager_PreRender(object sender, EventArgs e) { if (gvEntity.BottomPagerRow != null) { PagingControl paging = (PagingControl)gvEntity.BottomPagerRow.Cells[0].FindControl("pagingList"); paging.RecordCount = dsLog.CurrentView.LastSelectArguments.TotalRowCount; paging.CurrentPageIndex = gvEntity.PageIndex; } } protected void btnQuery_Click(object sender, EventArgs e) { btnQuery.CommandArgument = "Query"; gvEntity.DataBind(); tblAction.Visible = true; result.Visible = true; } public String[] GetItemSelection() { return Request.Form.GetValues("chkItem"); } protected void btnShow_Click(object sender, EventArgs e) { String[] ar = GetItemSelection(); var mgr = dsLog.CreateDataManager(); if (ar != null && ar.Count() > 0) { foreach (var InvoiceId in ar) { //var table = mgr.GetTable<ExceptionLog>(); var table = mgr.GetTable<ExceptionReplication>(); table.InsertOnSubmit(new ExceptionReplication { LogID = int.Parse(InvoiceId) }); } this.AjaxAlert("資料已重送!!"); } else { this.AjaxAlert("請選擇重送資料!!"); } mgr.SubmitChanges(); Model.Helper.ExceptionNotification.ProcessNotification(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Media.Imaging; using ClaudiaIDE.Settings; using System.Threading; using System.Collections; using ClaudiaIDE.Helpers; namespace ClaudiaIDE { public class SlideShowImageProvider : IImageProvider { private readonly Timer _timer; private readonly Setting _setting; private ImageFiles _imageFiles; private IEnumerator<string> _imageFilesPath; public bool Pause { get; set; } = false; public SlideShowImageProvider(Setting setting, string solutionfile = null) { SolutionConfigFile = solutionfile; _setting = setting; _setting.OnChanged.AddEventHandler(ReloadSettings); _timer = new Timer(state => { if (!Pause) ChangeImage(); }); ReloadSettings(null, null); } ~SlideShowImageProvider() { if (_setting != null) { _setting.OnChanged.RemoveEventHandler(ReloadSettings); } } public event EventHandler NewImageAvaliable; private ImageFiles GetImagesFromDirectory() { return new ImageFiles { Extensions = _setting.Extensions, ImageDirectoryPath = _setting.BackgroundImagesDirectoryAbsolutePath, Shuffle = _setting.ShuffleSlideshow }; } public BitmapSource GetBitmap() { var current = _imageFilesPath?.Current; if (string.IsNullOrEmpty(current)) return null; var bitmap = new BitmapImage(); var fileInfo = new FileInfo(current); if (fileInfo.Exists) { bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.UriSource = new Uri(current, UriKind.RelativeOrAbsolute); bitmap.EndInit(); bitmap.Freeze(); } else { ReloadSettings(null, null); return GetBitmap(); } BitmapSource ret_bitmap = bitmap; if (_setting.ImageStretch == ImageStretch.None) { bitmap = Utils.EnsureMaxWidthHeight(bitmap, _setting.MaxWidth, _setting.MaxHeight); if (bitmap.Width != bitmap.PixelWidth || bitmap.Height != bitmap.PixelHeight) { ret_bitmap = Utils.ConvertToDpi96(bitmap); } } if (_setting.SoftEdgeX > 0 || _setting.SoftEdgeY > 0) { ret_bitmap = Utils.SoftenEdges(ret_bitmap, _setting.SoftEdgeX, _setting.SoftEdgeY); } return ret_bitmap; } private void ReloadSettings(object sender, System.EventArgs e) { if (_setting.ImageBackgroundType == ImageBackgroundType.Single || _setting.ImageBackgroundType == ImageBackgroundType.SingleEach) { _timer.Change(Timeout.Infinite, Timeout.Infinite); } else { _imageFiles = GetImagesFromDirectory(); _imageFilesPath = _imageFiles.GetEnumerator(); _timer.Change(0, (int) _setting.UpdateImageInterval.TotalMilliseconds); } } public void NextImage() { if (_setting.ImageBackgroundType != ImageBackgroundType.Slideshow) return; if (!Pause) _timer.Change(0, (int) _setting.UpdateImageInterval.TotalMilliseconds); else ChangeImage(); } protected void ChangeImage() { if (_imageFilesPath.MoveNext()) { NewImageAvaliable?.Invoke(this, EventArgs.Empty); } else { // Reached the end of the images. Loop to beginning? if (_setting.LoopSlideshow) { _imageFilesPath.Reset(); if (_imageFilesPath.MoveNext()) { NewImageAvaliable?.Invoke(this, EventArgs.Empty); } } } } public ImageBackgroundType ProviderType { get { return ImageBackgroundType.Slideshow; } } public string SolutionConfigFile { get; private set; } } public class ImageFiles : IEnumerable<string> { public string Extensions { get; set; } public string ImageDirectoryPath { get; set; } public bool Shuffle { get; set; } public IEnumerator<string> GetEnumerator() { if (string.IsNullOrEmpty(Extensions) || string.IsNullOrEmpty(ImageDirectoryPath) || !Directory.Exists(ImageDirectoryPath)) { return new ImageFilesEnumerator(new List<string>()); } var extensions = Extensions .Split(new[] {",", " "}, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.ToUpper()); List<string> imageFilePaths = Directory.GetFiles(new DirectoryInfo(ImageDirectoryPath).FullName) .Where(x => extensions.Contains(Path.GetExtension(x).ToUpper())).OrderBy(x => x).ToList(); if (Shuffle) imageFilePaths.Shuffle(); if (!imageFilePaths.Any()) { return new ImageFilesEnumerator(new List<string>()); } else { return new ImageFilesEnumerator(imageFilePaths); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ImageFilesEnumerator : IEnumerator<string> { private int position; private readonly List<string> imageFilePaths; public ImageFilesEnumerator(List<string> imageFilePaths) { this.imageFilePaths = imageFilePaths; position = -1; } public string Current { get { return imageFilePaths[position]; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { } public bool MoveNext() { position++; return position < imageFilePaths.Count; } public void Reset() { position = -1; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Servico; using Modelo; namespace Apresentacao { public partial class Medicamento_Controle : UserControl { bool editar = false; private MedicamentoServico medicamentoServico = new MedicamentoServico(); public Medicamento_Controle() { InitializeComponent(); DataGridViewRefresh(); } private void DataGridViewRefresh() { dgvMedicamentos.DataSource = medicamentoServico.TodosOsMedicamentos(); } private void btnNovoMedicamento_Click(object sender, EventArgs e) { FormMedicamento formMedicamento = new FormMedicamento(); formMedicamento.Show(); } private void btnAtualizar_Click(object sender, EventArgs e) { DataGridViewRefresh(); } private void btnEditar_Click(object sender, EventArgs e) { FormMedicamento formMedicamento = new FormMedicamento( new Modelo.Medicamento() { MedicamentoId = Convert.ToInt64(dgvMedicamentos.CurrentRow.Cells["MedicamentoId"].Value.ToString()), Descricao = dgvMedicamentos.CurrentRow.Cells["Descricao"].Value.ToString(), ValorUnitario = Convert.ToDouble(dgvMedicamentos.CurrentRow.Cells["ValorUnitario"].Value.ToString()), } ); formMedicamento.Show(); } private void btnExcluir_Click(object sender, EventArgs e) { medicamentoServico.ExcluirMedicamento(Convert.ToInt32(dgvMedicamentos.CurrentRow.Cells["MedicamentoId"].Value.ToString())); DataGridViewRefresh(); } } }
using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using WebApplication.Api.Configuration.AutoMapper; using WebApplication.Data.Context; using WebApplication.Data.Repositories.Configurations; using WebApplication.Services.DtoModels; using WebApplication.Services.Services.ConfigurationService; using Xunit; namespace WebApplication.Tests { public class ConfigurationTest { private readonly ApplicationDbContext _context; private readonly IMapper _mapper; public ConfigurationTest() { var services = new ServiceCollection() .AddDbContext<ApplicationDbContext>( options => options .UseInMemoryDatabase("TestDB") .UseInternalServiceProvider( new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider())) .BuildServiceProvider(); _context = services.GetRequiredService<ApplicationDbContext>(); _context.Database.EnsureCreated(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(typeof(MappingProfile))); IMapper mapper = new Mapper(configuration); _mapper = mapper; } [Fact] public async Task Create_And_GetAll() { // Arrange var rep = new ConfigurationItemRepository(_context); var service = new ConfigurationService(rep, _mapper); var testModel = new ConfigurationItemDtoModel { Id = 0, Name = "32 gb RAM", Cost = 50.39M, ConfigurationType = new ConfigurationTypeDtoModel { Id = 1, TypeName = "Ram" } }; // Act await service.CreateConfigurationItem(testModel); var list = await service.GetAllConfigurationItems(); // Assert Assert.Equal(7, list.Count); Assert.NotNull(list.FirstOrDefault(x => x.Name == testModel.Name)); Assert.NotNull(list.FirstOrDefault(x => x.ConfigurationType.Id == testModel.ConfigurationType.Id)); } } }
namespace SGDE.Domain.Helpers { #region Using using SGDE.Domain.ViewModels; using SGDE.Domain.Supervisor; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; using System; using SGDE.Domain.Converters; using Newtonsoft.Json.Linq; using System.Collections.Generic; using SGDE.Domain.Entities; using System.Linq; using iTextSharp.text.rtf.table; #endregion public abstract class GenerateInvoice { public const string _CREATOR = "Servicio de Report (ADECUA)"; public static readonly Font _STANDARFONT_10 = FontFactory.GetFont(FontFactory.HELVETICA, 10); public static readonly Font _STANDARFONT_8 = FontFactory.GetFont(FontFactory.HELVETICA, 8); public static readonly Font _STANDARFONT_10_BOLD = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10); public static readonly Font _STANDARFONT_10_BOLD_CUSTOMCOLOR = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, new BaseColor(144, 54, 25)); public static readonly Font _STANDARFONT_12_BOLD = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); public static readonly Font _STANDARFONT_14_BOLD = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14); public static readonly Font _STANDARFONT_12_BOLD_WHITE = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, BaseColor.White); public static readonly Font _STANDARFONT_14_BOLD_WHITE = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14, BaseColor.White); public InvoiceViewModel _invoiceViewModel; protected Document _pdf; public InvoiceResponseViewModel _invoiceResponseViewModel; protected Client _client; protected Work _work; protected User _worker; protected Invoice _invoice; public InvoiceQueryViewModel _invoiceQueryViewModel; protected ISupervisor _supervisor; protected int _invoiceId; public GenerateInvoice(ISupervisor supervisor, InvoiceQueryViewModel invoiceQueryViewModel) { _supervisor = supervisor; _invoiceQueryViewModel = invoiceQueryViewModel; _invoiceResponseViewModel = new InvoiceResponseViewModel { typeFile = "application/pdf", data = new InvoiceViewModel { startDate = invoiceQueryViewModel.startDate, endDate = invoiceQueryViewModel.endDate }, typeInvoiceId = invoiceQueryViewModel.typeInvoice }; } public GenerateInvoice(ISupervisor supervisor, int invoiceId) { _supervisor = supervisor; _invoiceId = invoiceId; _invoiceResponseViewModel = new InvoiceResponseViewModel { typeFile = "application/pdf" }; } public abstract bool Validate(); protected abstract PdfPTable GetAllRowsDetailInvoice(Document pdf); protected abstract PdfPTable GetTableNumberInvoice(); public void Process() { if (!Validate()) throw new Exception("No se puede validar la Factura"); _invoice = AddInvoice(); _pdf = new Document(PageSize.Letter); var memoryStream = new MemoryStream(); var pdfWriter = PdfWriter.GetInstance(_pdf, memoryStream); _pdf.AddTitle("Factura Cliente"); _pdf.AddCreator(_CREATOR); _pdf.Open(); _pdf.Add(GetHeader()); _pdf.Add(GetTableNumberInvoice()); _pdf.Add(GetTableClient()); _pdf.Add(new Paragraph(" ", _STANDARFONT_8)); _pdf.Add(GetLineSeparator()); _pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetTableTitle()); _pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetTableTitleInvoice()); //_pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetAllRowsDetailInvoice(_pdf)); _pdf.Add(new Paragraph(" ", _STANDARFONT_8)); _pdf.Add(GetLineSeparator()); _pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetTableTitle1("FORMA DE PAGO")); _pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetPayment()); _pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetSignAndStamp()); _pdf.Add(new Paragraph(" ", _STANDARFONT_14_BOLD)); _pdf.Add(GetPassiveSubject()); _pdf.Close(); pdfWriter.Close(); _invoiceResponseViewModel.file = memoryStream.ToArray(); _invoiceResponseViewModel.fileName = $"Fact_{_invoice.Name.Replace("/", "_")}.pdf"; FillDataResponse(); } protected PdfPTable GetHeader() { var companyData = _supervisor.GetSettingByName("COMPANY_DATA"); if (companyData == null) throw new Exception("No existen datos de tu Empresa para poder realizar la factura"); var jsonCompanyData = JObject.Parse(companyData.data); var pdfPTable = new PdfPTable(2) { WidthPercentage = 100 }; var image = Image.GetInstance(Directory.GetCurrentDirectory() + "\\assets\\images\\arconsa.png"); image.ScalePercent(75f); var pdfCellImage = new PdfPCell(image) { Rowspan = 4, BorderWidth = 0, PaddingLeft = 20 }; pdfPTable.AddCell(pdfCellImage); var pdfCell = new PdfPCell(new Phrase(jsonCompanyData["companyName"].ToString(), _STANDARFONT_12_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(jsonCompanyData["cif"].ToString(), _STANDARFONT_12_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(jsonCompanyData["address"].ToString(), _STANDARFONT_12_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(jsonCompanyData["phoneNumber"].ToString(), _STANDARFONT_12_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); return pdfPTable; } protected virtual PdfPTable GetTableClient() { if (_client == null) throw new Exception("No existen datos para este Cliente"); var pdfPTable = new PdfPTable(2) { WidthPercentage = 100 }; var widths = new[] { 15f, 85f }; pdfPTable.SetWidths(widths); var pdfCell = new PdfPCell(new Phrase("Empresa", _STANDARFONT_10_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_client.Name, _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("CIF/NIF", _STANDARFONT_10_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_client.Cif, _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("Dirección", _STANDARFONT_10_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_client.Address, _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("Teléfono", _STANDARFONT_10_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_client.PhoneNumber, _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("Obra", _STANDARFONT_10_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_work.Name, _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); return pdfPTable; } protected double GetPriceHourSale(int? type, int? professionId) { if (type == null || professionId == null) return 0; var professionInClient = _client.ProfessionInClients.FirstOrDefault(x => x.ProfessionId == professionId); if (professionInClient == null) return 0; switch (type) { case 1: return (double)professionInClient.PriceHourSaleOrdinary; case 2: return (double)professionInClient.PriceHourSaleExtra; case 3: return (double)professionInClient.PriceHourSaleFestive; default: return 0; } } protected Invoice AddInvoice() { var invoice = _supervisor.AddInvoiceFromQuery(_invoiceQueryViewModel); return invoice; } protected PdfPTable GetTableTitle() { var pdfPTable = new PdfPTable(4) { WidthPercentage = 100 }; var widths = new[] { 40f, 20f, 20f, 20f }; pdfPTable.SetWidths(widths); var pdfCell = new PdfPCell(new Phrase("SERVICIOS REALIZADOS", _STANDARFONT_12_BOLD_WHITE)) { BackgroundColor = new BaseColor(20, 66, 92), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("UNIDAD", _STANDARFONT_12_BOLD_WHITE)) { BackgroundColor = new BaseColor(20, 66, 92), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("PRECIO UNIDAD", _STANDARFONT_12_BOLD_WHITE)) { BackgroundColor = new BaseColor(20, 66, 92), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("IMPORTE", _STANDARFONT_12_BOLD_WHITE)) { BackgroundColor = new BaseColor(20, 66, 92), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); return pdfPTable; } protected Chunk GetLineSeparator() { return new Chunk( new iTextSharp.text.pdf.draw.LineSeparator(0f, 100f, BaseColor.LightGray, Element.ALIGN_LEFT, 1)); } protected PdfPTable GetTableTitleInvoice() { var listMonths = new[] { "ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE" }; var monthIni = _invoice.StartDate.Month; var monthEnd = _invoice.EndDate.Month; var yearIni = _invoice.StartDate.Year; var yearEnd = _invoice.EndDate.Year; var title = string.Empty; if (_invoice.InvoiceToCancelId == null) { if (_invoice.TypeInvoice == 1) { if (monthIni == monthEnd && yearIni == yearEnd) { title = $"HORAS POR ADMINISTRACION SEGÚN SERVICIOS PRESTADOS EN LA OBRA DE REFERENCIA CORRESPONIENTES AL MES DE {listMonths[monthIni - 1]} {yearIni}"; } else { title = $"HORAS POR ADMINISTRACION SEGÚN SERVICIOS PRESTADOS EN LA OBRA DE REFERENCIA CORRESPONIENTES ENTRE LOS MESES DE {listMonths[monthIni - 1]} {yearIni} Y {listMonths[monthEnd - 1]} {yearEnd}"; } } } else { var invoiceParent = _supervisor.GetInvoice((int)_invoice.InvoiceToCancelId); title = $"FACTURA ABONO CORRESPONDIENTE A LA FACTURA Nº {invoiceParent.Name}"; } var pdfPTable = new PdfPTable(4) { WidthPercentage = 100 }; var widths = new[] { 40f, 20f, 20f, 20f }; pdfPTable.SetWidths(widths); if (string.IsNullOrEmpty(title)) { return pdfPTable; } var pdfCell = new PdfPCell(new Phrase(title, _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); return pdfPTable; } protected PdfPTable GetTableTitle1(string title) { var pdfPTable = new PdfPTable(1) { WidthPercentage = 100 }; var pdfCell = new PdfPCell(new Phrase(title, _STANDARFONT_14_BOLD_WHITE)) { BackgroundColor = new BaseColor(20, 66, 92), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f }; pdfPTable.AddCell(pdfCell); return pdfPTable; } protected PdfPTable GetPayment() { var pdfPTable = new PdfPTable(5) { WidthPercentage = 100 }; var widths = new[] { 20f, 20f, 10f, 20f, 30f }; pdfPTable.SetWidths(widths); var pdfCell = new PdfPCell(new Phrase("Método de Pago", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_client.WayToPay, _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("Nº de Cuenta", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(_client.AccountNumber, _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); GetInvoceToOrigen(pdfPTable); var taxBase = Math.Round(_invoice.DetailsInvoice.Sum(x => x.PriceUnity * x.Units), 2); pdfCell = new PdfPCell(new Phrase("Base Imponible", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{taxBase.ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); if (!_work.PassiveSubject) { var detailsGroup = _invoice.DetailsInvoice .GroupBy(x => x.Iva) .Select(y => new SumDetailInvoiceByIvaViewModel { Title = $"I.V.A. {y.Key * 100}%", Amount = Math.Round(y.Sum(z => z.Units * z.PriceUnity * z.Iva), 2) }); foreach (var detailGroup in detailsGroup) { pdfCell = new PdfPCell(new Phrase(detailGroup.Title, _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{detailGroup.Amount.ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); } } var percentageTaxBase = taxBase * _work.PercentageRetention; var titlePercentageTaxBase = percentageTaxBase == 0 ? "-" : percentageTaxBase.ToFormatSpain(); var ivaTaxBase = Math.Round(_invoice.DetailsInvoice.Sum(x => x.PriceUnity * x.Units * x.Iva), 2); var total = taxBase + ivaTaxBase - percentageTaxBase; pdfCell = new PdfPCell(new Phrase($"{Math.Round((double)_work.PercentageRetention * 100)}% de Retención", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{titlePercentageTaxBase} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase("Total Factura", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{total.ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); return pdfPTable; } protected PdfPTable GetPassiveSubject() { var pdfPTable = new PdfPTable(1) { WidthPercentage = 100 }; if (_work.PassiveSubject) { var pdfCell = new PdfPCell(new Phrase("IVA Inversión del Sujeto Pasivo: ARTÍCULO 88 LEY INVERSIÓN SUJETO PASIVO", _STANDARFONT_10_BOLD)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); } return pdfPTable; } protected PdfPTable GetSignAndStamp() { var pdfPTable = new PdfPTable(1) { WidthPercentage = 40, HorizontalAlignment = 2 }; var pdfCell = new PdfPCell(new Phrase("Firma y Sello", _STANDARFONT_12_BOLD)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f }; pdfPTable.AddCell(pdfCell); var image = Image.GetInstance(Directory.GetCurrentDirectory() + "\\assets\\images\\FirmAndSign.png"); image.ScalePercent(50); var pdfCellImage = new PdfPCell(image) { BorderWidthTop = 0, PaddingTop = 2, PaddingBottom = 2, PaddingRight = 2, PaddingLeft = 30, }; pdfPTable.AddCell(pdfCellImage); return pdfPTable; } private void FillDataResponse() { _invoiceResponseViewModel.data.name = _invoice.Name; _invoiceResponseViewModel.data.invoiceNumber = _invoice.InvoiceNumber; _invoiceResponseViewModel.data.taxBase = _invoice.TaxBase; _invoiceResponseViewModel.data.ivaTaxBase = _invoice.IvaTaxBase; _invoiceResponseViewModel.data.retentions = _invoice.Retentions; _invoiceResponseViewModel.data.startDate = _invoice.StartDate; _invoiceResponseViewModel.data.endDate = _invoice.EndDate; _invoiceResponseViewModel.data.issueDate = _invoice.IssueDate; _invoiceResponseViewModel.data.iva = _invoice.Iva; _invoiceResponseViewModel.data.total = _invoice.Total; _invoiceResponseViewModel.data.workId = _invoice.WorkId; _invoiceResponseViewModel.data.clientId = _invoice.ClientId; _invoiceResponseViewModel.data.userId = _invoice.UserId; } private void GetInvoceToOrigen(PdfPTable pdfPTable) { if (!_work.InvoiceToOrigin) return; var baseImponible = 0.0; var certificacionAnterior = 0.0; var certificacionOrigen = 0.0; foreach (var detailInvoice in _invoice.DetailsInvoice) { baseImponible += (double)detailInvoice.Units * (double)detailInvoice.PriceUnity; certificacionAnterior += (double)detailInvoice.UnitsAccumulated * (double)detailInvoice.PriceUnity; certificacionOrigen += (double)(detailInvoice.Units + detailInvoice.UnitsAccumulated) * (double)detailInvoice.PriceUnity; } baseImponible = Math.Round(baseImponible, 2); certificacionAnterior = Math.Round(certificacionAnterior, 2); certificacionOrigen = Math.Round(certificacionOrigen, 2); //var sumInvoices = _work.Invoices.Where(x => x.Id != _invoice.Id && x.EndDate < _invoice.StartDate).Select(x => x.TaxBase).Sum(); //var result = sumInvoices + _invoice.TaxBase; PdfPCell pdfCell; var totalContract = (double)_work.WorkBudgets.FirstOrDefault(x => x.Type == "Definitivo")?.TotalContract; if (totalContract != 0) { pdfCell = new PdfPCell(new Phrase("Total Contrato", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{Math.Round((double)totalContract, 2).ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); var pendingContract = (double)totalContract - certificacionOrigen; pdfCell = new PdfPCell(new Phrase("Pendiente Contrato", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{Math.Round((double)pendingContract, 2).ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); } pdfCell = new PdfPCell(new Phrase("Certificación a Origen", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{certificacionOrigen.ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); //var certBefore = _work.Invoices.Where(x => x.Id != _invoice.Id && x.EndDate < _invoice.StartDate).OrderByDescending(x => x.StartDate).FirstOrDefault(); //var taxBaseCertBefore = 0.0; //if (certBefore != null) // taxBaseCertBefore = Math.Round((double)certBefore.TaxBase, 2); pdfCell = new PdfPCell(new Phrase("Certificación Anterior", _STANDARFONT_10_BOLD_CUSTOMCOLOR)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase($"{certificacionAnterior.ToFormatSpain()} €", _STANDARFONT_10)) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); } protected void AddRowClearToDetailInvoice(PdfPTable pdfPTable) { var pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); pdfCell = new PdfPCell(new Phrase(" ", _STANDARFONT_10)) { HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 2f, PaddingBottom = 6f, BorderWidth = 0 }; pdfPTable.AddCell(pdfCell); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace GetSetGo.Dtos { public class VehicleDto { [Key] public int Id { get; set; } [Required] public string Name { get; set; } public VehicleTypeDto VehicleType { get; set; } public byte VehicleTypeId { get; set; } public string PlateNumber { get; set; } public string Color { get; set; } public bool Availability { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlockChain { interface IBlockChainHandler { bool AddPrescription(string patientId, string doctorId, DateTime validSinceDate, ObservableCollection<Medicine> medicines); bool RealizePrescription(string prescriptionId, string pharmacistId); ObservableCollection<Prescription> GetAllPrescriptionsByPatient(string patientId); ObservableCollection<Prescription> GetAllPrescriptionsByDoctor(string doctorId); ObservableCollection<Prescription> GetAllPrescriptions(); ObservableCollection<Prescription> GetAllRealizedPrescriptionsByPatient(string patientId); ObservableCollection<Prescription> GetAllRealizedPrescriptionsByPharmacist(string pharmacistId); ObservableCollection<Prescription> GetAllRealizedPrescriptionsByDoctor(string doctorId); ObservableCollection<Prescription> GetAllRealizedPrescriptions(); int GetNumberOfPrescriptions(); int GetNumberOfRealizedPrescriptions(); } }
using UnityEngine; using System.Collections; public class WallCollision : MonoBehaviour { public bool wallRight; public bool wallNearRight; public bool wallLeft; public bool wallNearLeft; public GroundCollision grounded; public playerController player; // Use this for initialization void Start() { } //check wall left public IEnumerator Deactivate() { wallNearRight = false; wallRight = false; wallNearLeft = false; wallLeft = false; gameObject.SetActive(false); yield return new WaitForSeconds(.1f); gameObject.SetActive(true); } void OnTriggerStay2D(Collider2D other) { wallNearRight = true; if ((other.tag == "Ground") && (grounded.grounded == false) && (player.currentSpeedy <= 0) && (Input.GetKey("d"))) { wallRight = true; } if ((other.tag == "Ground") && (grounded.grounded == false) && (player.currentSpeedy <= 0) && (Input.GetKey("a"))) { wallLeft = true; } } void OnTriggerExit2D(Collider2D other) { wallNearRight = false; if (other.tag == "Ground") { wallRight = false; } } /*void OnTriggerExit2D(Collider2D other) { if (other.tag == "Ground") { wallLeft = false; } } */ // Update is called once per frame void Update() { if (grounded.grounded == true) { wallRight = false; } } }
using System.Collections.Generic; using System.Linq; using Ecommerce.Dto; using Ecommerce.UnitOfWork; namespace Ecommerce.Service.Services { public class ProductService : IProductService { private readonly IUnitOfWork _uow; public ProductService(IUnitOfWork uow) { _uow = uow; } public ServiceResponse<List<ProductDto>> GetAll() { var products = _uow.ProductRepository.FindAll().Select(x => new ProductDto { ProductId = x.ProductId, Code = x.Code, Name = x.Name, Price = x.Price }).ToList(); return new ServiceResponse<List<ProductDto>> { Success = true, Message = "Products listed successfully.", Data = products }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test7._2 { class Program { static void Main(string[] args) { WaresInfo info1 = new WaresInfo(); info1.pring(); WaresInfo info2 = new WaresInfo("0000002222", "华为手机"); info2.pring(); Console.ReadKey(); } } class WaresInfo { public string serialNumber; public string name; public WaresInfo() { this.serialNumber = "20200915"; this.name = "麻辣香锅"; } public WaresInfo(string num,string name) { this.serialNumber = num; this.name = name; } public void pring() { Console.WriteLine("商品编号为:{0}的商品是:{1}",serialNumber,name); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tests { internal class EquivalentStringTestData : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { yield return new[] { "Abcd" }; yield return new[] { "cd ef" }; yield return new[] { "cD eD" }; yield return new[] { "Dc Ef" }; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
using System; using System.Collections.Generic; using System.Linq; using FluentValidation.Results; namespace DDDSouthWest.Website.Features.Admin.Account.ManageNews { public class ManageNewsViewModel { public ManageNewsViewModel() { Errors = new List<ValidationFailure>(); } public int Id { get; set; } public string Title { get; set; } public string Filename { get; set; } public DateTime DatePosted { get; set; } public string BodyMarkdown { get; set; } public bool IsLive { get; set; } public IList<ValidationFailure> Errors { get; set; } public bool HasErrors => Errors.Any(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SFP.SIT.SERV.Model._Consultas { public class NodoResp { public long nodclave { get; set; } public long repclave { get; set; } public int rtpclave { get; set; } public string rtpdescripcion { get; set; } public string rtpforma { get; set; } public string detdescripcion { get; set; } public NodoResp() { } } }
// Copyright 2018 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 NtApiDotNet; using NtApiDotNet.Utilities.Text; using NtApiDotNet.Win32; using NtApiDotNet.Win32.Security; using NtApiDotNet.Win32.Security.Native; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Text; using System.Text.RegularExpressions; namespace NtObjectManager.Utils { /// <para type="description">Enumeration to specify a text encoding.</para> public enum TextEncodingType { /// <summary> /// Binary raw text. /// </summary> Binary, /// <summary> /// 16 bit unicode text. /// </summary> Unicode, /// <summary> /// Big Endian 16 bit unicode text. /// </summary> BigEndianUnicode, /// <summary> /// UTF8 /// </summary> UTF8, /// <summary> /// UTF32 /// </summary> UTF32, /// <summary> /// UTF7 /// </summary> UTF7 } /// <summary> /// Some utility functions for PowerShell. /// </summary> public static class PSUtils { internal static T InvokeWithArg<T>(this ScriptBlock script_block, T default_value, params object[] args) { try { List<PSVariable> vars = new List<PSVariable>(); if (args.Length > 0) { vars.Add(new PSVariable("_", args[0])); } var os = script_block.InvokeWithContext(null, vars, args); if (os.Count > 0) { return (T)Convert.ChangeType(os[0].BaseObject, typeof(T)); } } catch { } return default_value; } internal static Collection<PSObject> InvokeWithArg(this ScriptBlock script_block, params object[] args) { List<PSVariable> vars = new List<PSVariable>(); if (args.Length > 0) { vars.Add(new PSVariable("_", args[0])); } return script_block.InvokeWithContext(null, vars, args); } internal static Encoding GetEncoding(TextEncodingType encoding) { switch (encoding) { case TextEncodingType.Binary: return BinaryEncoding.Instance; case TextEncodingType.Unicode: return Encoding.Unicode; case TextEncodingType.BigEndianUnicode: return Encoding.BigEndianUnicode; case TextEncodingType.UTF8: return Encoding.UTF8; case TextEncodingType.UTF32: return Encoding.UTF32; case TextEncodingType.UTF7: return Encoding.UTF7; default: throw new ArgumentException("Unknown text encoding", nameof(encoding)); } } internal static void AddDynamicParameter(this RuntimeDefinedParameterDictionary dict, string name, Type type, bool mandatory, int? position = null) { Collection<Attribute> attrs = new Collection<Attribute>(); ParameterAttribute attr = new ParameterAttribute { Mandatory = mandatory }; if (position.HasValue) { attr.Position = position.Value; } attrs.Add(attr); dict.Add(name, new RuntimeDefinedParameter(name, type, attrs)); } internal static bool GetValue<T>(this RuntimeDefinedParameterDictionary dict, string name, out T value) where T : class { value = default; if (!dict.ContainsKey(name)) return false; if (dict[name].Value is T result) { value = result; return true; } return false; } internal static bool GetValue<T>(this RuntimeDefinedParameterDictionary dict, string name, out T? value) where T : struct { value = default; if (!dict.ContainsKey(name)) return false; if (dict[name].Value is T result) { value = result; return true; } return false; } internal static Regex GlobToRegex(string glob, bool case_sensitive) { string escaped = Regex.Escape(glob); return new Regex("^" + escaped.Replace("\\*", ".*").Replace("\\?", ".") + "$", !case_sensitive ? RegexOptions.IgnoreCase : RegexOptions.None); } internal static bool HasGlobChars(string s) { return s.Contains("*") || s.Contains("?"); } private static string Combine(string path1, string path2) { path1 = path1.TrimEnd('\\', '/'); return path1 + @"\" + path2; } internal static NtResult<string> GetFileBasePath(SessionState state) { var current_path = state.Path.CurrentLocation; if (!current_path.Provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase)) { return NtResult<string>.CreateResultFromError(NtStatus.STATUS_OBJECT_PATH_NOT_FOUND, false); } return NtFileUtils.DosFileNameToNt(current_path.Path, false); } private static string ResolveRelativePath(SessionState state, string path, RtlPathType path_type) { var current_path = state.Path.CurrentFileSystemLocation; if (!current_path.Provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Can't make a relative Win32 path when not in a file system drive."); } switch (path_type) { case RtlPathType.Relative: return Combine(current_path.Path, path); case RtlPathType.Rooted: return $"{current_path.Drive.Name}:{path}"; case RtlPathType.DriveRelative: if (path.Substring(0, 1).Equals(current_path.Drive.Name, StringComparison.OrdinalIgnoreCase)) { return Combine(current_path.Path, path.Substring(2)); } break; } return path; } /// <summary> /// Resolve a Win32 path using current PS session state. /// </summary> /// <param name="state">The session state.</param> /// <param name="path">The path to resolve.</param> /// <returns>The resolved Win32 path.</returns> public static string ResolveWin32Path(SessionState state, string path) { return ResolveWin32Path(state, path, true); } internal static string ResolveWin32Path(SessionState state, string path, bool convert_to_nt_path) { var path_type = NtFileUtils.GetDosPathType(path); if (path_type == RtlPathType.Rooted && path.StartsWith(@"\??")) { path_type = RtlPathType.LocalDevice; } switch (path_type) { case RtlPathType.Relative: case RtlPathType.DriveRelative: case RtlPathType.Rooted: path = ResolveRelativePath(state, path, path_type); break; } return convert_to_nt_path ? NtFileUtils.DosFileNameToNt(path) : Path.GetFullPath(path); } internal static string ResolvePath(SessionState state, string path, bool win32_path) { if (win32_path) { return ResolveWin32Path(state, path); } else { return path; } } private static void DisposeObject(object obj) { IDisposable disp = obj as IDisposable; if (obj is PSObject psobj) { disp = psobj.BaseObject as IDisposable; } if (disp != null) { disp.Dispose(); } } internal static void Dispose(object input) { if (input is IEnumerable e) { foreach (object obj in e) { DisposeObject(obj); } } else { DisposeObject(input); } } /// <summary> /// Get list of volume info classes. /// </summary> /// <returns>The volume information classes.</returns> public static IEnumerable<KeyValuePair<string, int>> GetFsVolumeInfoClass() { List<KeyValuePair<string, int>> ret = new List<KeyValuePair<string, int>>(); foreach (var name in Enum.GetValues(typeof(FsInformationClass))) { ret.Add(new KeyValuePair<string, int>(name.ToString(), (int)name)); } return ret.AsReadOnly(); } private static NtToken GetSystemToken() { NtToken.EnableDebugPrivilege(); using (var ps = NtProcess.GetProcesses(ProcessAccessRights.QueryLimitedInformation).ToDisposableList()) { Sid local_system = KnownSids.LocalSystem; foreach (var p in ps) { using (var result = NtToken.OpenProcessToken(p, TokenAccessRights.Query | TokenAccessRights.Duplicate, false)) { if (!result.IsSuccess) continue; var token = result.Result; if (token.User.Sid == local_system && !token.Filtered && token.GetPrivilege(TokenPrivilegeValue.SeTcbPrivilege) != null && token.IntegrityLevel == TokenIntegrityLevel.System) { using (var imp_token = token.DuplicateToken(SecurityImpersonationLevel.Impersonation)) { if (imp_token.SetPrivilege(TokenPrivilegeValue.SeTcbPrivilege, PrivilegeAttributes.Enabled)) { using (imp_token.Impersonate()) { return Win32Security.LsaLogonUser("SYSTEM", "NT AUTHORITY", null, SecurityLogonType.Service, Logon32Provider.Default, false).GetResultOrDefault(); } } } } } } } return null; } private static Lazy<NtToken> _system_token = new Lazy<NtToken>(GetSystemToken); internal static ThreadImpersonationContext ImpersonateSystem() { using (var token = _system_token.Value?.DuplicateToken(SecurityImpersonationLevel.Impersonation)) { if (token == null) throw new ArgumentException("Can't impersonate system token."); return token.Impersonate(); } } /// <summary> /// Get the signing level for an image file. /// </summary> /// <param name="path">The path to the image file.</param> /// <returns>The signing level.</returns> public static SigningLevel GetSigningLevel(string path) { using (var file = NtFile.Open(path, null, FileAccessRights.Execute, FileShareMode.Read | FileShareMode.Delete, FileOpenOptions.NonDirectoryFile)) { using (var sect = NtSection.CreateImageSection(file)) { using (var map = sect.MapRead()) { return map.ImageSigningLevel; } } } } } }
using UnityEngine; public abstract class State { protected readonly Transform _target; //For convenience protected readonly StateMachine _stateMachine; protected Color _color; public Color color { get { return _color; } } protected State (Transform pTarget, StateMachine pStateMachine) { //Store values _target = pTarget.transform; _stateMachine = pStateMachine; } public void UpdateState () { //Are we still okay with our current state? EvaluateState (); //Let the state do its thing Update (); } public abstract void Start (); public abstract void End (); protected abstract void Update (); private void EvaluateState () { bool canAttack = _stateMachine.CanAttackTarget(); bool canChase = _stateMachine.CanChaseTarget(); //Close enough to attack if (canAttack) _stateMachine.SetState<AttackState> (); //Close enough to chase else if (canChase) _stateMachine.SetState<ChaseState> (); //Can't find anything, let's wander around instead else _stateMachine.SetState<WanderingState> (); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Gensokyo.Xaml.Converters { class VisibilityBoxes { public static readonly object Visible = Visibility.Visible; public static readonly object Collapsed = Visibility.Collapsed; public static readonly object Hidden = Visibility.Hidden; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MvcMovie.Models; namespace WebfirstApplication.Models { public class WebfirstApplicationContext : DbContext { public WebfirstApplicationContext (DbContextOptions<WebfirstApplicationContext> options) : base(options) { } public DbSet<MvcMovie.Models.Movie> Movie { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using Grpc.Core; using Etg.Data.Entry; using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; namespace Etg.Service { public class EtgService : ServiceBase { private Grpc.Core.Server server; private IEnumerable<int> securePorts; private IEnumerable<int> insecurePorts; private SslServerCredentials serverCredentials; private readonly ILogger<EtgService> logger; private readonly EntryDataServiceImpl entryDataServiceImpl; public EtgService(EntryDataServiceImpl entryDataServiceImpl, ILoggerFactory loggerFactory, IOptions<EtgServiceOptions> optionsAccessor) { this.securePorts = optionsAccessor.Value.SecureChannelPorts; this.insecurePorts = optionsAccessor.Value.InsecureChannelPorts; serverCredentials = new SslServerCredentials( optionsAccessor.Value.ServerKeyCertPairs.Select(x => new KeyCertificatePair(x.Cert, x.Key)), optionsAccessor.Value.CACert, true); this.entryDataServiceImpl = entryDataServiceImpl; this.logger = loggerFactory.CreateLogger<EtgService>(); } public void StartServer() { logger.LogDebug("EtgService server is starting."); this.server = new Server() { Services = { EntryDataService.BindService(entryDataServiceImpl) }, }; foreach (int port in this.securePorts) { this.server.Ports.Add(new ServerPort("0.0.0.0", port, serverCredentials)); } foreach (int port in this.insecurePorts) { this.server.Ports.Add(new ServerPort("0.0.0.0", port, ServerCredentials.Insecure)); } server.Start(); logger.LogDebug("EtgService server listening on secure port {0}, insecure port {1}", String.Join(",", securePorts), String.Join(",", insecurePorts)); } public void StopServer() { logger.LogDebug("Shutting down EtgService."); this.server.ShutdownAsync().Wait(); } protected override void OnStart(string[] args) { this.StartServer(); base.OnStart(args); logger.LogInformation("Service started."); } protected override void OnStop() { this.StopServer(); base.OnStop(); logger.LogInformation("Service stopped."); } } public class EtgServiceOptions { public List<int> SecureChannelPorts { get; set; } public List<int> InsecureChannelPorts { get; set; } public string CACert { get; set; } public List<KeyCertPair> ServerKeyCertPairs { get; set;} public class KeyCertPair { public string Key { get; set; } public string Cert { get; set; } } } }