text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PanelTest { public partial class Form1 : Form { Boolean bShow = false; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { /* Graphics g = panel1.CreateGraphics(); Pen pen = new Pen(Color.Red, 10); g.DrawRectangle(pen, 10, 10, 50, 50); * */ bShow = !bShow; // 패널 컨트롤을 다시 그리기 위해 작성 panel1.Invalidate(); } private void panel1_Paint(object sender, PaintEventArgs e) { if(bShow) { Graphics g = panel1.CreateGraphics(); Pen pen = new Pen(Color.Red, 10); g.DrawRectangle(pen, 10, 10, 50, 50); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab3_2 { public static class StringExtensions { public static float StringToFloat(this string stringToParse) { float floated; if (!float.TryParse(stringToParse, out floated)) { floated = 0.0f; } return floated; } } }
using Topshelf; namespace CCCP.Telegram { class Program { static void Main(string[] args) { HostFactory.Run(hostConfig => { hostConfig.StartAutomaticallyDelayed(); hostConfig.UseLog4Net("log4net.config"); hostConfig.EnableServiceRecovery(serviceRecovery => { serviceRecovery.RestartService(5); }); hostConfig.Service<CoffeeCounterService>(serviceConfig => { serviceConfig.ConstructUsing(() => new CoffeeCounterService()); serviceConfig.WhenStarted(s => s.Start()); serviceConfig.WhenStopped(s => s.Stop()); }); }); } } }
using UnityEditor; using UnityEngine; namespace HT.Framework { [InternalSettingItem(HTFrameworkModule.AspectTrack)] internal sealed class SettingItemAspectTrack : SettingItemBase { private AspectTracker _aspectTracker; public override string Name { get { return "AspectTrack"; } } public override void OnBeginSetting() { base.OnBeginSetting(); GameObject aspectTracker = GameObject.Find("HTFramework/AspectTrack"); if (aspectTracker) { _aspectTracker = aspectTracker.GetComponent<AspectTracker>(); } } public override void OnSettingGUI() { base.OnSettingGUI(); if (_aspectTracker) { GUILayout.BeginHorizontal(); _aspectTracker.IsEnableAspectTrack = EditorGUILayout.Toggle("Is Enable Track", _aspectTracker.IsEnableAspectTrack); GUILayout.EndHorizontal(); if (_aspectTracker.IsEnableAspectTrack) { GUILayout.BeginHorizontal(); _aspectTracker.IsEnableIntercept = EditorGUILayout.Toggle("Is Enable Intercept", _aspectTracker.IsEnableIntercept); GUILayout.EndHorizontal(); } if (GUI.changed) { HasChanged(_aspectTracker); } } } public override void OnReset() { base.OnReset(); if (_aspectTracker) { _aspectTracker.IsEnableAspectTrack = false; _aspectTracker.IsEnableIntercept = false; HasChanged(_aspectTracker); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BussinessAccessLayer; using DataAccessLayer.Entities; using MySql.Data.MySqlClient; namespace PMS { public partial class UserControl2 : UserControl { string constring = "server=127.0.0.1;database=pharmacydb;uid=root;pwd=khan61814;"; BSalesmen obj = new BSalesmen(); Salesmen Sales = new Salesmen(); public UserControl2() { InitializeComponent(); } private void UserControl2_Load(object sender, EventArgs e) { BSalesmen bsale = new BSalesmen(); dataGridView1.DataSource = bsale.viewSale(); } private void button1_Click(object sender, EventArgs e) { Sales.ID = textBox1.Text; Sales.Name = textBox2.Text; Sales.PPhone = textBox3.Text; Sales.SPhone = textBox4.Text; Sales.Address = textBox5.Text; int count = obj.ISale(Sales); if (count > 0) { MessageBox.Show("Inserted!"); } BSalesmen bsale = new BSalesmen(); dataGridView1.DataSource = bsale.viewSale(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button2_Click(object sender, EventArgs e) { Sales.ID = textBox1.Text; Sales.Name = textBox2.Text; Sales.PPhone = textBox3.Text; Sales.SPhone = textBox4.Text; Sales.Address = textBox5.Text; int count = obj.USale(Sales); if (count > 0) { MessageBox.Show("Updated!"); } BSalesmen bsale = new BSalesmen(); dataGridView1.DataSource = bsale.viewSale(); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex]; textBox1.Text = row.Cells[0].Value.ToString(); textBox2.Text = row.Cells[1].Value.ToString(); textBox3.Text = row.Cells[2].Value.ToString(); textBox4.Text = row.Cells[3].Value.ToString(); textBox5.Text = row.Cells[4].Value.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MeetingRoomBot.Services { public class ApiCredential { private string _token = null; public ApiCredential(string token) { _token = token; } public override string ToString() { return _token; } } }
using System; using System.Windows.Forms; namespace PDV.UTIL.Components.Custom { public class ToolStripMenuItem : System.Windows.Forms.ToolStripMenuItem { public decimal IDItemMenu { get; set; } public ToolStripMenuItem() { } public static explicit operator ToolStripMenuItem(Control v) { return (ToolStripMenuItem)v; } } }
using System; namespace LOD.After { public class JoB { public int Salary { get; set; } public String Title { get; set; } public JoB(int salary,string designation) { Title = designation; Salary = salary; } internal void ChangeJobPositionTo(string newDesignatioName) { Title = newDesignatioName; } } }
using Moq; using Runpath.Common.HttpProcessor; using Runpath.Common.HttpProcessor.Interfaces; using Runpath.Dto.V1; using Runpath.Services.Tests.TestData; using Runpath.Services.V1; using Runpath.Services.V1.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Runpath.Services.Tests.V1 { public class PhotoServiceTests : IDisposable { private readonly MockRepository _mockRepository; private readonly Mock<IHttpRequestFactory> _mockHttpRequestFactory; private readonly Mock<IAlbumService> _mockAlbumService; public PhotoServiceTests() { _mockRepository = new MockRepository(MockBehavior.Strict); _mockHttpRequestFactory = _mockRepository.Create<IHttpRequestFactory>(); _mockAlbumService = _mockRepository.Create<IAlbumService>(); } public void Dispose() { _mockRepository.VerifyAll(); } private PhotoService CreateService() { return new PhotoService(_mockHttpRequestFactory.Object, _mockAlbumService.Object); } private async Task<List<PhotoViewModel>> SetupPhotoViewModels(int userId, string albumsFileLocation, string photosFileLocation) { // Arrange List<AlbumViewModel> albumViewModels = MockedData.GetAlbumViewModels(albumsFileLocation); _mockAlbumService.Setup(x => x.GetUserAlbums(userId)).Returns(Task.FromResult(albumViewModels.Where(a => a.UserId == userId).ToList())); List<PhotoViewModel> photoViewModels = MockedData.GetPhotoViewModels(photosFileLocation); HttpResponseMessage httpResponseMessage = new HttpResponseMessage() { Content = new JsonContent(photoViewModels) }; _mockHttpRequestFactory.Setup(x => x.Get(It.IsAny<string>())).Returns(Task.FromResult(httpResponseMessage)); var unitUnderTest = CreateService(); return await unitUnderTest.GetUserSpecificAlbumPhotos(userId); } [Theory] [InlineData(1, @"\InputFiles\AlbumsUserId1Data.json", @"\InputFiles\PhotosUserId1Data.json", 500)] [InlineData(6, @"\InputFiles\AlbumsUserId6Data.json", @"\InputFiles\PhotosUserId6Data.json", 500)] public async Task GetUserSpecificAlbumPhotos_StateUnderTest_ExpectedBehavior(int userId, string albumsFileLocation, string photosFileLocation, int expectedResult) { // Act var result = await SetupPhotoViewModels(userId, albumsFileLocation, photosFileLocation); // Assert Assert.True(result.Count == expectedResult); } [Theory] [InlineData(1, @"\InputFiles\AlbumsUserId1Data.json", @"\InputFiles\PhotosEmptyData.json", 0)] [InlineData(6, @"\InputFiles\AlbumsEmptyData.json", @"\InputFiles\PhotosUserId6Data.json", 0)] [InlineData(18, @"\InputFiles\AlbumsUserId6Data.json", @"\InputFiles\PhotosUserId6Data.json", 0)] public async Task GetUserSpecificAlbumPhotos_StateUnderTest_EmptyData_ExpectedBehavior(int userId, string albumsFileLocation, string photosFileLocation, int expectedResult) { // Act var result = await SetupPhotoViewModels(userId, albumsFileLocation, photosFileLocation); // Assert Assert.True(result.Count == expectedResult); } } }
using System; using System.Collections.Generic; using System.Text; namespace Nm.Reservation { public static class ReservationDbProperties { public const string ConnectionStringName = "NmReservation"; public static string DbTalbePrefix = "Nm";//暂时未使用 } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class SingleState : MonoBehaviour { int m_Index; public Image m_ImageCoin; public Text m_PrizeText; public Image m_CircleImage; public Image m_LineImage; public Sprite[] m_SpriteList; public GameObject m_Pivot; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void SetIndex(int index) { m_Index = index; if (index == GameConfig.Instance.GetNumberOfPvEStage()) { transform.FindChild("ImageCircle").gameObject.GetComponent<Image>().enabled = false; } m_PrizeText.text = GameConfig.Instance.GetSingleReward(index - 1).ToString(); } public void SetCompleted() { } public void Refresh() { m_Pivot.SetActive(false); PlayerProfile pl = GameManager.Instance.GetPlayerProfile(); Debug.Log("PVEStage: " + pl.m_CurrentPVEStage); if (m_Index <= pl.m_CurrentPVEStage) { m_CircleImage.sprite = m_SpriteList[3]; if (m_Index == pl.m_CurrentPVEStage) { m_LineImage.sprite = m_SpriteList[1]; } else { m_LineImage.sprite = m_SpriteList[1]; } } else { if (m_Index == pl.m_CurrentPVEStage + 1) { m_Pivot.SetActive(true); } m_CircleImage.sprite = m_SpriteList[2]; m_LineImage.sprite = m_SpriteList[0]; } if (pl.m_PVEState[m_Index - 1] == 1) { m_ImageCoin.sprite = m_SpriteList[4]; } } }
/* *************************************************************** * 프로그램 명 : Round1Prac.cs * 작성자 : 최은정 (이송이, 류서현, 신은지, 최세화, 홍예지) * 최조 작성일 : 2019년 12월 02일 * 최종 작성일 : 2019년 12월 07일 * 프로그램 설명 : Round1의 연습 단계에 알맞게 창을 구성한다. * 프로그램 흐름 : 도형1 출력(한번에)-> 맞을 때까지 검사 -> 맞으면 o 출력 * -> 도형2 출력(한번에)-> 맞을 때까지 검사 -> 맞으면 o 출력 * *************************************************************** */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class Round1Prac : MonoBehaviour { public GameObject ingredient1; public GameObject ingredient2; public GameObject correct; public GameObject wrong; Container situ; public void Start() { situ = GameObject.Find("Situation").GetComponent<Container>(); Invoke("Round1prac", 8); } void Round1prac() { Invoke("ShowShape1", 1); } void ShowShape1() { ingredient1.SetActive(true); //while (true) //{ // if(알맞은 동작 인식) { // correct.SetActive(true); // break; // } //} Invoke("ShowShape2", 2); } void ShowShape2() { correct.SetActive(false); ingredient1.SetActive(false); ingredient2.SetActive(true); //while (true) //{ // if(알맞은 동작 인식) { // correct.SetActive(true); // break; // } //} situ.situation = "RD1REAL"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Collections; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.Data.Sql; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; /// <summary> /// Summary description for Class_City /// </summary> public class Class_City { string connStr = ConfigurationManager.ConnectionStrings["SCMCon"].ConnectionString; string BizCon = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString; public Class_City() { } // from cities for search// public DataSet get_SourceCities() { DataSet ds = new DataSet(); ds.Clear(); using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand comm = new SqlCommand("get_CityAll", conn)) { SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; try { conn.Open(); ada.Fill(ds, "CityList"); } catch (Exception err) { } finally { conn.Close(); } } } return ds; } ///Insert Record into City Distance Table /// public Int32 Insert_CityDistance(Int32 obj_SourceID,Int32 obj_DestinationID,Int32 obj_Distance) { int resp = 0; using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand comm = new SqlCommand("Insert_CityDistance", conn)) { SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; ada.SelectCommand.Parameters.AddWithValue("@obj_SourceCityID", obj_SourceID); ada.SelectCommand.Parameters.AddWithValue("@obj_DestinationCityID", obj_DestinationID); ada.SelectCommand.Parameters.AddWithValue("@obj_Distance", obj_Distance); try { conn.Open(); ada.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception err) { resp = 0; } finally { conn.Close(); comm.Dispose(); ada.Dispose(); } } } return resp; } // //Retrieving Mobile No from Post Ad Table by Ad ID----****************** public ArrayList get_CityDistanceBySourceCityID_DestinationCityID(Int32 obj_SourceCityID,Int32 obj_DestinationCityID) { Int32 resp = 3; ArrayList arr = new ArrayList(); arr.Clear(); using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand comm = new SqlCommand("get_CityDistanceBySourceCityID_DestinationCityID", conn)) { SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; ada.SelectCommand.Parameters.AddWithValue("@obj_SourceCityID", obj_SourceCityID); ada.SelectCommand.Parameters.AddWithValue("@obj_DestinationCityID", obj_DestinationCityID); try { conn.Open(); SqlDataReader dr = ada.SelectCommand.ExecuteReader(); if (dr.HasRows) { if (dr.Read()) { if (!dr.IsDBNull(0)) { resp = 1; } else { resp = 0; } } else { resp = 0; } } else { resp = 0; } dr.Close(); } catch (Exception err) { resp = 0; } finally { conn.Close(); } } } arr.Add(resp); return arr; } //get the distance public ArrayList get_citydistance(Int32 obj_SourceCityID, Int32 obj_DestinationCityID) { Int32 resp = 3; ArrayList arr = new ArrayList(); string src, dest, dist; arr.Clear(); using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand comm = new SqlCommand("get_citydistance", conn)) { SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; ada.SelectCommand.Parameters.AddWithValue("@obj_SourcecityID", obj_SourceCityID); ada.SelectCommand.Parameters.AddWithValue("@obj_DestcityID", obj_DestinationCityID); try { conn.Open(); SqlDataReader dr = ada.SelectCommand.ExecuteReader(); if (dr.HasRows) { if (dr.Read()) { if (!dr.IsDBNull(0)) { src = dr[1].ToString().Trim(); dest = dr[2].ToString().Trim(); dist = dr[3].ToString().Trim(); resp = 1; arr.Add(resp); arr.Add(src); arr.Add(dest); arr.Add(dist); } else { resp = 0; arr.Add(resp); } } else { resp = 0; arr.Add(resp); } } else { resp = 0; arr.Add(resp); } dr.Close(); } catch (Exception err) { resp = 0; arr.Add(resp); } finally { conn.Close(); } } } return arr; } //Insert Route Chart Master public Int32 Insert_Bizconnect_RouteChartMaster(int RouteID, int TransporterID, string fromloc, string toloc, int trucktypeid, int citydistanceid, double costperkm, double totalcostpertruck) { int resp = 0; using (SqlConnection conn = new SqlConnection(BizCon)) { using (SqlCommand comm = new SqlCommand("Insert_BizConnect_RoutChartMaster", conn)) { try { conn.Open(); SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; ada.SelectCommand.Parameters.AddWithValue("@RouteID", RouteID); ada.SelectCommand.Parameters.AddWithValue("@TransporterID", TransporterID); ada.SelectCommand.Parameters.AddWithValue("@From_Loc", fromloc); ada.SelectCommand.Parameters.AddWithValue("@To_Loc", toloc); ada.SelectCommand.Parameters.AddWithValue("@Trucktype_ID",trucktypeid); ada.SelectCommand.Parameters.AddWithValue("@CityDistanceID", citydistanceid); ada.SelectCommand.Parameters.AddWithValue("@CostPerKM", costperkm); ada.SelectCommand.Parameters.AddWithValue("@TotalCostPerTruck", totalcostpertruck); ada.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception err) { } finally { conn.Close(); } } } return resp; } // get routeId public DataSet get_RouteID(int trasnsporterid,string fromcity,string tocity) { DataSet ds = new DataSet(); ds.Clear(); using (SqlConnection conn = new SqlConnection(BizCon)) { using (SqlCommand comm = new SqlCommand("Get_RouteID", conn)) { SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; ada.SelectCommand.Parameters.AddWithValue("@obj_TransporterID", trasnsporterid); ada.SelectCommand.Parameters.AddWithValue("@obj_FromCity", fromcity); ada.SelectCommand.Parameters.AddWithValue("@obj_ToCity", tocity); try { conn.Open(); ada.Fill(ds, "RouteID"); } catch (Exception err) { } finally { conn.Close(); } } } return ds; } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("CardBackPagingArrowBase")] public class CardBackPagingArrowBase : MonoBehaviour { public CardBackPagingArrowBase(IntPtr address) : this(address, "CardBackPagingArrowBase") { } public CardBackPagingArrowBase(IntPtr address, string className) : base(address, className) { } public void EnablePaging(bool enable) { object[] objArray1 = new object[] { enable }; base.method_8("EnablePaging", objArray1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OOPPrinciplesPart1 { class Student : Person, IComment { public string Comment { get; set; } public int ClassNumber { get; set; } public Student() { } } }
namespace UmbracoMapperified.Web.Handlers { using System.Collections.Generic; using System.Linq; using UmbracoMapperified.Web.Helpers; using UmbracoMapperified.Web.Infrastructure.Handlers; using UmbracoMapperified.Web.ViewModels; using UmbracoMapperified.Web.ViewModels.Partials; using Umbraco.Core.Models; using Umbraco.Web; using Zone.UmbracoMapper; /// <summary> /// Handler for mapping the <see cref="LatestNewsWidgetViewModel"/> partial view model /// </summary> public class LatestNewsWidgetHandler : BaseHandler, IHandler<LatestNewsWidgetViewModel> { public LatestNewsWidgetHandler(IUmbracoMapper mapper) : base(mapper) { } public LatestNewsWidgetHandler(IUmbracoMapper mapper, IPublishedContent rootNode) : base(mapper, rootNode) { } /// <summary> /// Processes the mapping from the content to to the partial page view model /// </summary> /// <param name="to">Partial page view model to map to</param> public void Handle(LatestNewsWidgetViewModel to) { var newsOverviewPage = GetNewsOverviewPage(); if (newsOverviewPage == null) { return; } Mapper.Map(newsOverviewPage, to); var newsItems = GetLatestNewsItems(newsOverviewPage); Mapper.MapCollection(newsItems, to.NewsItems); } /// <summary> /// Helper to retrieve the latest news items /// </summary> /// <param name="newsOverviewPage">News overview page instance</param> /// <returns>List of latest news content items</returns> private static IEnumerable<IPublishedContent> GetLatestNewsItems(IPublishedContent newsOverviewPage) { return newsOverviewPage.Descendants("umbNewsItem") .MostRecent(5) .ToList(); } } }
using System; using System.Net; using System.Net.Sockets; using System.Threading; namespace Game.Network { public class GameClient: BaseClient { public IPEndPoint iPEndPoint { get; set; } ///// <summary> ///// 连接完成时引发事件。 ///// </summary> public event EventHandler<SocketAsyncEventArgs> connectSucess; /// <summary> /// 连接发生错误 /// </summary> public event EventHandler<SocketAsyncEventArgs> connectError; public GameClient() : base() { Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } public void ConnectAsync(string ip, int port) { //判断是否已连接 if (IsConnected) throw new InvalidOperationException("已连接至服务器。"); else { iPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); StartConnect(null); } } private void StartConnect(SocketAsyncEventArgs e) { if (e == null) { e = new SocketAsyncEventArgs() { RemoteEndPoint = iPEndPoint }; e.Completed += ConnectEventArg_Completed; e.UserToken = this; } bool willRaiseEvent = Socket.ConnectAsync(e); //如果没有挂起 if (!willRaiseEvent) ProcessConnect(e); } private void ConnectEventArg_Completed(object sender, SocketAsyncEventArgs e) { ProcessConnect(e); } private void ProcessConnect(SocketAsyncEventArgs e) { try { if (e.SocketError == SocketError.Success) { connectSucess?.Invoke(this, e); ReceiveAsync(); } else CloseClientSocket(e); } catch (Exception E) { Console.WriteLine(E.Message); } } public void Connect(string ip, int port) { Socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); } public void Send(byte[] buffer) { try { Socket.Send(Handler.ProcessWrite(buffer)); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// 设置心跳 /// </summary> private void SetHeartBeat() { //byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };// 首次探测时间20 秒, 间隔侦测时间2 秒 byte[] inValue = new byte[] { 1, 0, 0, 0, 0x88, 0x13, 0, 0, 0xd0, 0x07, 0, 0 };// 首次探测时间5 秒, 间隔侦测时间2 秒 Socket.IOControl(IOControlCode.KeepAliveValues, inValue, null); } } }
using LuaInterface; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Threading; using UnityEngine; namespace SLua { public class LuaState : IDisposable { private struct UnrefPair { public LuaState.UnRefAction act; public int r; } public delegate byte[] LoaderDelegate(string fn); public delegate void OutputDelegate(string msg); public delegate void UnRefAction(IntPtr l, int r); private IntPtr l_; private int mainThread; internal WeakDictionary<int, LuaDelegate> delgateMap = new WeakDictionary<int, LuaDelegate>(); public static LuaState.LoaderDelegate loaderDelegate; public static LuaState.OutputDelegate logDelegate; public static LuaState.OutputDelegate errorDelegate; private Queue<LuaState.UnrefPair> refQueue; public int PCallCSFunctionRef; public static LuaState main; private static Dictionary<IntPtr, LuaState> statemap = new Dictionary<IntPtr, LuaState>(); private static IntPtr oldptr = IntPtr.Zero; private static LuaState oldstate = null; public static LuaCSFunction errorFunc = new LuaCSFunction(LuaState.errorReport); public IntPtr L { get { if (!this.isMainThread()) { SluaLogger.LogError("Can't access lua in bg thread"); throw new Exception("Can't access lua in bg thread"); } if (this.l_ == IntPtr.Zero) { SluaLogger.LogError("LuaState had been destroyed, can't used yet"); throw new Exception("LuaState had been destroyed, can't used yet"); } return this.l_; } set { this.l_ = value; } } public IntPtr handle { get { return this.L; } } public object this[string path] { get { return this.getObject(path); } set { this.setObject(path, value); } } public LuaState() { this.mainThread = Thread.get_CurrentThread().get_ManagedThreadId(); this.L = LuaDLL.luaL_newstate(); LuaState.statemap.set_Item(this.L, this); if (LuaState.main == null) { LuaState.main = this; } this.refQueue = new Queue<LuaState.UnrefPair>(); ObjectCache.make(this.L); LuaDLL.lua_atpanic(this.L, new LuaCSFunction(LuaState.panicCallback)); LuaDLL.luaL_openlibs(this.L); string chunk = "\nlocal assert = assert\nlocal function check(ok,...)\n\tassert(ok, ...)\n\treturn ...\nend\nreturn function(cs_func)\n\treturn function(...)\n\t\treturn check(cs_func(...))\n\tend\nend\n"; LuaDLL.lua_dostring(this.L, chunk); this.PCallCSFunctionRef = LuaDLL.luaL_ref(this.L, LuaIndexes.LUA_REGISTRYINDEX); LuaState.pcall(this.L, new LuaCSFunction(LuaState.init)); } public bool isMainThread() { return Thread.get_CurrentThread().get_ManagedThreadId() == this.mainThread; } public static LuaState get(IntPtr l) { if (l == LuaState.oldptr) { return LuaState.oldstate; } LuaState result; if (LuaState.statemap.TryGetValue(l, ref result)) { LuaState.oldptr = l; LuaState.oldstate = result; return result; } LuaDLL.lua_getglobal(l, "__main_state"); if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); return null; } IntPtr intPtr = LuaDLL.lua_touserdata(l, -1); LuaDLL.lua_pop(l, 1); if (intPtr != l) { return LuaState.get(intPtr); } return null; } [MonoPInvokeCallback(typeof(LuaCSFunction))] private static int init(IntPtr L) { LuaDLL.lua_pushlightuserdata(L, L); LuaDLL.lua_setglobal(L, "__main_state"); LuaDLL.lua_pushcfunction(L, new LuaCSFunction(LuaState.print)); LuaDLL.lua_setglobal(L, "print"); LuaDLL.lua_pushcfunction(L, new LuaCSFunction(LuaState.pcall)); LuaDLL.lua_setglobal(L, "pcall"); LuaState.pushcsfunction(L, new LuaCSFunction(LuaState.import)); LuaDLL.lua_setglobal(L, "import"); string str = "\nlocal resume = coroutine.resume\nlocal function check(co, ok, err, ...)\n\tif not ok then UnityEngine.Debug.LogError(debug.traceback(co,err)) end\n\treturn ok, err, ...\nend\ncoroutine.resume=function(co,...)\n\treturn check(co, resume(co,...))\nend\n"; LuaState.get(L).doString(str); LuaState.get(L).doString("if jit then require('jit.opt').start('sizemcode=256','maxmcode=256') for i=1,1000 do end end"); LuaState.pushcsfunction(L, new LuaCSFunction(LuaState.dofile)); LuaDLL.lua_setglobal(L, "dofile"); LuaState.pushcsfunction(L, new LuaCSFunction(LuaState.loadfile)); LuaDLL.lua_setglobal(L, "loadfile"); LuaState.pushcsfunction(L, new LuaCSFunction(LuaState.loader)); int index = LuaDLL.lua_gettop(L); LuaDLL.lua_getglobal(L, "package"); LuaDLL.lua_getfield(L, -1, "searchers"); int num = LuaDLL.lua_gettop(L); for (int i = LuaDLL.lua_rawlen(L, num) + 1; i > 1; i--) { LuaDLL.lua_rawgeti(L, num, (long)(i - 1)); LuaDLL.lua_rawseti(L, num, (long)i); } LuaDLL.lua_pushvalue(L, index); LuaDLL.lua_rawseti(L, num, 1L); LuaDLL.lua_settop(L, 0); return 0; } public void Close() { if (this.L != IntPtr.Zero && LuaState.main == this) { SluaLogger.Log("Finalizing Lua State."); LuaDLL.lua_close(this.L); ObjectCache.del(this.L); ObjectCache.clear(); LuaState.statemap.Clear(); LuaState.oldptr = IntPtr.Zero; LuaState.oldstate = null; this.L = IntPtr.Zero; LuaState.main = null; } } public void Dispose() { this.Dispose(true); GC.Collect(); GC.WaitForPendingFinalizers(); } public virtual void Dispose(bool dispose) { if (dispose) { this.Close(); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int errorReport(IntPtr L) { LuaDLL.lua_getglobal(L, "debug"); LuaDLL.lua_getfield(L, -1, "traceback"); LuaDLL.lua_pushvalue(L, 1); LuaDLL.lua_pushnumber(L, 2.0); LuaDLL.lua_call(L, 2, 1); LuaDLL.lua_remove(L, -2); SluaLogger.LogError(LuaDLL.lua_tostring(L, -1)); if (LuaState.errorDelegate != null) { LuaState.errorDelegate(LuaDLL.lua_tostring(L, -1)); } LuaDLL.lua_pop(L, 1); return 0; } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int import(IntPtr l) { int result; try { LuaDLL.luaL_checktype(l, 1, LuaTypes.LUA_TSTRING); string text = LuaDLL.lua_tostring(l, 1); string[] array = text.Split(new char[] { '.' }); LuaDLL.lua_pushglobaltable(l); for (int i = 0; i < array.Length; i++) { LuaDLL.lua_getfield(l, -1, array[i]); if (!LuaDLL.lua_istable(l, -1)) { result = LuaObject.error(l, "expect {0} is type table", array); return result; } LuaDLL.lua_remove(l, -2); } LuaDLL.lua_pushnil(l); while (LuaDLL.lua_next(l, -2) != 0) { string text2 = LuaDLL.lua_tostring(l, -2); LuaDLL.lua_getglobal(l, text2); if (!LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); result = LuaObject.error(l, "{0} had existed, import can't overload it.", new object[] { text2 }); return result; } LuaDLL.lua_pop(l, 1); LuaDLL.lua_setglobal(l, text2); } LuaDLL.lua_pop(l, 1); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int pcall(IntPtr L) { if (LuaDLL.lua_type(L, 1) != LuaTypes.LUA_TFUNCTION) { return LuaObject.error(L, "arg 1 expect function"); } LuaDLL.luaL_checktype(L, 1, LuaTypes.LUA_TFUNCTION); int num = LuaDLL.lua_pcall(L, LuaDLL.lua_gettop(L) - 1, LuaDLL.LUA_MULTRET, 0); LuaDLL.lua_pushboolean(L, num == 0); LuaDLL.lua_insert(L, 1); return LuaDLL.lua_gettop(L); } internal static void pcall(IntPtr l, LuaCSFunction f) { int num = LuaObject.pushTry(l); LuaDLL.lua_pushcfunction(l, f); if (LuaDLL.lua_pcall(l, 0, 0, num) != 0) { LuaDLL.lua_pop(l, 1); } LuaDLL.lua_remove(l, num); } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int print(IntPtr L) { int num = LuaDLL.lua_gettop(L); string text = string.Empty; LuaDLL.lua_getglobal(L, "tostring"); for (int i = 1; i <= num; i++) { if (i > 1) { text += " "; } LuaDLL.lua_pushvalue(L, -1); LuaDLL.lua_pushvalue(L, i); LuaDLL.lua_call(L, 1, 1); text += LuaDLL.lua_tostring(L, -1); LuaDLL.lua_pop(L, 1); } LuaDLL.lua_settop(L, num); SluaLogger.Log(text); if (LuaState.logDelegate != null) { LuaState.logDelegate(text); } return 0; } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int loadfile(IntPtr L) { LuaState.loader(L); if (LuaDLL.lua_isnil(L, -1)) { string text = LuaDLL.lua_tostring(L, 1); return LuaObject.error(L, "Can't find {0}", new object[] { text }); } return 2; } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int dofile(IntPtr L) { int num = LuaDLL.lua_gettop(L); LuaState.loader(L); if (!LuaDLL.lua_toboolean(L, -2)) { return 2; } if (LuaDLL.lua_isnil(L, -1)) { string text = LuaDLL.lua_tostring(L, 1); return LuaObject.error(L, "Can't find {0}", new object[] { text }); } int num2 = LuaDLL.lua_gettop(L); LuaDLL.lua_call(L, 0, LuaDLL.LUA_MULTRET); num2 = LuaDLL.lua_gettop(L); return num2 - num; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int panicCallback(IntPtr l) { string text = string.Format("unprotected error in call to Lua API ({0})", LuaDLL.lua_tostring(l, -1)); throw new Exception(text); } public static void pushcsfunction(IntPtr L, LuaCSFunction function) { LuaDLL.lua_getref(L, LuaState.get(L).PCallCSFunctionRef); LuaDLL.lua_pushcclosure(L, Marshal.GetFunctionPointerForDelegate(function), 0); LuaDLL.lua_call(L, 1, 1); } public object doString(string str) { byte[] bytes = Encoding.get_UTF8().GetBytes(str); object result; if (this.doBuffer(bytes, "temp buffer", out result)) { return result; } return null; } public object doString(string str, string chunkname) { byte[] bytes = Encoding.get_UTF8().GetBytes(str); object result; if (this.doBuffer(bytes, chunkname, out result)) { return result; } return null; } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int loader(IntPtr L) { string text = LuaDLL.lua_tostring(L, 1); byte[] array = LuaState.loadFile(text); if (array == null) { LuaObject.pushValue(L, true); LuaDLL.lua_pushnil(L); return 2; } if (LuaDLL.luaL_loadbuffer(L, array, array.Length, "@" + text) == 0) { LuaObject.pushValue(L, true); LuaDLL.lua_insert(L, -2); return 2; } string err = LuaDLL.lua_tostring(L, -1); return LuaObject.error(L, err); } public object doFile(string fn) { byte[] array = LuaState.loadFile(fn); if (array == null) { SluaLogger.LogError(string.Format("Can't find {0}", fn)); return null; } object result; if (this.doBuffer(array, "@" + fn, out result)) { return result; } return null; } public bool doBuffer(byte[] bytes, string fn, out object ret) { ret = null; int num = LuaObject.pushTry(this.L); if (LuaDLL.luaL_loadbuffer(this.L, bytes, bytes.Length, fn) != 0) { string text = LuaDLL.lua_tostring(this.L, -1); LuaDLL.lua_pop(this.L, 2); throw new Exception(text); } if (LuaDLL.lua_pcall(this.L, 0, LuaDLL.LUA_MULTRET, num) != 0) { LuaDLL.lua_pop(this.L, 2); return false; } LuaDLL.lua_remove(this.L, num); ret = this.topObjects(num - 1); return true; } internal static byte[] loadFile(string fn) { byte[] result; try { byte[] array; if (LuaState.loaderDelegate != null) { array = LuaState.loaderDelegate(fn); } else { fn = fn.Replace(".", "/"); TextAsset textAsset = (TextAsset)Resources.Load(fn); if (textAsset == null) { result = null; return result; } array = textAsset.get_bytes(); } if (array != null) { DebugInterface.require(fn, array); } result = array; } catch (Exception ex) { throw new Exception(ex.get_Message()); } return result; } internal object getObject(string key) { LuaDLL.lua_pushglobaltable(this.L); object @object = this.getObject(key.Split(new char[] { '.' })); LuaDLL.lua_pop(this.L, 1); return @object; } internal void setObject(string key, object v) { LuaDLL.lua_pushglobaltable(this.L); this.setObject(key.Split(new char[] { '.' }), v); LuaDLL.lua_pop(this.L, 1); } internal object getObject(string[] remainingPath) { object obj = null; for (int i = 0; i < remainingPath.Length; i++) { LuaDLL.lua_pushstring(this.L, remainingPath[i]); LuaDLL.lua_gettable(this.L, -2); obj = this.getObject(this.L, -1); LuaDLL.lua_remove(this.L, -2); if (obj == null) { break; } } return obj; } internal object getObject(int reference, string field) { int newTop = LuaDLL.lua_gettop(this.L); LuaDLL.lua_getref(this.L, reference); object @object = this.getObject(field.Split(new char[] { '.' })); LuaDLL.lua_settop(this.L, newTop); return @object; } internal object getObject(int reference, int index) { if (index >= 1) { int newTop = LuaDLL.lua_gettop(this.L); LuaDLL.lua_getref(this.L, reference); LuaDLL.lua_rawgeti(this.L, -1, (long)index); object @object = this.getObject(this.L, -1); LuaDLL.lua_settop(this.L, newTop); return @object; } throw new IndexOutOfRangeException(); } internal object getObject(int reference, object field) { int newTop = LuaDLL.lua_gettop(this.L); LuaDLL.lua_getref(this.L, reference); LuaObject.pushObject(this.L, field); LuaDLL.lua_gettable(this.L, -2); object @object = this.getObject(this.L, -1); LuaDLL.lua_settop(this.L, newTop); return @object; } internal void setObject(string[] remainingPath, object o) { int newTop = LuaDLL.lua_gettop(this.L); for (int i = 0; i < remainingPath.Length - 1; i++) { LuaDLL.lua_pushstring(this.L, remainingPath[i]); LuaDLL.lua_gettable(this.L, -2); } LuaDLL.lua_pushstring(this.L, remainingPath[remainingPath.Length - 1]); LuaObject.pushVar(this.L, o); LuaDLL.lua_settable(this.L, -3); LuaDLL.lua_settop(this.L, newTop); } internal void setObject(int reference, string field, object o) { int newTop = LuaDLL.lua_gettop(this.L); LuaDLL.lua_getref(this.L, reference); this.setObject(field.Split(new char[] { '.' }), o); LuaDLL.lua_settop(this.L, newTop); } internal void setObject(int reference, int index, object o) { if (index >= 1) { int newTop = LuaDLL.lua_gettop(this.L); LuaDLL.lua_getref(this.L, reference); LuaObject.pushVar(this.L, o); LuaDLL.lua_rawseti(this.L, -2, (long)index); LuaDLL.lua_settop(this.L, newTop); return; } throw new IndexOutOfRangeException(); } internal void setObject(int reference, object field, object o) { int newTop = LuaDLL.lua_gettop(this.L); LuaDLL.lua_getref(this.L, reference); LuaObject.pushObject(this.L, field); LuaObject.pushObject(this.L, o); LuaDLL.lua_settable(this.L, -3); LuaDLL.lua_settop(this.L, newTop); } internal object topObjects(int from) { int num = LuaDLL.lua_gettop(this.L); int num2 = num - from; if (num2 == 0) { return null; } if (num2 == 1) { object result = LuaObject.checkVar(this.L, num); LuaDLL.lua_pop(this.L, 1); return result; } object[] array = new object[num2]; for (int i = 1; i <= num2; i++) { array[i - 1] = LuaObject.checkVar(this.L, from + i); } LuaDLL.lua_settop(this.L, from); return array; } private object getObject(IntPtr l, int p) { p = LuaDLL.lua_absindex(l, p); return LuaObject.checkVar(l, p); } public LuaFunction getFunction(string key) { return (LuaFunction)this[key]; } public LuaTable getTable(string key) { return (LuaTable)this[key]; } public void gcRef(LuaState.UnRefAction act, int r) { LuaState.UnrefPair unrefPair = default(LuaState.UnrefPair); unrefPair.act = act; unrefPair.r = r; Queue<LuaState.UnrefPair> queue = this.refQueue; lock (queue) { this.refQueue.Enqueue(unrefPair); } } public void checkRef() { int num = 0; Queue<LuaState.UnrefPair> queue = this.refQueue; lock (queue) { num = this.refQueue.get_Count(); } for (int i = 0; i < num; i++) { Queue<LuaState.UnrefPair> queue2 = this.refQueue; LuaState.UnrefPair unrefPair; lock (queue2) { unrefPair = this.refQueue.Dequeue(); } unrefPair.act(this.L, unrefPair.r); } } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; //using System.Windows.Forms; namespace Almacen { public class Consultas { Conexion conexcion = new Conexion(); SqlDataAdapter dataa = new SqlDataAdapter(); DataSet datas = new DataSet(); Boolean estado_conexcion = false; SqlCommand registro; public SqlDataReader datos; SqlDataReader Lista; public int id; public int i; public int d; public Boolean inicio_sesion(int user, string pass) { if (i == 0) { SqlCommand conectar;//SqlCommand → escribe la consulta que se quiere ejecutar conectar = new SqlCommand("select id_admin, pass from administrador where id_admin=@id_admin and pass=@pass", conexcion.conectar());//consulta SqlServer conectar.Parameters.AddWithValue("@id_admin", user.ToString());//especifica el tipo de comando conectar.Parameters.AddWithValue("@pass", pass);//pasa los valores que tiene el metodo,el de abajo tambien ↓ conectar.ExecuteNonQuery();//ejecuta la consulta Sql try { SqlDataAdapter da = new SqlDataAdapter(conectar);//asocia la consulta que se va a ejecutar da.Fill(datas, "administrador");//especifica de que tabla se van a tomar(llenar) los datos. Fill → llenar DataRow dr;//hace referencia a las filas de una tabla dr = datas.Tables["administrador"].Rows[0];//asigna una fila a la variable if (user.ToString() == dr["id_admin"].ToString() & pass == dr["pass"].ToString()) { WebForm1 wf = new WebForm1(); // wf.identificacion = user ; d = 1; estado_conexcion = true; } else { i = 1; } } catch (Exception ex) { i = 1; if (i == 0) { // MessageBox.Show(ex.Message); } } } if (i == 1) { SqlCommand conectar;//SqlCommand → escribe la consulta que se quiere ejecutar conectar = new SqlCommand("select id_user, pass from usuarios where id_user=@id_user and pass=@pass", conexcion.conectar());//consulta SqlServer conectar.Parameters.AddWithValue("@id_user", user.ToString());//especifica el tipo de comando conectar.Parameters.AddWithValue("@pass", pass);//pasa los valores que tiene el metodo,el de abajo tambien ↓ conectar.ExecuteNonQuery();//ejecuta la consulta Sql try { SqlDataAdapter da = new SqlDataAdapter(conectar);//asocia la consulta que se va a ejecutar da.Fill(datas, "usuarios");//especifica de que tabla se van a tomar(llenar) los datos. Fill → llenar DataRow dr;//hace referencia a las filas de una tabla dr = datas.Tables["usuarios"].Rows[0];//asigna una fila a la variable if (user.ToString() == dr["id_user"].ToString() & pass == dr["pass"].ToString()) { d = 2; estado_conexcion = true; } else { i = 1; } } catch (Exception ex) { i = 2; if (i == 0) { //MessageBox.Show(ex.Message); } } } if (i == 2) { //MessageBox.Show("no esta registrado", "aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return estado_conexcion; } public SqlCommand registro_admin(string user, string pass, string nombre, string apellido) { try { registro = new SqlCommand("insert into administrador(id_admin,pass,nombre,apellido) values (@id_admin,@pass,@nombre,@apellido)", conexcion.conectar()); registro.CommandType = CommandType.Text; registro.Parameters.AddWithValue("@id_admin", SqlDbType.VarChar).Value = user; registro.Parameters.AddWithValue("@pass", SqlDbType.VarChar).Value = pass; registro.Parameters.AddWithValue("@nombre", SqlDbType.VarChar).Value = nombre; registro.Parameters.AddWithValue("@apellido", SqlDbType.VarChar).Value = apellido; registro.ExecuteNonQuery(); //MessageBox.Show("Usuario registrado con excito"); } catch (Exception ex) { //MessageBox.Show(ex.Message); } return registro; } public SqlCommand registro_compra(string user, string pass, string nombre, string apellido, string admin) { try { registro = new SqlCommand("insert into usuarios(id_user,pass,nombre,apellido,id_admin) values (@id_user,@pass,@nombre,@apellido,@id_admin)", conexcion.conectar()); registro.CommandType = CommandType.Text; registro.Parameters.AddWithValue("@id_user", SqlDbType.VarChar).Value = user; registro.Parameters.AddWithValue("@pass", SqlDbType.VarChar).Value = pass; registro.Parameters.AddWithValue("@nombre", SqlDbType.VarChar).Value = nombre; registro.Parameters.AddWithValue("@apellido", SqlDbType.VarChar).Value = apellido; registro.Parameters.AddWithValue("@id_admin", SqlDbType.VarChar).Value = admin; registro.ExecuteNonQuery(); } catch (Exception ex) {} return registro; } public SqlCommand registro_categorias(string user, string nombre, string id_admi) { try { registro = new SqlCommand("insert into categorias(id_categorias,nombre_categorias,id_admin) values (@id_categorias,@nombre_categorias,@id_admin)", conexcion.conectar()); registro.CommandType = CommandType.Text; registro.Parameters.AddWithValue("@id_categorias", SqlDbType.VarChar).Value = user; registro.Parameters.AddWithValue("@nombre_categorias", SqlDbType.VarChar).Value = nombre; registro.Parameters.AddWithValue("@id_admin", SqlDbType.VarChar).Value = id_admi; registro.ExecuteNonQuery(); //MessageBox.Show("Usuario registrado con excito"); } catch (Exception ex) { //MessageBox.Show(ex.Message); } return registro; } public void eliminar_admin(int user) { SqlCommand borrarctg = new SqlCommand("DELETE from categorias where id_admin=@id_admin", conexcion.conectar()); borrarctg.Parameters.AddWithValue("@id_admin", user); borrarctg.ExecuteNonQuery(); SqlCommand comando = new SqlCommand("DELETE from Administrador where id_admin=@id_admin", conexcion.conectar()); comando.Parameters.AddWithValue("@id_admin", user); comando.ExecuteNonQuery(); } public void eliminar_comprador(int user) { SqlCommand comando = new SqlCommand("DELETE from usuarios where id_user=@id_user", conexcion.conectar()); comando.Parameters.AddWithValue("@id_user", user); comando.ExecuteNonQuery(); } public void eliminar_categorias(int user) { SqlCommand comando = new SqlCommand("DELETE from categorias where id_categorias=@id_categorias", conexcion.conectar()); comando.Parameters.AddWithValue("@id_categorias", user); comando.ExecuteNonQuery(); } public void Modificar_admin(string user, string pass, string nombre, string apellido) { SqlCommand actualizar = new SqlCommand("update administrador set pass=@pass, nombre=@nombre, apellido=@apellido where id_admin=@id_admin", conexcion.conectar()); try { actualizar.Parameters.AddWithValue("@id_admin", user); actualizar.Parameters.AddWithValue("@pass", pass); actualizar.Parameters.AddWithValue("@nombre", nombre); actualizar.Parameters.AddWithValue("@apellido", apellido); actualizar.ExecuteNonQuery(); datas.Clear(); } catch (Exception e) { //MessageBox.Show(e.Message); } } public void Modificar_user(string user, string pass, string nombre, string apellido) { SqlCommand actualizar = new SqlCommand("update usuarios set pass=@pass, nombre=@nombre, apellido=@apellido where id_user=@id_user", conexcion.conectar()); try { actualizar.Parameters.AddWithValue("@id_user", user); actualizar.Parameters.AddWithValue("@pass", pass); actualizar.Parameters.AddWithValue("@nombre", nombre); actualizar.Parameters.AddWithValue("@apellido", apellido); actualizar.ExecuteNonQuery(); datas.Clear(); } catch (Exception e) { //MessageBox.Show(e.Message); } } public void Modificar_carat(string user, string nombre, string id_admin) { SqlCommand actualizar = new SqlCommand("update categorias set nombre_categorias=@nombre_categorias where id_categorias=@id_categorias", conexcion.conectar()); try { actualizar.Parameters.AddWithValue("@id_categorias", user); actualizar.Parameters.AddWithValue("@nombre_categorias", nombre); actualizar.Parameters.AddWithValue("@id_admin", id_admin); actualizar.ExecuteNonQuery(); datas.Clear(); } catch (Exception e) { //MessageBox.Show(e.Message); } } public void consultarid_cat(string nomb)// { DataSet ds = new DataSet(); SqlCommand consulta; consulta = new SqlCommand("select id_categorias from categorias where nombre_categorias=@nombre_categorias", conexcion.conectar()); consulta.CommandType = CommandType.Text; consulta.Parameters.AddWithValue("@nombre_categorias", nomb); consulta.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(consulta); da.Fill(ds, "categorias"); datos = consulta.ExecuteReader();//saca los datos de la tabla try { } catch (Exception error) { } } public void Lista_categorias(DropDownList cb) { cb.Items.Clear(); conexcion.conectar(); SqlCommand cmd = new SqlCommand("select nombre_categorias from categorias", conexcion.conectar()); Lista = cmd.ExecuteReader(); while (Lista.Read()) { cb.Items.Add(Lista[0].ToString()); } cb.Items.Insert(0, "Categorias"); cb.SelectedIndex = 0; } public SqlCommand registro_productos(string idprod, string idcat, string nombreprod, string precioprod) { try { registro = new SqlCommand("insert into productos(id_productos,id_categoria,nombre_productos,precio_productos) values (@id_productos,@id_categoria,@nombre_productos,@precio_productos)", conexcion.conectar()); registro.CommandType = CommandType.Text; registro.Parameters.AddWithValue("@id_productos", SqlDbType.VarChar).Value = idprod; registro.Parameters.AddWithValue("@id_categoria", SqlDbType.VarChar).Value = idcat; registro.Parameters.AddWithValue("@nombre_productos", SqlDbType.VarChar).Value = nombreprod; registro.Parameters.AddWithValue("@precio_productos", SqlDbType.Float).Value = precioprod; registro.ExecuteNonQuery(); //MessageBox.Show("Producto registrado con excito"); } catch (Exception ex) { // MessageBox.Show(ex.Message); } return registro; } } }
using System; namespace RemotingHelloWorld { public interface IHello { string Hello(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace pacman { public partial class PuppetMasterWindow : Form { public PuppetMasterWindow() { InitializeComponent(); tbChat.Text = ""; tbChat.ReadOnly = true; } private void tbMsg_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { PuppetMaster.read(tbMsg.Text); tbMsg.Text = ""; } } public void changeText(string input) { tbChat.Text = input; } private void PuppetMasterWindow_Load(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; using System.IO; using System.Text.RegularExpressions; using System.Web.Routing; namespace Inspinia_MVC5_SeedProject { public static class UrlHelperExtensions { public static string Action(this UrlHelper helper, string actionName, string controllerName, object routeValues, string protocol, bool defaultPort) { return Action(helper, actionName, controllerName, routeValues, protocol, null, defaultPort); } public static string Action(this UrlHelper helper, string actionName, string controllerName, object routeValues, string protocol, string hostName, bool defaultPort) { if (!defaultPort) { return helper.Action(actionName, controllerName, new RouteValueDictionary(routeValues), protocol, hostName); } string port = "80"; if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase)) { port = "443"; } Uri requestUrl = helper.RequestContext.HttpContext.Request.Url; string defaultPortRequestUrl = Regex.Replace(requestUrl.ToString(), @"(?<=:)\d+?(?=/)", port); Uri url = new Uri(new Uri(defaultPortRequestUrl, UriKind.Absolute), requestUrl.PathAndQuery); var requestContext = GetRequestContext(url); var urlHelper = new UrlHelper(requestContext, helper.RouteCollection); var values = new RouteValueDictionary(routeValues); values.Add("controller", controllerName); values.Add("action", actionName); return urlHelper.RouteUrl(null, values, protocol, hostName); } private static RequestContext GetRequestContext(Uri uri) { // Create a TextWriter with null stream as a backing stream // which doesn't consume resources using (var writer = new StreamWriter(Stream.Null)) { var request = new HttpRequest( filename: string.Empty, url: uri.ToString(), queryString: string.IsNullOrEmpty(uri.Query) ? string.Empty : uri.Query.Substring(1)); var response = new HttpResponse(writer); var httpContext = new HttpContext(request, response); var httpContextBase = new HttpContextWrapper(httpContext); return new RequestContext(httpContextBase, new RouteData()); } } } public static class HMTLHelperExtensions { public static string IsSelected(this HtmlHelper html, string controller = null, string action = null) { string cssClass = "active"; string currentAction = (string)html.ViewContext.RouteData.Values["action"]; string currentController = (string)html.ViewContext.RouteData.Values["controller"]; if (String.IsNullOrEmpty(controller)) controller = currentController; if (String.IsNullOrEmpty(action)) action = currentAction; return controller == currentController && action == currentAction ? cssClass : String.Empty; } } }
using System.Collections.Generic; namespace HseClass.Data.Entities { public class UserClass { public int UserId { get; set; } public int ClassRoomId { get; set; } } }
using System; namespace DataLayer { public static class Constantes { #region atributos #endregion #region // Utilerias public const string spCATConsultarParametro = "spCATConsultarParametro"; public const string spCATConsultarParametros = "spCATConsultarParametros"; public static string spCATConsultarElementosCatalogoSoloTexto = "spCATConsultarElementosCatalogoSoloTexto"; public const string spUTIRespaldarBaseDatos = "spUTIRespaldarBaseDatos"; // No se usa public const string spUTIObtenerFechaHoraServidor = "spUTIObtenerFechaHoraServidor"; public const String spCOMConsultarMensajes = "spCOMConsultarMensajes"; #endregion // Utilerias #region SPs public const String spApoyoDBAObtenerAccesos = "01spApoyoDBAObtenerAccesos"; public const String spApoyoDBAObteneAreas = "01spApoyoDBAObtenerAreas"; public const String spApoyoDBAObtenerTipoAccesos = "01spApoyoDBAObtenerTiposAcesos"; public const String spApoyoDBAObtenerPerfiles = "01spApoyoDBAObtenerPerfiles"; public const String spApoyoDBAEjecutarScript = "01spApoyoDBAEjecutarScript"; public const String spBitacora = "spBitacora"; #endregion Sps //Consultas #region sps_Consultas public const string sp_Fac_Buscar_Cliente = "sp_Fac_Buscar_Cliente"; public const string sp_Fac_Consultar_Catalogo = "sp_Fac_Consultar_Catalogo"; public const string sp_Fac_Consultar_Sucursal = "sp_Fac_Consultar_Sucursal"; public const string sp_Fac_Consultar_Ticket = "sp_Fac_Consultar_Ticket"; public const string sp_Fac_Valida_Ticket_Comprobante = "sp_Fac_Valida_Ticket_Comprobante"; public const string sp_Fac_CalculaImpuestosArticulo = "sp_Fac_CalculaImpuestosArticulo"; public const string sp_Fac_GuardaComprobante = "sp_Fac_GuardaComprobante"; //public const string sp_Fac_Valida_Ticket_Comprobante = "sp_Fac_Valida_Ticket_Comprobante"; public const string sp_Fac_Buscar_Comprobante = "sp_Fac_Buscar_Comprobante"; public const string sp_Fac_GuardaBinariosComprobante = "sp_Fac_GuardaBinariosComprobante"; #endregion sps_Consultas //Modificaciones #region sps_Modificaciones public const string sp_Fac_DesActivar_Cliente = "sp_Fac_DesActivar_Cliente"; public const string sp_Fac_Guarda_Cliente = "sp_Fac_Guarda_Cliente"; #endregion sps_Modificaciones #region Login public const string sp_Seg_VerificaUsuario = "spSegLogueaUsuario"; #endregion #region Ventas public const string spVenConsultarArticulo = "spVenConsultaArticulo"; public const string spVenGuardaArticulos = "spVenGuardaArticulos"; public const string spVenConsultaArticulos = "spVenConsultaArticulos"; public const string spConsultaCatalogos = "spConsultaCatalogos"; #endregion #region CancelaComprobante public const string sp_Fac_CancelaComprobante = "sp_Fac_CancelaComprobante"; public const string sp_Uti_RegistraBitacora = "sp_Uti_RegistraBitacora"; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UrTLibrary.Server.Logging.Annotations; namespace UrTLibrary.Server.Logging.Events { public class AccountValidatedEvent : LogEvent { public int Slot { get; set; } public string Account { get; set; } public int Num { get; set; } public string Rank { get; set; } } }
namespace PRGTrainer.Core.AdminHandler { using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using log4net; using Model.Result; using ResultFileGenerator; using Shared.EncryptString; /// <summary> /// Обработчик администрирования. /// </summary> public class AdminHandler : IAdminHandler { #region Private fields /// <summary> /// Таблица с администраторами. /// </summary> private const string AdminsTable = @"Admins"; /// <summary> /// Таблица с результатами пользователя. /// </summary> private const string UserResultsTable = @"UserResults"; /// <summary> /// Таблица со счетчиком неверных ответов на вопросы. /// </summary> private const string QuestionResultsTable = @"QuestionResults"; /// <summary> /// Генератор результатов пользователей. /// </summary> private readonly IResultFileGenerator _resultFileGenerator; /// <summary> /// Шифровальщик. /// </summary> private readonly IEncrypter _encrypter; /// <summary> /// Соединение с сервером. /// </summary> private readonly SqlConnection _connection; #endregion /// <summary> /// Инициализирует экземпляр <see cref="AdminHandler"/> /// </summary> /// <param name="resultFileGenerator">Генератор результатов пользователей.</param> /// <param name="encrypter">Шифровальщик.</param> public AdminHandler([NotNull]IResultFileGenerator resultFileGenerator, [NotNull]IEncrypter encrypter) { _resultFileGenerator = resultFileGenerator; _encrypter = encrypter; var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[@"UserStatistics"].ConnectionString; _connection = new SqlConnection(connectionString); Logger = LogManager.GetLogger(typeof(AdminHandler)); } /// <inheritdoc /> public StatisticOutputFileType OutputFileType { private get; set; } /// <summary> /// Логгер. /// </summary> private ILog Logger { get; } /// <inheritdoc /> public async Task<bool> TryAddNewAdmin(int identifier, string token) { var query = $"EXECUTE dbo.AddAdmin @Token = '{_encrypter.Encrypt(token)}', @Identifier = {identifier}"; try { await _connection.OpenAsync().ConfigureAwait(false); using (var command = new SqlCommand(query, _connection)) { await command.ExecuteNonQueryAsync().ConfigureAwait(false); } } catch (Exception exception) { Console.WriteLine(exception); if (Logger.IsErrorEnabled) Logger.Error(@"Не удалось добавить нового администратора!", exception); } finally { _connection.Close(); } return await IsUserAdmin(identifier).ConfigureAwait(false); } /// <inheritdoc /> public async Task<bool> IsUserAdmin(int identifier) { var query = $"SELECT Count(*) FROM dbo.{AdminsTable} WHERE UserId = '{identifier}'"; try { await _connection.OpenAsync().ConfigureAwait(false); using (var command = new SqlCommand(query, _connection)) { var reader = await command.ExecuteReaderAsync().ConfigureAwait(false); await reader.ReadAsync().ConfigureAwait(false); return reader.GetInt32(0) != 0; } } catch (Exception exception) { Console.WriteLine(exception); if (Logger.IsErrorEnabled) Logger.Error(@"Не удалось проверить является ли пользователь администратором!", exception); return false; } finally { _connection.Close(); } } /// <inheritdoc /> public async Task<string> GetStatisticForUsers(ICollection<string> users, DateTime startDate, int identifier) { if (!await IsUserAdmin(identifier)) return string.Empty; var results = new List<UserResult>(); var query = $"SELECT username, result, finishtime FROM {UserResultsTable} WHERE (finishtime > convert(datetime,'{startDate:dd-MM-yy}', 5) AND username IS NOT NULL)"; if (users != null && users.Any()) query += @" AND (" + string.Join(@" OR ", users.Select(user => $"username = '{user}'")) + @")"; query += @";"; try { await _connection.OpenAsync().ConfigureAwait(false); using (var command = new SqlCommand(query, _connection)) { var reader = await command.ExecuteReaderAsync().ConfigureAwait(false); while (await reader.ReadAsync().ConfigureAwait(false)) { var user = reader.GetString(0); var result = (int)reader.GetDouble(1); var date = reader.GetDateTime(2); if (results.Any(item => item.User == user)) results[results.FindIndex(item => item.User == user)].Result[date] = result; else results.Add(new UserResult { User = user, Result = new Dictionary<DateTime, int> { { date, result } } }); } } } catch (Exception exception) { Console.WriteLine(exception); if (Logger.IsErrorEnabled) Logger.Error(@"Не удалось получить результаты пользователей!", exception); return string.Empty; } finally { _connection.Close(); } foreach (var result in results) { var sortedResult = new SortedDictionary<DateTime, int>(result.Result); var keyValuePairs = sortedResult.OrderBy(item => item.Key); result.Result = keyValuePairs.ToDictionary(item => item.Key, item => item.Value); } if (OutputFileType.Equals(StatisticOutputFileType.Image)) return _resultFileGenerator.GenerateAsImage(results); if (OutputFileType.Equals(StatisticOutputFileType.Text)) return _resultFileGenerator.GenerateAsText(results); throw new ArgumentOutOfRangeException("", OutputFileType, @"Неизвестный тип выходного файла!"); } /// <inheritdoc /> public async Task<string> GetStatisticForUsers(ICollection<string> users, int identifier) { return await GetStatisticForUsers(users, DateTime.MinValue, identifier).ConfigureAwait(false); } /// <inheritdoc /> public async Task<string> GetStatisticForQuestions(int identifier) { if (!await IsUserAdmin(identifier)) return string.Empty; var questionResult = new List<QuestionResult>(); var query = $"SELECT question, wrongcount FROM dbo.{QuestionResultsTable};"; try { await _connection.OpenAsync().ConfigureAwait(false); using (var command = new SqlCommand(query, _connection)) { var reader = await command.ExecuteReaderAsync().ConfigureAwait(false); while (await reader.ReadAsync().ConfigureAwait(false)) questionResult.Add(new QuestionResult { Question = reader.GetString(0), Quota = reader.GetInt32(1)}); } } catch (Exception exception) { Console.WriteLine(exception); if (Logger.IsErrorEnabled) Logger.Error(@"Не удалось получить результаты пользователей!", exception); return string.Empty; } finally { _connection.Close(); } var sum = questionResult.Aggregate((double)0, (current, item) => current + item.Quota); questionResult.ForEach(item => item.Quota = item.Quota/sum); if (OutputFileType.Equals(StatisticOutputFileType.Image)) return _resultFileGenerator.GenerateAsImage(questionResult); if (OutputFileType.Equals(StatisticOutputFileType.Text)) return _resultFileGenerator.GenerateAsText(questionResult); throw new ArgumentOutOfRangeException("", OutputFileType, @"Неизвестный тип выходного файла!"); } } }
using System; using System.Linq; using System.Collections.Generic; namespace GENN { /// <summary> /// A place where organisms are born, live and die. /// </summary> public class GenePool { // Private data stores private int _Generation; private Input[] InputLayer; private NeuralNet[] Pool; public GenePool (Input[] inputLayer, int organismCount, int outputCount, int[] hiddenDimensions) { // Copy the input layer InputLayer = inputLayer; // Populate the gene pool Pool = new NeuralNet [organismCount]; for (int i = 0; i < organismCount; i++) Pool[i] = new NeuralNet (InputLayer, hiddenDimensions, outputCount); } /// <summary> /// Get/Set the input layer of the <see cref="GenePool"/>. /// </summary> /// <value>The input.</value> public double[] Inputs { get { double[] input = new double[InputLayer.Length]; for (int i = 0; i < InputLayer.Length; i++) input [i] = InputLayer [i].Value; return input; } } /// <summary> /// An array of ideal outputs. /// </summary> public double[] TargetOutput; /// <summary> /// Checks the error of a "candidate" <see cref="NeuralNetwork"/> output by averaging the difference between /// <see cref="TargetOutput"/> and the candidate's <see cref="Output"/>. /// </summary> /// <returns>The error.</returns> /// <param name="candidate">Candidate.</param> private double CheckError(NeuralNet candidate) { double[] output = candidate.Output; double[] errors = new double[TargetOutput.Length]; for (int i = 0; i < TargetOutput.Length; i++) { errors [i] = (TargetOutput [i] - output [i]) / TargetOutput[i]; } return errors.Average (); } private void Sort() { Pool.OrderBy (net => net.Output); } public double NextGeneration() { _Generation++; KillOff (); Breed (); return CheckError (BestCandidate); } public int Generation { get { return _Generation; } } // public NeuralNet BestCandidate // { // get // { // // } // } // // public double BestFitnessScore // { // get // { // // } // } } }
// // 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.Collections; using System.ComponentModel; using System.Web.UI; #endregion namespace DotNetNuke.Services.Syndication { /// <summary> /// RSS data source control implementation, including the designer /// </summary> [DefaultProperty("Url")] public class RssDataSource : DataSourceControl { private GenericRssChannel _channel; private RssDataSourceView _itemsView; private string _url; public GenericRssChannel Channel { get { if (_channel == null) { if (string.IsNullOrEmpty(_url)) { _channel = new GenericRssChannel(); } else { _channel = GenericRssChannel.LoadChannel(_url); } } return _channel; } } public int MaxItems { get; set; } public string Url { get { return _url; } set { _channel = null; _url = value; } } protected override DataSourceView GetView(string viewName) { if (_itemsView == null) { _itemsView = new RssDataSourceView(this, viewName); } return _itemsView; } } public class RssDataSourceView : DataSourceView { private readonly RssDataSource _owner; internal RssDataSourceView(RssDataSource owner, string viewName) : base(owner, viewName) { _owner = owner; } public override void Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) { callback(ExecuteSelect(arguments)); } protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) { return _owner.Channel.SelectItems(_owner.MaxItems); } } }
namespace XMLApiProject.Services.Models.PaymentService.XML.RequestService.Responses { public class Ping { } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.Files.Mount { /** * Interface IMountManager * * Manages all mounted storages in the system * @since 8.2.0 */ public interface IMountManager { /** * Add a new mount * * @param \OCP\Files\Mount\IMountPoint mount * @since 8.2.0 */ void addMount(IMountPoint mount); /** * Remove a mount * * @param string mountPoint * @since 8.2.0 */ void removeMount(string mountPoint); /** * Change the location of a mount * * @param string mountPoint * @param string target * @since 8.2.0 */ void moveMount(string mountPoint, string target); /** * Find the mount for path * * @param string path * @return \OCP\Files\Mount\IMountPoint|null * @since 8.2.0 */ IMountPoint? find(string path); /** * Find all mounts in path * * @param string path * @return \OCP\Files\Mount\IMountPoint[] * @since 8.2.0 */ IList<IMountPoint> findIn(string path); /** * Remove all registered mounts * * @since 8.2.0 */ void clear(); /** * Find mounts by storage id * * @param string id * @return \OCP\Files\Mount\IMountPoint[] * @since 8.2.0 */ IList<IMountPoint> findByStorageId(string id); /** * @return \OCP\Files\Mount\IMountPoint[] * @since 8.2.0 */ IList<IMountPoint> getAll(); /** * Find mounts by numeric storage id * * @param int id * @return \OCP\Files\Mount\IMountPoint[] * @since 8.2.0 */ IList<IMountPoint> findByNumericId(int id); } }
using PlatformRacing3.Server.API.Game.Commands; using PlatformRacing3.Server.Game.Client; namespace PlatformRacing3.Server.Game.Commands.User; internal sealed class MuteCommand : ICommand { private readonly CommandManager commandManager; public MuteCommand(CommandManager commandManager) { this.commandManager = commandManager; } public string Permission => "command.mute.use"; public void OnCommand(ICommandExecutor executor, string label, ReadOnlySpan<string> args) { if (args.Length >= 1) { int i = 0; foreach (ClientSession target in this.commandManager.GetTargets(executor, args[0])) { if (target.PermissionRank > executor.PermissionRank || target == executor) { continue; } i++; target.UserData.Muted = true; if (args.Length == 1) { target.SendMessage("You have been muted for absolute no reason, I bet some staff must hate you"); } else { target.SendMessage("You have been muted for " + string.Join(' ', args[1..].ToArray())); } } executor.SendMessage($"Effected {i} clients"); } else { executor.SendMessage("Usage: /kick [user] [reason(empty)]"); } } }
using GlobalDevelopment.SocialNetworks; using Umbraco.Web.Mvc; using System.Web.Mvc; namespace GlobalDevelopment.Controllers { public class RazorSurfaceController : SurfaceController { public RedirectResult FacebookLoginRegister(string url, string memberType, string memberGroups, string propertyAlias) { FacebookM.Authorization(url); FacebookM.MemberRegisterU(memberType, memberGroups, propertyAlias); return Redirect(url); } } }
namespace BUKEP.TESTS.DRIVER.Enums { /// <summary> /// Перечисление стендов /// </summary> public enum StandType { /// <summary> /// http://iis-2:803/ /// </summary> AsuBukepTests = 0, /// <summary> /// https://asu.bukep.ru:444/ /// </summary> AsuBukep = 1, /// <summary> /// http://iis-2:812/ /// </summary> EnrolleeBukepTests = 2, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class PasajeAvion : Pasaje { public int cantidadEscalas; public PasajeAvion() { } public PasajeAvion(string origen, string destino, Pasajero pasajero, float precio, DateTime fecha, int cantidadEscalas) :base(origen, destino,pasajero,precio,fecha) { this.cantidadEscalas = cantidadEscalas; } public override string Mostrar() { return String.Format("{0}\nPrecioFinal: {1}",base.Mostrar(),this.PrecioFinal); } public override float PrecioFinal { get { switch(this.cantidadEscalas) { case 1: return Precio - ((Precio * 10) / 100); case 2: return Precio - ((Precio * 20) / 100); } return Precio - ((Precio * 30) / 100); ; } } } }
using Microsoft.EntityFrameworkCore; using ProManager.Entities.Common; namespace ProManager.Entities { public partial class ProManagerContext : DbContext { public virtual DbSet<MenuItem> MenuItems { get; set; } public virtual DbSet<SystemRoles> SystemRoles { get; set; } public virtual DbSet<ApplicationModules> ApplicationModules { get; set; } public virtual DbSet<ApplicationModuleMenus> ApplicationModuleMenus { get; set; } public virtual DbSet<ApplicationModuleSystemRoles> ApplicationModuleSystemRoles { get; set; } public virtual DbSet<BusinessRoles> BusinessRoles { get; set; } public virtual DbSet<ApplicationUserBusinessRole> ApplicationUserBusinessRole { get; set; } public virtual DbSet<BusinessRoleMenus> BusinessRoleMenus { get; set; } public virtual DbSet<Languages> Languages { get; set; } public virtual DbSet<Translations> Translations { get; set; } public virtual DbSet<MenuItemGroup> MenuItemGroup { get; set; } } }
using Android.Views; using Android.Widget; using Xamarin.Forms; using App1.Droid.Renderers; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(EditText), typeof(EditTextRenderer))] namespace App1.Droid.Renderers { public class EditTextRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.SetBackgroundResource(Resource.Drawable.EditText); //Control.TextAlignment = Android.Views.TextAlignment.Center; Control.Gravity = GravityFlags.Center; //Control.HintTextColors = Color.Gray.ToAndroid (); } } } }
/* * Copyright (c) 2017 Samsung Electronics Co., Ltd 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 Tizen; using Tizen.Applications; using Tizen.NUI; using Tizen.NUI.BaseComponents; namespace SimpleLayout { class SimpleLayout : NUIApplication { private static readonly string LogTag = "LAYOUT"; public static readonly string ItemContentNameIcon = "ItemIcon"; public static readonly string ItemContentNameTitle = "ItemTitle"; public static readonly string ItemContentNameDescription = "ItemDescription"; protected override void OnCreate() { base.OnCreate(); Initialize(); } private class ListItem { private string IconPath = null; private string Label = null; private string Description = null; public ListItem(string iconPath, string label) { IconPath = iconPath; Label = label; } public ListItem(string iconPath, string label, string description) { IconPath = iconPath; Label = label; Description = description; } public string GetIconPath() { return IconPath; } public string GetLabel() { return Label; } public string GetDescription() { return Description; } }; private static readonly ListItem[] ListItems = { new ListItem("/images/application-icon-101.png", "Gallery", "Local images viewer"), new ListItem("/images/application-icon-102.png", "Wifi"), new ListItem("/images/application-icon-103.png", "Apps", "List of available applications"), new ListItem("/images/application-icon-104.png", "Desktops", "List of available desktops") }; private void Initialize() { Log.Debug(LogTag, "Application initialize started..."); // Change the background color of Window to White & respond to key events Window window = Window.Instance; window.BackgroundColor = Color.White; window.KeyEvent += OnKeyEvent; //Create background Log.Debug(LogTag, "Creating background..."); ImageView im = new ImageView(DirectoryInfo.Resource + "/images/bg.png"); im.Size2D = new Size2D(window.Size.Width, window.Size.Height); window.Add(im); //Create Linear Layout Log.Debug(LogTag, "Creating linear layout..."); LinearLayout linearLayout = new LinearLayout(); linearLayout.LinearOrientation = LinearLayout.Orientation.Vertical; linearLayout.CellPadding = new Size2D(20, 20); //Create main view View mainView = new View(); mainView.Size2D = new Size2D(window.Size.Width, window.Size.Height); mainView.Layout = linearLayout; //Create custom items and add it to view for (int i = 0; i < 4; i++) { //Create item base view. View itemView = new View(); itemView.BackgroundColor = new Color(0.47f, 0.47f, 0.47f, 0.5f); itemView.Name = "ItemView_" + i.ToString(); //Create item layout responsible for positioning in each item ItemLayout itemLayout = new ItemLayout(); itemView.Layout = itemLayout; //Crate item icon ImageView icon = new ImageView(DirectoryInfo.Resource + ListItems[i].GetIconPath()); icon.Size2D = new Size2D(100, 100); icon.Name = ItemContentNameIcon; itemView.Add(icon); PropertyMap titleStyle = new PropertyMap(); titleStyle.Add("weight", new PropertyValue("semiBold")); //Create item title TextLabel title = new TextLabel(ListItems[i].GetLabel()); title.Size2D = new Size2D(400, 60); title.FontStyle = titleStyle; title.Name = ItemContentNameTitle; title.PixelSize = 38.0f; itemView.Add(title); string strDescription = ListItems[i].GetDescription(); if (strDescription != null) { TextLabel description = new TextLabel(strDescription); description.Size2D = new Size2D(500, 50); description.Name = ItemContentNameDescription; description.PixelSize = 28.0f; itemView.Add(description); } else { title.Size2D = new Size2D(400, 110); } mainView.Add(itemView); } window.Add(mainView); } private void OnKeyEvent(object sender, Window.KeyEventArgs eventArgs) { if (eventArgs.Key.State == Key.StateType.Down) { switch (eventArgs.Key.KeyPressedName) { case "Back": case "XF86Back": //for emulator Exit(); break; } } } static void Main(string[] args) { SimpleLayout simpleLayout = new SimpleLayout(); simpleLayout.Run(args); simpleLayout.Dispose(); } } }
using Ambassador.Models.EventModels.Interfaces; using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq.Expressions; namespace Ambassador.Entities { [DisplayName("Event")] public class Event : IAmbassadorEventManagerReviewModel, IOrganizationEventManagerCreateModel, IOrganizationEventManagerEditModel, IOrganizationEventManagerReviewModel { [Key] [Required] [MaxLength(450)] public string Id { get; set; } [Required] public string Name { get; set; } [Required] public string Description { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy hh:mm tt}", ApplyFormatInEditMode = true)] public DateTime? Start { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy hh:mm tt}", ApplyFormatInEditMode = true)] public DateTime? End { get; set; } [NotMapped] [DisplayFormat(DataFormatString = "{0:hh\\:mm}")] public TimeSpan Duration { get { return End.Value.Subtract((DateTime)Start); } } public int? AmbassadorReviewOfEventRating { get; set; } public string AmbassadorReviewOfEventComment { get; set; } public int? OrganizationReviewOfEventRating { get; set; } public string OrganizationReviewOfEventComment { get; set; } public bool Deleted { get; set; } [Timestamp] public byte[] RowVersion { get; set; } [MaxLength(450)] public string OrganizationId { get; set; } public Organization Organization { get; set; } [MaxLength(450)] public string AmbassadorId { get; set; } public Ambassador Ambassador { get; set; } [Required] [MaxLength(450)] public string LocationId { get; set; } public Location Location { get; set; } [MaxLength(450)] public string SeriesId { get; set; } public EventSeries Series { get; set; } public bool IsActive() { return Expressions.IsActive().Compile().Invoke(this); } public bool IsNotActive() { return Expressions.IsNotActive().Compile().Invoke(this); } public bool IsAvailable() { return Expressions.IsAvailable().Compile().Invoke(this); } public bool IsNotAvailable() { return Expressions.IsNotAvailable().Compile().Invoke(this); } public bool RequiresAmbassadorReview() { return Expressions.RequiresAmbassadorReview().Compile().Invoke(this); } public bool RequiresOrganizationReview() { return Expressions.RequiresOrganizationReview().Compile().Invoke(this); } public static class Expressions { public static Expression<Func<Event, bool>> IsActive() { var now = DateTimeOffset.Now; return x => !x.Deleted && x.End > now; } public static Expression<Func<Event, bool>> IsNotActive() { var now = DateTimeOffset.Now; return x => x.Deleted || x.End < now; } public static Expression<Func<Event, bool>> IsAvailable() { var now = DateTimeOffset.Now; return x => !x.Deleted && x.End > now && x.AmbassadorId == null; } public static Expression<Func<Event, bool>> IsNotAvailable() { var now = DateTimeOffset.Now; return x => x.Deleted || x.End < now || x.AmbassadorId != null; } public static Expression<Func<Event, bool>> RequiresAmbassadorReview() { var now = DateTimeOffset.Now; return x => !x.Deleted && x.End < now && x.AmbassadorId != null && x.AmbassadorReviewOfEventRating == null; } public static Expression<Func<Event, bool>> RequiresOrganizationReview() { var now = DateTimeOffset.Now; return x => !x.Deleted && x.End < now && x.AmbassadorId != null && x.OrganizationReviewOfEventRating == null; } } } }
using Amazon.Suporte.Database; using Amazon.Suporte.Enum; using Amazon.Suporte.Model; using System; namespace Amazon.Suporte.Services { public class ProblemService : IProblemService { private SupportDBContext _context; public ProblemService(SupportDBContext context) { _context = context; } public Problem CreateProblem(Problem problem) { problem.CreatedAt = DateTime.Now; problem.Status = StatusEnum.Created; var unitOfWork = new UnitOfWork(_context); unitOfWork.ProblemRepository.Add(problem); unitOfWork.Complete(); return problem; } public Problem GetProblemByIdentificator(string identificator) { return new UnitOfWork(_context) .ProblemRepository .GetProblemByIdentificator(identificator); } } }
using NekoUchi.DAL.Helpers; using System; using System.Collections.Generic; using System.Text; using MongoDB.Bson; using MongoDB.Driver; namespace NekoUchi.DAL { public class Course : Model.Course, ISerializationHelper { #region Properties public ObjectId _id { get; set; } #endregion #region Static methods public static bool SubscribeUser(string email, string courseId) { try { ObjectId id = new ObjectId(courseId); var dataProvider = new MongoDataProvider(); var db = dataProvider.GetDatabase(); var collection = db.GetCollection<Course>("Course"); var filter = Builders<Course>.Filter.Where(x => x._id == id); var update = Builders<Course>.Update.AddToSet(x => x.Subscribed, email); var result = collection.UpdateOne(filter, update); if (result.ModifiedCount == 1) { return true; } else { return false; } } catch (Exception) { return false; } } public static bool AddLesson (Model.Lesson lesson, string courseId) { try { ObjectId id = new ObjectId(courseId); var dataProvider = new MongoDataProvider(); var db = dataProvider.GetDatabase(); var collection = db.GetCollection<Course>("Course"); var filter = Builders<Course>.Filter.Where(c => c._id == id); var update = Builders<Course>.Update.AddToSet(c => c.Lessons, lesson); var result = collection.UpdateOne(filter, update); if (result.ModifiedCount == 1) { return true; } else { return false; } } catch (Exception) { return false; } } public static bool UpdateLesson (Model.Lesson lesson, string courseId) { try { ObjectId id = new ObjectId(courseId); var dataProvider = new MongoDataProvider(); var db = dataProvider.GetDatabase(); var collection = db.GetCollection<Course>("Course"); var filter = Builders<Course>.Filter.And( Builders<Course>.Filter.Where(c => c._id == id), Builders<Course>.Filter.ElemMatch(c => c.Lessons, l => l.Name == lesson.Name)); var update = Builders<Course>.Update.Set(c => c.Lessons[-1], lesson); var result = collection.UpdateOne(filter, update); if (result.ModifiedCount == 1) { return true; } else { return false; } } catch (Exception) { return false; } } public static bool UnsubscribeUser(string email, string courseId) { try { ObjectId id = new ObjectId(courseId); var dataProvider = new MongoDataProvider(); var db = dataProvider.GetDatabase(); var collection = db.GetCollection<Course>("Course"); var filter = Builders<Course>.Filter.Where(x => x._id == id); var update = Builders<Course>.Update.Pull(x => x.Subscribed, email); var result = collection.UpdateOne(filter, update); if (result.ModifiedCount == 1) { return true; } else { return false; } } catch (Exception) { return false; } } public static string CreateCourse(Course newCourse) { IDataProvider data = new MongoDataProvider(); newCourse = data.Create(newCourse); return newCourse._id.ToString(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloGit { class Program { static void Main(string[] args) { // Attempt at github with VS2015 Console.WriteLine("Hey there Git!"); Console.WriteLine("So glad it is working!"); Console.WriteLine("Can you read this?^^"); Console.WriteLine("bla bla bla bla bla bla bla bla"); } } }
using Godot; using System; public class Fireplace : Node2D { [Export] public float HeatInnerRadius = 50.0f; [Export] public float HeatOuterRadius = 100.0f; [Export] public bool HealEnabled = false; [Export] public float HealInnerRadius = 10.0f; [Export] public float HealOuterRadius = 20.0f; [Export] public float HealSpeed = 20.0f; public override void _Ready() { } }
using System; class Program { public static void Main() { int WorkingDays = int.Parse(Console.ReadLine()); double Pay = double.Parse(Console.ReadLine()); double USDc = double.Parse(Console.ReadLine()); double MonthlyPay = Pay * (double)WorkingDays; double AnnualPay = MonthlyPay * 14.5; double VatPay = AnnualPay * 0.75; double AnnualBGN = VatPay * USDc; Console.WriteLine("{0:f2}", AnnualBGN / 365); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using VS.GUI.InheritedControl.Interface; using VS.Logic; namespace VS.GUI.InheritedControl { public partial class VSLaunchLabel : System.Windows.Forms.Label, IStateChangedListener, IDataBindSinglePersist { public event EventHandler BindingOccured; private void OnBindingOccured(System.EventArgs e) { EventHandler ev = BindingOccured; if (ev != null) { ev(this, e); } } public VSLaunchLabel() { InitializeComponent(); } protected object _DataSource; protected string _DataSourceProperty; protected string _LocalProperty; public object DataSource { get { return this._DataSource; } set { this._DataSource = value; this.RebindData(); } } public string DataSourceProperty { get { return this._DataSourceProperty; } set { this._DataSourceProperty = value; this.RebindData(); } } public string LocalProperty { get { return this._LocalProperty; } set { this._LocalProperty = value; this.RebindData(); } } public void RebindData() { try { this.DataBindings.Clear(); this.DataBindings.Add(this._LocalProperty, this._DataSource, this._DataSourceProperty); OnBindingOccured(EventArgs.Empty); } catch (Exception) { } } public void RebindData(object DataSource) { try { this.DataBindings.Clear(); RebindData(); } catch (Exception) { } } public void BindData(string LocalProperty, object DataSource, string DataSourceProperty) { this._DataSource = DataSource; this._DataSourceProperty = DataSourceProperty; this._LocalProperty = LocalProperty; this.RebindData(); } public void StateChanged(BaseLogic sender, StateChangedEventArgs args) { if (args.State == eState.RETRIEVED) { this.DataSource = sender.Container; } } } }
using System.Configuration; using NUnit.Framework; using OpenQA.Selenium; using log4net; namespace UITestProject.FrameData { [TestFixture] public class TestFrame <TWebDriver> where TWebDriver : IWebDriver, new() { private static readonly string baseUrl = ConfigurationManager.AppSettings["url"]; protected static IWebDriver driver; protected static ILog Log; private static void RunDriver() { driver = new TWebDriver(); Log.Info($"{driver.GetType().ToString()} the driver is initialized"); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(baseUrl); } [OneTimeSetUp] public void Init() { Log = LogManager.GetLogger(GetType()); RunDriver(); } [OneTimeTearDown] public void CloseDriver() { driver.Quit(); } } }
using System.Threading.Tasks; namespace Amesc.Dominio._Consultas { public interface IDadosAnaliticosPorCursoConsulta { Task<DadosAnaliticosPorCurso> Consultar(int cursoId, int ano); } }
using Entities.Models; using DAL.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using DAL.Repo; using System.Diagnostics; namespace ConsoleTest { public class Seedmethodtest { public Theme GetSingle(string info, ApplicationDbContext context) { var query = (from c in context.Themes select c).FirstOrDefault<Theme>(x => x.info == info); return query; } public Theme GetThemeByName(string Themename) { Theme Themetemp = null; using (ThemeRepository Themerepo = new ThemeRepository()) { Themetemp = Themerepo.GetSingleByName(Themename); Themerepo.context.Entry(Themetemp).State = EntityState.Detached; } return Themetemp; } public void Seed() { ApplicationDbContext context = new ApplicationDbContext(); List<Theme> _themes = context.Themes.ToList(); Theme theme1 = new Theme(); theme1 = GetThemeByName("Theme 1"); //Console.WriteLine(theme1.info+theme1.Passinggrade+theme1.ThemeId); if (theme1 != null) { Console.WriteLine(theme1.info +" "+ theme1.Passinggrade +" "+ theme1.ThemeId); } else Console.WriteLine("Theme is null"); Theme theme2 = GetThemeByName("Theme 2"); context.Points.AddOrUpdate( new Point { Coef = 1, NumPoint = 1, NomPoint = "Pas d’objets / outils cassés, dégradés sur le poste" , theme = theme1}, new Point { Coef = 4, NumPoint = 2, NomPoint = "Pas d’objets hors contexte ou personnel dans la zone", theme = theme1 }, new Point { Coef = 1, NumPoint = 3, NomPoint = "Pas d’objets inutiles ", theme = theme1 }, new Point { Coef = 2, NumPoint = 4, NomPoint = "Pas de documents non mis à jour / périmés", theme = theme1 }, new Point { Coef = 1, NumPoint = 5, NomPoint = "Pas de documents inutiles affichés", theme = theme1 }, new Point { Coef = 5, NumPoint = 6, NomPoint = "Les poubelles et boites à rebuts ne débordent pas", theme = theme1 }, new Point { Coef = 3, NumPoint = 7, NomPoint = "Les moyens de lutte incendie ne sont pas masqués et sont accessibles", theme = theme1 }, new Point { Coef = 3, NumPoint = 8, NomPoint = "Aucun carton/matière/bobine/outillage/matériel/ par terre", theme = theme1 }, new Point { Coef = 1, NumPoint = 9, NomPoint = "Tout Les objets/ Outils sur le bureau/poste sont identifiés et rangés", theme = theme2 }, new Point { Coef = 1, NumPoint = 10, NomPoint = "Il y a un emplacement dédié pour chaque chose", theme = theme2 }, new Point { Coef = 1, NumPoint = 11, NomPoint = "Les produits/cartes sont correctement rangé/posé", theme = theme2 }, new Point { Coef = 1, NumPoint = 12, NomPoint = "Chaque mobilier (armoire, tiroir, étagère) fait l'objet d'une identification sur son contenu", theme = theme2 }, new Point { Coef = 1, NumPoint = 13, NomPoint = "Les règles de rangement bureau de fin de journée /départ sont définis, affichées et connues", theme = theme2 }, new Point { Coef = 1, NumPoint = 14, NomPoint = "Rien sur les armoires (pas de stockage par-dessus les armoires)", theme = theme2 }, new Point { Coef = 1, NumPoint = 15, NomPoint = "Les poubelles ont un emplacement dédié et identifié", theme = theme2 }, new Point { Coef = 1, NumPoint = 16, NomPoint = "Les transpalettes ,chariots et roulis ont un emplacement dédié et identifié", theme = theme2 }, new Point { Coef = 1, NumPoint = 17, NomPoint = "Le marquage au sol est en bon état", theme = theme2 }, new Point { Coef = 1, NumPoint = 18, NomPoint = "Les câbles / fils électriques sont rangés et sécurisés", theme = theme2 }, new Point { Coef = 1, NumPoint = 19, NomPoint = "Les extincteurs moyens de lutte incendie et issus de secours sont repérés", theme = theme2 } ); context.SaveChanges(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace Dawnfall.Helper { public static class HelperSaveLoad { public static bool SaveJsonToPrefs<T>(T o, string key) { try { PlayerPrefs.SetString(key, JsonUtility.ToJson(o)); return true; } catch { return false; } } public static T LoadFromJsonPrefs<T>(string key, T defaultValue) { try { return JsonUtility.FromJson<T>(PlayerPrefs.GetString(key)); } catch { return defaultValue; } } public static void SaveToFileWithBinFormater<T>(T obj, string path, string name, string extention) { string filePath = System.IO.Path.Combine(path, name + "." + extention); FileStream file = File.Open(filePath, FileMode.Create); BinaryFormatter binFormater = new BinaryFormatter(); binFormater.Serialize(file, obj); file.Close(); } public static T LoadFromFileWithBinaryFormater<T>(string path, string name, string extention) where T : class { string[] allFiles = Directory.GetFiles(path, name + "." + extention, SearchOption.TopDirectoryOnly); if (allFiles.Length == 0) return null; FileStream file = File.Open(allFiles[0], FileMode.Open); BinaryFormatter binFormatter = new BinaryFormatter(); T loadedData = (T)binFormatter.Deserialize(file); file.Close(); return loadedData; } public static void SaveTextureToPng(string pathWithoutExtention, Texture2D texture) { byte[] texData = texture.EncodeToPNG(); File.WriteAllBytes(Path.Combine(Application.dataPath, pathWithoutExtention) + ".png", texData); } //public static string[] GetAllFileNames(string extension) //{ // ExternalData externalData = ExternalData.Instance; // CheckForSaveFolder(); // return Directory.GetFiles(externalData.SavePath, "*." + externalData.SaveExtention); //} //public static void CheckForSaveFolder() //{ // ExternalData externalMaster = ExternalData.Instance; // if (externalMaster.SavePath == "") // { // externalMaster.SavePath = System.IO.Path.Combine(Application.persistentDataPath, "Levels"); // } // if (!Directory.Exists(externalMaster.SavePath)) // Directory.CreateDirectory(externalMaster.SavePath); //} //public static void SaveToFile<T>(T obj, string path, string name, string extention) //{ // CheckForSaveFolder(); // string filePath = System.IO.Path.Combine(path, name + "." + extention); // FileStream file = File.Open(filePath, FileMode.Create); // BinaryFormatter binFormater = new BinaryFormatter(); // binFormater.Serialize(file, obj); // file.Close(); //} //public static T LoadFile<T>(string path, string name, string extention) where T : class //{ // CheckForSaveFolder(); // string[] allFiles = Directory.GetFiles(path, name + "." + extention, SearchOption.TopDirectoryOnly); // if (allFiles.Length == 0) // return null; // FileStream file = File.Open(allFiles[0], FileMode.Open); // BinaryFormatter binFormatter = new BinaryFormatter(); // T loadedData = (T)binFormatter.Deserialize(file); // file.Close(); // return loadedData; //} //public static bool DeleteLevel(string levelName) //TODO: trigger event //{ // ExternalMaster externalMaster = ExternalMaster.Instance; // CheckForSaveFolder(); // string filePath = System.IO.Path.Combine(externalMaster.SavePath, levelName + "." + externalMaster.SaveExtention); // if (File.Exists(filePath)) // { // File.Delete(filePath); // EventManager.TriggerEvent(EventNames.External_Files_Changed); // return true; // } // return false; //} } }
// // Copyright (c), 2017. Object Training Pty Ltd. All rights reserved. // Written by Tim Hastings. // using System; using Xamarin.Forms; namespace MyListApp { /// <summary> /// The Item. /// Copyright (c), 2017. Object Training Pty Ltd. All rights reserved. /// Written by Tim Hastings. /// </summary> public class Item { public long id { get; set; } public String Name { get; set; } public String Address { get; set; } // Added public String Detail { get; set; } public Image Icon { get; set; } public Item() { // Always initiate instance variables. id = 0; Name = ""; Address = ""; Detail = ""; Icon = new Image() { Source = "avatar.png"}; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; namespace MADSPack.Compression { public class MadsPackFont { public int maxHeight; public int maxWidth; public byte[] charWidths; public uint[] charOffsets; public byte[] charData; private byte[] paletteData; public string pathtoCol; private List<byte> _fontColors = new List<byte>(); public MadsPackFont(MadsPackEntry item) { _fontColors.Add(0xFF); _fontColors.Add(0xF); _fontColors.Add(7); _fontColors.Add(8); MemoryStream fontFile = new MemoryStream(item.getData()); maxHeight = fontFile.ReadByte(); maxWidth = fontFile.ReadByte(); charWidths = new byte[128]; // Char data is shifted by 1 charWidths[0] = 0; fontFile.Read(charWidths, 1, 127); fontFile.ReadByte(); // remainder charOffsets = new uint[128]; uint startOffs = 2 + 128 + 256; uint fontSize = (uint)(fontFile.Length - startOffs); charOffsets[0] = 0; for (int i = 1; i < 128; i++) { byte[] twobyte = new byte[2]; fontFile.Read(twobyte, 0, 2); ushort val = (ushort)BitConverter.ToInt16(twobyte, 0); charOffsets[i] = val - startOffs; } fontFile.ReadByte(); // remainder charData = new byte[fontSize]; fontFile.Read(charData, 0, (int)fontSize); } public Bitmap GenerateFontMap() { Bitmap bmp = new Bitmap(500, 200); string a = "!\"$%()+,-./:;?01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; writeString(ref bmp, a, new Point(9, 9), 9, 500); return bmp; } public int writeString(ref Bitmap bmp, string msg, Point pt, int spaceWidth, int width) { PalReader r = new PalReader(); this.paletteData = r.GetPalette(pathtoCol + "\\VICEROY.PAL"); int xEnd; if (width > 0) xEnd = Math.Min((int)bmp.Width, pt.X + width); else xEnd = bmp.Width; int x = pt.X; int y = pt.Y; int skipY = 0; if (y < 0) { skipY = -y; y = 0; } int height = Math.Max(0, maxHeight - skipY); if (height == 0) return x; int bottom = y + height - 1; if (bottom > bmp.Height - 1) { height -= Math.Min(height, bottom - (bmp.Height - 1)); } if (height <= 0) return x; int xPos = x; char[] text = Encoding.ASCII.GetChars(Encoding.ASCII.GetBytes(msg)); for (int l = 0; l < text.Length; l++) { char theChar = (char)(text[l] & 0x7F); int charWidth = charWidths[(byte)theChar]; if (charWidth > 0) { if (xPos + charWidth > xEnd) return xPos; uint initialCharDataByte = charOffsets[(byte)theChar] + 1; uint endCharDataByte = charOffsets[(byte)theChar + 1] + 1; int bpp = getBpp(charWidth); if (skipY != 0) initialCharDataByte += (uint)(bpp * skipY); List<byte> pixellist = new List<byte>(); for (int i = 0; i < height; i++) { for (int j = 0; j < bpp; j++) { long dataindex = initialCharDataByte + ((i * bpp) + j); if (dataindex >= charData.Length) dataindex = charData.Length - 1; byte val = charData[dataindex]; // Get all 8 bits from this byte byte bit8 = (byte)((val & 0x80) >> 7); byte bit7 = (byte)((val & 0x40) >> 6); byte bit6 = (byte)((val & 0x20) >> 5); byte bit5 = (byte)((val & 0x10) >> 4); byte bit4 = (byte)((val & 0x08) >> 3); byte bit3 = (byte)((val & 0x04) >> 2); byte bit2 = (byte)((val & 0x02) >> 1); byte bit1 = (byte)(val & 0x01); byte nib4 = (byte)((bit8 << 1) + bit7); byte nib3 = (byte)((bit6 << 1) + bit5); byte nib2 = (byte)((bit4 << 1) + bit3); byte nib1 = (byte)((bit2 << 1) + bit1); pixellist.Add(_fontColors[nib4]); pixellist.Add(_fontColors[nib3]); pixellist.Add(_fontColors[nib2]); pixellist.Add(_fontColors[nib1]); } } int[,] pxdata = new int[height, charWidth]; int counter = 0; for (int i = 0; i < charWidth * height; i++) { int h = (i / charWidth); int w = i % charWidth; if (counter >= pixellist.Count) pxdata[h, w] = 0; else pxdata[h, w] = pixellist[counter]; // Skip the quantity of bpp from the end (god knows why) if (i % charWidth == charWidth - 1) { counter += (bpp * 4) - charWidth; } counter++; } // Draw the char Bitmap b = new Bitmap(charWidth, height); for (int yy = 0; yy < height; yy++) { for (int xx = 0; xx < charWidth; xx++) { // Get RGB values for this index int aa, rr, gg, bb; if (pxdata[yy, xx] == 255 || pxdata[yy, xx] == 0) { aa = rr = gg = bb = 0; } else { aa = 255; rr = paletteData[pxdata[yy, xx] * 3] * 2; gg = paletteData[(pxdata[yy, xx] * 3) + 1] * 2; bb = paletteData[(pxdata[yy, xx] * 3) + 1] * 2; } b.SetPixel(xx, yy, Color.FromArgb(aa, rr, gg, bb)); } } Graphics g = Graphics.FromImage(bmp); g.DrawImage(b, new Point(xPos, pt.Y)); xPos += charWidth; } else { // Add spacing to next char xPos += spaceWidth; } } return xEnd; } public int getWidth(string msg, int spaceWidth) { int width = 0; char[] text = Encoding.ASCII.GetChars(Encoding.ASCII.GetBytes(msg)); if (msg.Length > 0) { for (int i = 0; i < text.Length; i++) { width += charWidths[text[i] & 0x7F] + spaceWidth; } width -= spaceWidth; } return width; } public int getBpp(int charWidth) { if (charWidth > 12) return 4; else if (charWidth > 8) return 3; else if (charWidth > 4) return 2; else return 1; } } }
using Psub.DataService.HandlerPerQuery.PublicationCommentProcess.Entities; namespace Psub.DataService.Abstract { public interface IPublicationCommentService { PublicationCommentListItem Save(int objectId, string text, int commentId); ListPublicationComment GetPublicationCommentsByPublicationId(int id, int pageSize, int pageNumber); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ArteVida.GestorWeb.ViewModels { public class AtletaViewModel { public int PessoaId { get; set; } [Display(Name = "Ficha nº")] public string NumeroFicha { get; set; } [Display(Name = "Nome")] [Required(ErrorMessage = "O campo NOME deve ser preenchido.")] public string Nome { get; set; } [Display(Name = "Endereço")] public string Endereco { get; set; } public string Bairro { get; set; } public string Cidade { get; set; } public string Estado { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [Display(Name = "Data Cadastro")] public DateTime? DataCadastro { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [Display(Name = "Data Nascimento")] public DateTime? DataNascimento { get; set; } public string Rg { get; set; } //[StringLength(11)] public string Cpf { get; set; } //[StringLength(1)] public string Sexo { get; set; } public int? Idade { get; set; } public string Telefone { get; set; } public string Escola { get; set; } public string Serie { get; set; } public string Pai { get; set; } [Display(Name = "Telefone Pai")] public string TelefonePai { get; set; } [Display(Name = "Mãe")] public string Mae { get; set; } [Display(Name = "Telefone Mãe")] public string TelefoneMae { get; set; } public string Modalidade { get; set; } public string NomePais { get; set; } public string TelefonePais { get; set; } } }
namespace DbIntegrationTestsWithContainers { using System.Data.SqlClient; using System.Threading.Tasks; using Dapper; using Xunit; public class MovieTests : IClassFixture<MovieFixture> { private readonly MovieFixture fixture; public MovieTests(MovieFixture fixture) { this.fixture = fixture; } [Fact] public async Task CountQuery_ShouldRunSuccessfully() { using (var conn = new SqlConnection(fixture.ConnectionString)) { conn.Open(); var total = await conn.ExecuteScalarAsync(@"SELECT COUNT(1) from Movie"); Assert.Equal(9, total); } } [Theory] [InlineData("George Lucas", 4)] [InlineData("J.J. Abrams", 2)] [InlineData("Irvin Kershner", 1)] public async Task CountMoviesByDirector_ShouldRunSuccessfully(string director, int expectedTotal) { using (var conn = new SqlConnection(fixture.ConnectionString)) { conn.Open(); var total = await conn.ExecuteScalarAsync(@"SELECT COUNT(1) FROM Movie WHERE Director = @Director", new { Director = director }); Assert.Equal(expectedTotal, total); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Diagnostics; namespace Circuits { class InputSource : Gate { public InputSource(int x, int y) : base(x, y) { pins.Add(new Pin(this, false, 20)); MoveTo(x, y); } public override bool IsMouseOn(int x, int y) { if (left <= x && x < left + WIDTH && top <= y && y < top + HEIGHT) return true; else return false; } public override void Draw(Graphics paper) { if (selected) { paper.DrawImage(Properties.Resources.Input_Yellow, left, top); } else { paper.DrawImage(Properties.Resources.Input, left, top); } foreach (Pin p in pins) p.Draw(paper); } public override void MoveTo(int x, int y) { Debug.WriteLine("pins = " + pins.Count); left = x; top = y; } } }
using EcobitStage.DataTransfer; namespace EcobitStage.ViewModel.DataViewModel { public interface ITransfer { DTO ConvertToDTO(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Model.Locale; using Utility; namespace Model.Models.ViewModel { public class InvoiceViewModel : QueryViewModel { public InvoiceViewModel() { InvoiceType = 7; InvoiceDate = DateTime.Now; TaxAmount = 1; No = "00000000"; RandomNo = String.Format("{0:0000}",(DateTime.Now.Ticks % 10000)); TaxRate = 0.05m; DonateMark = "0"; } public int? SellerID { get; set; } public String SellerName { get; set; } public String SellerReceiptNo { get; set; } public String BuyerReceiptNo { get; set; } public String No { get; set; } public DateTime? InvoiceDate { get; set; } public String Remark { get; set; } public String BuyerRemark { get; set; } public byte? CustomsClearanceMark { get; set; } public byte? InvoiceType { get; set; } public byte? TaxType { get; set; } public decimal? TaxRate { get; set; } public String RandomNo { get; set; } public string DonateMark { get; set; } public string CarrierType { get; set; } public string CarrierId1 { get; set; } public string CarrierId2 { get; set; } public string NPOBAN { get; set; } public string CustomerID { get; set; } public string BuyerName { get; set; } public String TrackCode { get; set; } public String DataNumber { get; set; } public decimal? TotalAmount { get; set; } public decimal? SalesAmount { get; set; } public decimal? TaxAmount { get; set; } public decimal? DiscountAmount { get; set; } public String[] Brief { get; set; } public String[] ItemNo { get; set; } public String[] ItemRemark { get; set; } public decimal?[] UnitCost { get; set; } public decimal?[] CostAmount { get; set; } public int?[] Piece { get; set; } public bool? Counterpart { get; set; } public string Phone { get; set; } public string Address { get; set; } public string EMail { get; set; } public byte? BuyerMark { get; set; } public string CheckNo { get; set; } public string RelateNumber { get; set; } public string Category { get; set; } public Naming.InvoiceProcessType? InvoiceProcessType { get; set; } public bool? ForPreview { get; set; } public bool? B2BRelation { get; set; } } public class InvoiceBuyerViewModel : QueryViewModel { public int? InvoiceID { get; set; } public String ReceiptNo { get; set; } public String PostCode { get; set; } public String Address { get; set; } public String Name { get; set; } public int? BuyerID { get; set; } public String CustomerID { get; set; } public String ContactName { get; set; } public String Phone { get; set; } public String EMail { get; set; } public String CustomerName { get; set; } public String Fax { get; set; } public String PersonInCharge { get; set; } public String RoleRemark { get; set; } public String CustomerNumber { get; set; } public int? BuyerMark { get; set; } } public class AllowanceViewModel : QueryViewModel { public AllowanceViewModel() { AllowanceType = Naming.AllowanceTypeDefinition.賣方開立; } public int? AllowanceID { get; set; } public String AllowanceNumber { get; set; } public Naming.AllowanceTypeDefinition? AllowanceType { get; set; } public DateTime? AllowanceDate { get; set; } public decimal? TotalAmount { get; set; } public decimal? TaxAmount { get; set; } public int? SellerID { get; set; } public String BuyerReceiptNo { get; set; } public String BuyerName { get; set; } public int? InvoiceID { get; set; } public Naming.InvoiceProcessType? ProcessType { get; set; } public int?[] ItemID { get; set; } public short[] No { get; set; } public String[] InvoiceNo { get; set; } public decimal?[] Piece { get; set; } public decimal?[] Amount { get; set; } public decimal[] Tax { get; set; } public DateTime[] InvoiceDate { get; set; } public short?[] OriginalSequenceNo { get; set; } public String[] PieceUnit { get; set; } public String[] OriginalDescription { get; set; } public Naming.TaxTypeDefinition[] TaxType { get; set; } public decimal?[] UnitCost { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using JoveZhao.Framework.DDD; namespace BPiaoBao.SystemSetting.Domain.Models.Behavior { public interface IBehaviorStatRepository : IRepository<BehaviorStat> { } }
using System.ComponentModel; using DiabloStats.Database.Model; using DiabloStats.Diablo; namespace DiabloStats.Meter { public interface IMeterHandler { MeterOptions Meter { get; set; } bool Visible { get; set; } event PropertyChangedEventHandler PropertyChanged; void Update(Helper helper); void TriggerRefresh(); IMeterOverlay GetOverlay(); } }
namespace CTB.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class CTB_CONTR { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public CTB_CONTR() { CTB_CONTR_ACT_ECO = new HashSet<CTB_CONTR_ACT_ECO>(); } [Key] public long CONTR_COD { get; set; } public long? PER_COD { get; set; } [Display(Name = "RUC")] [StringLength(15)] public string CONTR_DOC_TRI { get; set; } [StringLength(1)] public string CONTR_ULT_DIG_DOC_TRI { get; set; } [StringLength(120)] public string CONTR_NOM_COM { get; set; } [StringLength(2)] public string CONTR_TIP { get; set; } [Column(TypeName = "date")] public DateTime? CONTR_FEC_INSC { get; set; } [StringLength(1)] public string CONTR_EST { get; set; } [StringLength(1)] public string CONTR_COND { get; set; } [StringLength(30)] public string CONTR_USU_SOL { get; set; } [StringLength(30)] public string CONTR_CLA_SOL { get; set; } [StringLength(30)] public string CONTR_COD_ENV { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CTB_CONTR_ACT_ECO> CTB_CONTR_ACT_ECO { get; set; } public virtual GEN_PER GEN_PER { get; set; } } }
namespace Micro.Net { public class MicroHostConfiguration { public string Assembly { get; set; } public string ConfigClass { get; set; } } }
using System; using System.Data.Entity; namespace Click.Data { public class ClickDbContext : DbContext { public DbSet<Counter> Counters { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Binding { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { public Car MyCar { get; set; } public ObservableCollection<Car> Cars { get; set; } private string someText; public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string name = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } public string SomeText { get { return someText; } set { someText = value; OnPropertyChanged(); } } public MainWindow() { InitializeComponent(); SomeText = "Salam"; this.DataContext = this; MyCar = new Car { Model = "X7", Vendor = "BMW", Year = 2021 }; Cars = new ObservableCollection<Car> { new Car { Model="Cruze", Vendor="Chevrolet", Year=2015 }, new Car { Model="CLS", Vendor="Mercedes", Year=2015 }, new Car { Model="Quadraporte", Vendor="Maseratti", Year=2015 } }; } private void Button_Click_1(object sender, RoutedEventArgs e) { MyCar.Model = "Best Model"; } private void Button_Click(object sender, RoutedEventArgs e) { var linear = new LinearGradientBrush(); linear.GradientStops.Add(new GradientStop { Color = Colors.Red, Offset = 0 }); linear.GradientStops.Add(new GradientStop { Color = Colors.Black, Offset = 1 }); this.Resources["PrimaryColor"] = linear; } private void addBtn_Click(object sender, RoutedEventArgs e) { var car = new Car { Model = "La ferrari", Vendor = "Ferrari", Year = 2020 }; Cars.Add(car); } private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var infoWindow = new InfoWindow(); //infoWindow.InfoCar = listbox.SelectedItem as Car; infoWindow.Car = listbox.SelectedItem as Car; infoWindow.ShowDialog(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CTDLGT.Danh_sách_liên_kết { public class GenericList<T> : ICollection<T> { // Định nghĩa phần tử của danh sách là Node public class Node { T data; // phần dữ liệu của Node Node next = null; // next trỏ đến Node tiếp theo // Contructor Node với dữ liệu t public Node() { } public Node(T t) { next = null; data = t; } // Định nghĩa các thuộc tính (Propeties) public T Data { get { return data; } set { data = value; } } public Node Next { get { return next; } set { next = value; } } } // khai báo các thành phần của ds liên kết // head : trỏ đến đầu ds // last : trỏ đến cuối ds, phần do sinh viên làm thêm Node head = null; public Node Head //Expose a public property to get to head of the list { get { return head; } } int ICollection<T>.Count => throw new NotImplementedException(); public bool IsReadOnly => throw new NotImplementedException(); Node last = null; public int Count; // phương thức khai báo trả về một phần tử với dữ liệu trừu tượng // chương trình (bài 23) áp dụng phương thức này mới cụ thể dữ liệu data public IEnumerator<T> GetEnumerator() { var p = head; while (p != null) { yield return p.Data; p = p.Next; } } /*LinkedList<int> linkedList = new LinkedList<int>(new List<int> { 1, 2, 3, 4 }); */ public GenericList() { } public GenericList(IEnumerable<T> initalize) { foreach (T item in initalize) { AddLast(item); } } /* Thêm vào Đầu danh sách(AddHead): Giải thích * Vì head chính là Node đầu tiên vì thế ta chỉ cần cập nhật lại head là xong *Cho Next của n (như là sợi dây) trỏ hay buộc vào head. Lúc này head chính là Node đầu tiên thì cập nhật lại head chính là n; */ #region method phụ public bool Isempty() => head == null; public int Length() { var size = 0; var P = head; while (P != null) { size++; P = P.Next; } return size; } public int count(T search_for) { var current = head; var phu = 0; while (current != null) { if (!Equals(current.Data, search_for)) phu++; current = current.Next; } return phu; } public T GetHeadData() { //This trick can be used instead of using an else //The method returns the default value for the type T var temp = default(T); if (head != null) { temp = head.Data; } return temp; } public T GetEndAdded() { // The value of temp is returned as the value of the method. // The following declaration initializes temp to the appropriate // default value for type T. The default value is returned if the // list is empty. var temp = default(T); var current = head; while (current != null) { temp = current.Data; current = current.Next; } return temp; } public void Clear() { head = null; last = null; Count = 0; } #endregion #region method chính public void Reverse() { Node prev = null; var current = head; if (current == null) return; while (current != null) { var next = current.Next; current.Next = prev; prev = current; current = next; } head = prev; } public bool isSortedAsc(Node head, IComparer<T> cmp) { // Base cases if (head == null || head.Next == null) return true; // Check first two nodes and recursively // check remaining. return (cmp.Compare(head.Data, head.Next.Data) < 0 && isSortedAsc(head.Next, cmp)); } public void Delete(T value) { if (head == null) return; if (Equals(head.Data, value)) { head = head.Next; return; } var n = head; while (n.Next != null) { if (Equals(n.Next.Data, value)) { n.Next = n.Next.Next; return; } n = n.Next; } } public void Addhead(T t) { var n = new Node(t); if (Isempty()) { head = last = n; } else { n.Next = head;// đem Next của Node n vừa tạo trỏ đến head hiện tại head = n;//cập nhập lại giá trị head } Count++; } public void AddLast(T t) { var newNode = new Node(t); if (Isempty()) { head = last = newNode; } else { last.Next = newNode; //gán lại Next của Node cuối cùng (cũ) sẽ trỏ đến Node mới. last = newNode; //cập nhập lại giá trị last,bây giờ Node cuối của danh sách là Node chúng ta vừa thêm. Count++; } } public void AddLast2(T t) { var n = new Node(t); Node p, q; p = head; q = new Node(); while (p != null) { q = p; p = p.Next; } q.Next = n; } public void Addpos(T t, int pos) { var P = new Node(t); var Q = head; var i = 1; var size = 0; while (Q != null) { size++; Q = Q.Next; } if (pos < 1 && pos > size) Console.WriteLine("Vi tri ko hop le"); else { if (pos == 1) Addhead(t); //chen vao vi tri dau tien else { while (Q != null && i != pos - 1) //duyet den vi tri k-1 { i++; Q = Q.Next; } P.Next = Q.Next;// gán Next của Node mới bằng địa chỉ của Node sau q Q.Next = P;// cập nhập lại Next của Node q trỏ đến Node mới. } } } public int SearchNode1(T t) { var temp = head; var i = 1; while (temp != null && string.Compare(temp.Data.ToString(), t.ToString(), StringComparison.CurrentCulture) != 0) { temp = temp.Next; i = i + 1; } if (temp != null) { return i; } return 0; } public bool SearchNode2(T item) { var temp = this.head; var matched = false; while (!(matched = temp.Data.ToString().Equals(item.ToString())) && temp.Next != null) { temp = temp.Next; } return matched; } public int SearchNode3(T item) { for (Node p = head; p != null; p = p.Next) { if (string.Compare(p.Data.ToString(), item.ToString(), StringComparison.CurrentCulture) == 0) return 1; } return 0; } public int countoccurentx(T search_for) { var current = head; var dem = 0; while (current != null) { if (Equals(current.Data, search_for)) dem++; current = current.Next; } return dem; } public void RemoveFromStart() { if (Count > 0) { head = head.Next;// chuyen con tro cua cai head dau tien qua cai head tiep theo Count--; } else { Console.WriteLine("No element exist in this linked list."); } } public void RemoveAt(int k) { var P = head; var i = 1; var size = Length(); if (k < 1 && k > size) Console.WriteLine("Vi tri ko hop le"); else { if (k == 1) RemoveFromStart(); else { while (P != null && i != k - 1) //duyet den vi tri k-1 { P = P.Next; i++; // khi i = k -1 thì i sẽ dừng } P.Next = P.Next.Next; //cho P tro sang Node ke tiep vi tri k } } } public void Remove(T t) { var ps = SearchNode1(t); if (ps == 0) return; else { RemoveAt(ps); } } public void SelectionSort(IComparer<T> cmp) { var currentOuter = head; while (currentOuter != null) { var minimum = currentOuter; var currentInner = currentOuter.Next; while (currentInner != null) { if (cmp.Compare(currentInner.Data, minimum.Data) < 0) { minimum = currentInner; } currentInner = currentInner.Next; } if (!Object.ReferenceEquals(minimum, currentOuter)) { var temp = currentOuter.Data; currentOuter.Data = minimum.Data; minimum.Data = temp; } currentOuter = currentOuter.Next; } } public void deleteX(T t)//xóa x còn 1 lần { var k = countoccurentx(t); Console.WriteLine(k); if (k > 1) { for (int i = 0; i < k - 1; i++) { Remove(t); } } } public void deleteallofX(T t) { var k = countoccurentx(t); if (k >= 1) { for (int i = 0; i < k; i++) { Remove(t); } } } public bool ListEmpty() { return head == null ? true : false; } // Lấy phần tử đầu danh sách public T Pop() { var n = head; head = n.Next; return n.Data; } // Lấy giá trị đầu danh sách public T Top() { return head.Data; } public void MergeSortedList(Node first, Node second) { if (Convert.ToInt32(first.Next.Data.ToString()) > Convert.ToInt32(second.Data.ToString())) { var t = first; first = second; second = t; } head = first; while ((first.Next != null) && (second != null)) { if (Convert.ToInt32(first.Next.Data.ToString()) < Convert.ToInt32(second.Data.ToString())) { first = first.Next; } else { var n = first.Next; var t = second.Next; first.Next = second; second.Next = n; first = first.Next; second = t; } } if (first.Next == null) first.Next = second; } public void PrintAllNodes() { //Traverse from head Console.Write("Head "); var curr = head; while (curr != null) { Console.Write("-> "); Console.Write(curr.Data); curr = curr.Next; } Console.Write("-> NULL"); Console.WriteLine(); } public T[] ToArray() { var result = new T[Length()]; var index = 0; var node = head; while (node != null) { result[index] = node.Data; node = node.Next; } return result; } // TOlIST TUONG TU public void SelectionSort2(IComparer<T> cmp) { Node p, q; p = head; q = null; while (p.Next != null) { q = p.Next; while (q != null) { if (cmp.Compare(p.Data, q.Data) > 0) { var tmp = p; p = q; q = tmp; } q = q.Next; } p = p.Next; } } public T maxnode(IComparer<T> cmp) { var max = head.Data; var p = head.Next; while (p != null) { if (cmp.Compare(p.Data, max) > 0) max = p.Data; p = p.Next; } return max; } public T minnode(IComparer<T> cmp) { var min = head.Data; var p = head.Next; while (p != null) { if (cmp.Compare(p.Data, min) < 0) min = p.Data; p = p.Next; } return min; } public void CopyTo(T[] array, int arrayIndex) { var current = head; while (current != null) { array[arrayIndex++] = current.Data; current = current.Next; } } public bool Contains(T value) { var current = head; while (current != null) { if (current.Next.Equals(value)) { return true; } current = current.Next; } return false; } public void Add(T item) { throw new NotImplementedException(); } bool ICollection<T>.Remove(T item) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Web; using System.Web.Services; using System.Xml; using eIVOGo.Properties; using Model.DataEntity; using Model.Helper; using Model.InvoiceManagement; using Model.Locale; using Model.Schema.EIVO; using Model.Schema.TurnKey; using Model.Schema.TXN; using Utility; using Uxnet.Com.Security.UseCrypto; using System.IO; using System.Data; using eIVOGo.Helper; using Model.Security.MembershipManagement; using eIVOGo.Module.Common; namespace eIVOGo.Published { public partial class eInvoiceService { [WebMethod] public virtual XmlDocument UploadInvoiceBuyerCmsCSV(byte[] uploadData) { Root result = createMessageToken(); try { CryptoUtility crypto = new CryptoUtility(); byte[] dataToSign; if (crypto.VerifyEnvelopedPKCS7(uploadData, out dataToSign)) { String fileName = Path.Combine(Logger.LogDailyPath, String.Format("InvoiceBuyer_{0}.csv", Guid.NewGuid())); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(dataToSign, 0, dataToSign.Length); fs.Flush(); fs.Close(); } using (InvoiceManager mgr = new InvoiceManager()) { ///憑證資料檢查 /// var token = mgr.GetTable<OrganizationToken>().Where(t => t.Thumbprint == crypto.SignerCertificate.Thumbprint).FirstOrDefault(); if (token != null) { BranchBusinessCounterpartUploadManager csvMgr = new BranchBusinessCounterpartUploadManager(mgr); csvMgr.BusinessType = Naming.InvoiceCenterBusinessType.銷項; csvMgr.MasterID = token.CompanyID; Encoding encoding = dataToSign.IsUtf8(dataToSign.Length) ? Encoding.UTF8 : Encoding.GetEncoding(Settings.Default.CsvUploadEncoding); csvMgr.ParseData(UserProfileFactory.CreateInstance(Settings.Default.SystemAdmin), fileName, encoding); if (!csvMgr.Save()) { var items = csvMgr.ErrorList; result.Response = new RootResponse { InvoiceNo = items.Select(d => new RootResponseInvoiceNo { Value = d.DataContent, Description = d.Status, ItemIndexSpecified = true, ItemIndex = csvMgr.ItemList.IndexOf(d) }).ToArray() }; ThreadPool.QueueUserWorkItem(ExceptionNotification.SendNotification, new ExceptionInfo { Token = token, BusinessCounterpartError = items }); } else { result.Result.value = 1; } } else { result.Result.message = "營業人憑證資料驗證不符!!"; } } } else { result.Result.message = "發票資料簽章不符!!"; } } catch (Exception ex) { Logger.Error(ex); result.Result.message = ex.Message; } return result.ConvertToXml(); } [WebMethod] public virtual XmlDocument UploadInvoiceCmsCSV(byte[] uploadData) { Root result = createMessageToken(); try { CryptoUtility crypto = new CryptoUtility(); byte[] dataToSign; if (crypto.VerifyEnvelopedPKCS7(uploadData, out dataToSign)) { String fileName = Path.Combine(Logger.LogDailyPath, String.Format("Invoice_{0}.csv", Guid.NewGuid())); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(dataToSign, 0, dataToSign.Length); fs.Flush(); fs.Close(); } using (InvoiceManagerV3 mgr = new InvoiceManagerV3()) { ///憑證資料檢查 /// var token = mgr.GetTable<OrganizationToken>().Where(t => t.Thumbprint == crypto.SignerCertificate.Thumbprint).FirstOrDefault(); if (token != null) { CsvInvoiceUploadManagerV2 csvMgr = new CsvInvoiceUploadManagerV2(mgr, token.CompanyID); csvMgr.DefaultInvoiceType = Naming.InvoiceTypeDefinition.一般稅額計算之電子發票; csvMgr.AutoTrackNo = false; Encoding encoding = dataToSign.IsUtf8(dataToSign.Length) ? Encoding.UTF8 : Encoding.GetEncoding(Settings.Default.CsvUploadEncoding); csvMgr.ParseData(null, fileName, encoding); if (!csvMgr.Save()) { var items = csvMgr.ErrorList; result.Response = new RootResponse { InvoiceNo = items.Select(d => new RootResponseInvoiceNo { Value = d.DataContent, Description = d.Status, ItemIndexSpecified = true, ItemIndex = csvMgr.ItemList.IndexOf(d) }).ToArray() }; ThreadPool.QueueUserWorkItem(ExceptionNotification.SendNotification, new ExceptionInfo { Token = token, InvoiceError = items }); } else { result.Result.value = 1; if (token.Organization.OrganizationStatus.PrintAll == true) { SharedFunction.SendMailMessage(token.Organization.CompanyName + "電子發票已匯入,請執行發票列印作業!!", Settings.Default.WebMaster, token.Organization.CompanyName + "電子發票開立郵件通知"); } } } else { result.Result.message = "營業人憑證資料驗證不符!!"; } } } else { result.Result.message = "發票資料簽章不符!!"; } } catch (Exception ex) { Logger.Error(ex); result.Result.message = ex.Message; } return result.ConvertToXml(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Radix.Domain.RadixContext.Entities; namespace Radix.Domain.RadixContext.Repositories { public interface IEventRepository : IBaseRepository<Event> { Task<IEnumerable<Event>> GetAllEventsByUser(int id); } }
using System; using System.Collections.Generic; namespace CIS4800 { public class Cylinder : Shape { private const int MAX_RESOLUTION = 20; Vertex origin;//"origin" in this shape is the top-centre of the double radius; double height; int resolution; public Cylinder (Vertex o, double r, double h, int res) : base() { origin = o; radius = r; height = h; resolution = res; //assert minimum resolution if (resolution < MAX_RESOLUTION) resolution = MAX_RESOLUTION; base.setEdges (setupCylinder_Polygon ()); } private List<Edge> setupCylinder_Polygon() { List<Edge> ae = new List<Edge> (); //top/bottom of cylinder for (int i = 0; i <= this.resolution; i++) { double angle = 2 * Math.PI / resolution * i; double nextAngle = 2 * Math.PI / resolution * (i + 1); Vertex v1 = new Vertex (Math.Cos (angle), origin.getY (), Math.Sin (angle)); Vertex v2; //top if (i == resolution) { v2 = new Vertex (Math.Cos (0), origin.getY (), Math.Sin (0)); } else { v2 = new Vertex (Math.Cos (nextAngle), origin.getY (), Math.Sin (nextAngle)); } ae.Add (new Edge (v1, v2)); //bottom v1 = new Vertex(Math.Cos (angle), origin.getY () - height, Math.Sin (angle)); Vertex v3; if (i == resolution) { v3 = new Vertex (Math.Cos (0), origin.getY () - height, Math.Sin (0)); } else { v3 = new Vertex (Math.Cos (nextAngle), origin.getY () - height, Math.Sin (nextAngle)); } ae.Add (new Edge (v1, v3)); //add sides ae.Add (new Edge (v2, v3)); } return ae; } } }
using System; class GetLargestNumber { //Write a method GetMax() with two parameters that returns the larger of two integers. //Write a program that reads 3 integers from the console and prints the largest of them using the method GetMax(). static void Main() { Console.Write("Enter your first number: "); int firstNumber = int.Parse(Console.ReadLine()); Console.Write("Enter your second number: "); int secondNumber = int.Parse(Console.ReadLine()); Console.Write("Enter your third number: "); int thirdNumber = int.Parse(Console.ReadLine()); Console.WriteLine("The biggest number of {0}, {1} and {2} is {3}.", firstNumber, secondNumber, thirdNumber, GetMaxOfThree(firstNumber, secondNumber, thirdNumber)); } static int GetMax(int a, int b) { int largestNumber = Math.Max(a, b); return largestNumber; } static int GetMaxOfThree(int a, int b, int c) { int largestOfThree = GetMax(GetMax(a, b), c); return largestOfThree; } }
using BB.Common.WinForms; using Nancy; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Appy.Core; using Appy.Core.Nancy; using Appy.Core.Themes; using Splash.Services; using Splash.Models; namespace Splash.Modules { public class SplashModule : NancyModule { public SplashModule() { Get["/"] = parameters => { return View["index"]; }; } } }
 using System; using System.Data; using System.Collections.Generic; using Maticsoft.Common; using PDTech.OA.Model; namespace PDTech.OA.BLL { /// <summary> /// 风险类型定义表 /// </summary> public partial class RISK_TYPE_INFO { private readonly PDTech.OA.DAL.RISK_TYPE_INFO dal=new PDTech.OA.DAL.RISK_TYPE_INFO(); public RISK_TYPE_INFO() {} #region BasicMethod /// <summary> /// 获取 /// </summary> /// <param name="where"></param> /// <returns></returns> public IList<Model.RISK_TYPE_INFO> get_risktypeList(Model.RISK_TYPE_INFO where) { return dal.get_risktypeList(where); } #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
using System.Collections.Generic; using System; using System.Collections; namespace perceptron_net { public enum Operators { OR = 1, AND = 2, NAND = 3, XOR = 4 } public class TrainingData { public double[] Input { get; set; } public double CorrectVal { get; set; } public TrainingData(double correctVal, params double[] inputs) { Input = inputs; CorrectVal = correctVal; } } public class TrainingDataGenerator { public List<TrainingData> Data { get; set; } public TrainingDataGenerator(int numberOfItems, Operators caseVal) { Data = new List<TrainingData>(); for (int i = 0; i < numberOfItems; i++) { int val1 = new System.Random().Next(0, 2); int val2 = new System.Random().Next(0, 2); BitArray resultBits = CalculateExpected(caseVal, val1, val2); double result = Convert.ToDouble(ToNumeral(resultBits)); System.Console.WriteLine($"Training data generation: {val1} val1 {caseVal.ToString()} {val2} val2 is {result}"); Data.Add(new TrainingData(result, Convert.ToDouble(val1), Convert.ToDouble(val2))); } } public int ToNumeral(BitArray binary) { if (binary == null) throw new ArgumentNullException("binary"); if (binary.Length > 32) throw new ArgumentException("must be at most 32 bits long"); var result = new int[1]; binary.CopyTo(result, 0); return result[0]; } public BitArray CalculateExpected(Operators caseVal, int val1, int val2) { switch (caseVal) { // OR case Operators.OR: return new BitArray(BitConverter.GetBytes(val1)).Or(new BitArray(BitConverter.GetBytes(val2))); // AND case Operators.AND: return new BitArray(BitConverter.GetBytes(val1)).And(new BitArray(BitConverter.GetBytes(val2))); // NAND case Operators.NAND: return new BitArray(BitConverter.GetBytes(val2)).Not().And(new BitArray(BitConverter.GetBytes(val1))); // XOR case Operators.XOR: return new BitArray(BitConverter.GetBytes(val1)).Xor(new BitArray(BitConverter.GetBytes(val2))); default: return new BitArray(2); } } } }
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp2 { public class Person { private String name; public void SetName(String aName) { name = aName; } public String GetName() { return name; } } }
using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using PyTK.CustomElementHandler; using StardewValley; using StardewModdingAPI; using StardewValley.Objects; using MusicBlocks.Common; using System; namespace MusicBlocks.Instruments { internal class KeyboardBlock : Block, ISaveElement, ICustomObject { public KeyboardBlock() { this.Build(); } public override void Build() { base.Build(); this.Texture = ModEntry._helper.Content.Load<Texture2D>(@"assets\Keyboard.png", ContentSource.ModFolder); this.name = "Keyboard Block"; this.boundingBox.Value = new Rectangle((int)this.tileLocation.X * 64, (int)this.tileLocation.Y * 64, 64, 64); menu = new Menu(new string[] { "Piano" }); } public override string getDescription() { return "Keyboard."; } public override Item getOne() { return new KeyboardBlock(); } public override object getReplacement() { return base.getReplacement(); } public override Dictionary<string, string> getAdditionalSaveData() { return base.getAdditionalSaveData(); } public override void rebuild(Dictionary<string, string> additionalSaveData, object replacement) { base.rebuild(additionalSaveData, replacement); } public ICustomObject recreate(Dictionary<string, string> additionalSaveData, object replacement) { KeyboardBlock keyboard = new KeyboardBlock(); keyboard.menu.sca = additionalSaveData["sca"]; keyboard.menu.gro = additionalSaveData["gro"]; keyboard.menu.dur = additionalSaveData["dur"]; keyboard.menu.labels[menu.labelIndex] = additionalSaveData["sou"]; keyboard.menu.value = Convert.ToSingle(additionalSaveData["vol"]); keyboard.tileLocation.Value = StringToVector2(additionalSaveData["tile"]); return keyboard; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Exercicio4 : Form { public Exercicio4() { InitializeComponent(); textBoxOrdemCrescente.Enabled = false; } private void button1_Click(object sender, EventArgs e) { int numero1, numero2, numero3; numero1 = Convert.ToInt32(textBoxNumero1.Text); numero2 = Convert.ToInt32(textBoxNumero2.Text); numero3 = Convert.ToInt32(textBoxNumero3.Text); if(numero1 <= numero2 && numero1 <= numero3 && numero2 <=numero3) { textBoxOrdemCrescente.Text = numero1.ToString() + ", "+ numero2.ToString() +", "+ numero3.ToString(); } else if (numero1 <= numero2 && numero1 <= numero3 && numero3 <= numero2) { textBoxOrdemCrescente.Text = numero1.ToString() + ", " + numero3.ToString() + ", " + numero2.ToString(); } else if (numero2 <= numero1 && numero2 <= numero3 && numero1 <= numero3) { textBoxOrdemCrescente.Text = numero2.ToString() + ", " + numero1.ToString() + ", " + numero3.ToString(); } else if (numero2 <= numero1 && numero2 <= numero3 && numero3 <= numero1) { textBoxOrdemCrescente.Text = numero2.ToString() + ", " + numero3.ToString() + ", " + numero1.ToString(); } else if (numero3 <= numero1 && numero3 <= numero2 && numero1 <= numero2) { textBoxOrdemCrescente.Text = numero3.ToString() + ", " + numero1.ToString() + ", " + numero2.ToString(); } else if (numero3 <= numero1 && numero3 <= numero2 && numero2 <= numero1) { textBoxOrdemCrescente.Text = numero3.ToString() + ", " + numero2.ToString() + ", " + numero1.ToString(); } } private void Exercicio3_Load(object sender, EventArgs e) { } private void button1_Click_1(object sender, EventArgs e) { textBoxNumero1.Clear(); textBoxNumero2.Clear(); textBoxNumero3.Clear(); textBoxOrdemCrescente.Clear(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace NppFormatPlugin.DpTools { public class DpTools { protected const string c_NewLine = "\r\n"; protected const string c_HorizontalSpace = "\t"; protected const char c_OpeningTag = '<'; protected const char c_ClosingTag = '>'; protected string m_unformatedString; // State variables protected int m_ColumnCount = 0; protected char m_LastControlCharacter = char.MinValue; protected bool m_IsFirstOpening = true; public DpTools(string unformatedString) { this.m_unformatedString = unformatedString; } public void Load(string unformattedString) { this.m_unformatedString = unformattedString; this.m_ColumnCount = 0; this.m_LastControlCharacter = char.MinValue; this.m_IsFirstOpening = true; } public string Format() { Stopwatch stopWatch = Stopwatch.StartNew(); StringBuilder formatedStringBuilder = new StringBuilder(); char currentChar; string toAppend = string.Empty; for (int i = 0; i < m_unformatedString.Length; ++i) { currentChar = m_unformatedString[i]; toAppend = string.Empty; if (this.IsOpeningCharacter(currentChar)) { // erstes < if (m_IsFirstOpening) { // erster '<' -> kein NewLine! m_IsFirstOpening = false; toAppend = Convert.ToString(currentChar); } // nicht erstes < else { // was war davor if (m_LastControlCharacter == c_OpeningTag) { // nur wenn < nach < kommt dann weiter ruecken this.m_ColumnCount += 1; } toAppend = c_NewLine + this.CreateHorizontalSpace(this.m_ColumnCount) + Convert.ToString(currentChar); } this.m_LastControlCharacter = c_OpeningTag; } else if (this.IsClosingCharacter(currentChar)) { // closing > if (m_LastControlCharacter == c_OpeningTag) { // > nach < toAppend = Convert.ToString(currentChar); } else { // > nach > this.m_ColumnCount -= 1; toAppend = c_NewLine + this.CreateHorizontalSpace(this.m_ColumnCount) + Convert.ToString(currentChar); } this.m_LastControlCharacter = c_ClosingTag; } else { toAppend = Convert.ToString(currentChar); } formatedStringBuilder.Append(toAppend); } stopWatch.Stop(); return formatedStringBuilder.ToString(); } protected bool IsControlCharacter(char c) { return (c == c_OpeningTag) || (c == c_ClosingTag); } protected bool IsOpeningCharacter(char c) { return (c == c_OpeningTag); } protected bool IsClosingCharacter(char c) { return (c == c_ClosingTag); } protected string CreateHorizontalSpace(int horizontalCount) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < horizontalCount; ++i) { sb.Append(c_HorizontalSpace); } return sb.ToString(); } } }
namespace PaderbornUniversity.SILab.Hip.EventSourcing { public interface IEntity<TKey> { TKey Id { get; } } }
using System.Linq; using System.Threading.Tasks; using CCCP.DAL.Repositories; using CCCP.Telegram.Core; using Telegram.Bot; using Telegram.Bot.Types; using User = CCCP.DAL.Entities.User; namespace CCCP.Telegram { public static class Statistics { public static async Task SendUserStats(this TelegramBotClient bot, Message message, User userInfo, RegistrationRepository registrationRepository, int savedCups) { var totalSubmitCount = userInfo.TotalSubmitCount; string registrationInfo = null; var registrations = registrationRepository.GetRegistrations(userInfo.Id).ToList(); if (registrations.Any()) { var firstRegistration = registrations.First(); var lastRegistration = registrations.Last(); registrationInfo = $"First registration: {firstRegistration.Timestamp}\n" + $"Last registration: {lastRegistration.Timestamp}"; } await bot.Send(message, $"Total submitted: {totalSubmitCount} of total: {savedCups}.\n\n" + $"{registrationInfo}", false); } public static async Task SendStatsExtended(this TelegramBotClient bot, Message message, RegistrationRepository registrationRepository, int savedCups) { var firstAndLastRegistration = registrationRepository.GetFirstAndLastRegistrations(); await bot.Send(message, $"{Helpers.TotalSavedText(savedCups)}\n\n" + $"Tower size: {Helpers.GetTotalTowerSize(savedCups):#.##} meters.\n" + $"Total length: {Helpers.GetTotalLength(savedCups):#.##} meters.\n\n" + $"First registration: {firstAndLastRegistration.Item1.Timestamp}.\n" + $"Last registration: {firstAndLastRegistration.Item2.Timestamp}.\n", false); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TitleButton : MonoBehaviour { public HoverButton hoverButton; public GreyscaleImage image; public bool IsLocked { get; protected set; } private void Start() { //Lock(); } public void Lock() { hoverButton.interactable = false; image.greyscale = true; } public void Unlock() { hoverButton.interactable = true; image.greyscale = false; } }
using System; using System.Collections.Generic; using System.Linq; namespace Simpler.Core.Tasks { public class DisposeTasks : InTask<DisposeTasks.Input> { public class Input { public Task Owner { get; set; } public string[] InjectedTaskNames { get; set; } } public override void Execute() { var taskNames = new List<string>(In.InjectedTaskNames); var properties = In.Owner.GetType().GetProperties(); foreach (var property in properties.Where( property => property.PropertyType.IsSubclassOf(typeof(Task)) && taskNames.Contains(property.PropertyType.FullName) && (property.GetValue(In.Owner, null) != null) && (property.PropertyType.GetInterface(typeof(IDisposable).FullName) != null))) { ((IDisposable) property.GetValue(In.Owner, null)).Dispose(); property.SetValue(In.Owner, null, null); } } } }
 namespace Stock { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; /// <summary> /// Represents a single stock group. /// </summary> public class StockGroup { #region Constants and Fields private List<StockDataPoint> dataPoints; private String name; #endregion #region Constructors and Destructors public StockGroup(string name, List<StockDataPoint> dataPoints) { this.dataPoints = dataPoints; this.name = name; } #endregion #region Public Properties /// <summary> /// Gets or sets the list of the data points in this stockGroup. /// </summary> public List<StockDataPoint> DataPoints { get { return dataPoints; } set { Contract.Requires(!ReferenceEquals(value, null)); Contract.Ensures(ReferenceEquals(value, DataPoints)); dataPoints = value; } } /// <summary> /// Gets the name of this stock group. /// </summary> public string Name { get { return name; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; using Valve.VR; public class RoomManager : NetworkBehaviour { public SteamVR_Action_Boolean roomSwitch = SteamVR_Input.GetBooleanAction("RoomControl", "RoomSwitch"); public override void OnStartLocalPlayer() { base.OnStartLocalPlayer(); roomSwitch.AddOnChangeListener(OnRoomSwitch, SteamVR_Input_Sources.Any); } public void OnDestroy() { if (!isLocalPlayer) { return; } roomSwitch.RemoveOnChangeListener(OnRoomSwitch, SteamVR_Input_Sources.Any); } private void OnRoomSwitch(SteamVR_Action_Boolean fromAction, SteamVR_Input_Sources fromSource, bool newState) { if (!newState) { return; } if (!isLocalPlayer) { return; } if (!isServer) { return; } CmdChangeToNextRoom(); } [Command] private void CmdChangeToNextRoom() { CustomNetworkManager networkManager = FindObjectOfType<CustomNetworkManager>(); networkManager.ChangeToNextRoom(); } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SalemOptimizer { public static class InspirationalDatabase { private static readonly Lazy<List<Inspirational>> inspirationals = new Lazy<List<Inspirational>>(Load); public static List<Inspirational> Inspirationals { get { return inspirationals.Value; } } static List<Inspirational> Load() { return File.ReadAllLines("Inspirationals.tab") .Select(row => row.Split('\t')) .Select ( (cols, index) => new Inspirational ( cols[0], int.Parse(cols[18]), cols .Select((val, idx) => new { Index = idx, Value = val }) .Where(i => i.Index >= 2 && i.Index <= 16) .OrderBy(i => i.Index) .Select(i => string.IsNullOrWhiteSpace(i.Value) ? 0 : int.Parse(i.Value)) .ToArray(), int.Parse(cols[19]) ) ) .Where(i => i.Proficiencies.Length > 0) .Select((inspirational, index) => { inspirational.Id = index; return inspirational; }) .ToList(); } public static string InspToLine(Inspirational insp) { string line = String.Concat(insp.Name, "\t\t"); foreach (int i in insp.Proficiencies) { if(i>0) line = String.Concat(line, i.ToString()); line = String.Concat(line, "\t"); } line = String.Concat(line, insp.Inspiration.ToString(),"\t"); line = String.Concat(line, insp.Uses.ToString(),"\t"); line = String.Concat(line, insp.Diff.ToString()); return line; } public static void SaveToFile(string filename) { string[] list = new string[Inspirationals.Count]; int i = 0; foreach (Inspirational insp in Inspirationals) { list[i] = InspToLine(insp); i++; } File.WriteAllLines(filename, list); } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Threading.Tasks; using MediaManager.API.Helpers; using MediaManager.API.Models; using MediaManager.API.Repository; using MediaManager.API.Services; using MediaManager.DAL.DBEntities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; namespace MediaManager.API.Controllers { /// <summary> /// Controller class to handle web API request related to Users /// </summary> [Authorize] [EnableCors("AnyGET")] [Route("api/Users")] public class UserController : Controller { private UserRepository userRepository; private ITypeHelperService typeHelperService; private IPropertyMappingService propertyMappingService; private IUrlHelper urlHelper; private object CreateLinksForUsers(UserResourceParameter parameter, bool hasNext, bool hasPrevious) { var links = new List<LinkDTO>(); links.Add(new LinkDTO(GenerateUsersResourceUri(parameter, ResourceUriType.Current), "self", "GET")); if (hasNext) links.Add(new LinkDTO(GenerateUsersResourceUri(parameter, ResourceUriType.nextPage), "next", "GET")); if (hasPrevious) links.Add(new LinkDTO(GenerateUsersResourceUri(parameter, ResourceUriType.previousPage), "prev", "GET")); return links; } private string GenerateUsersResourceUri(UserResourceParameter parameter, ResourceUriType uriType) { switch (uriType) { case ResourceUriType.nextPage: return urlHelper.Link("GetUsers", new { parameter = new UserResourceParameter { Username = parameter.Username, searchQuery = parameter.searchQuery, Fields = parameter.Fields, PageNumber = parameter.PageNumber + 1, PageSize = parameter.PageSize, OrderBy = parameter.OrderBy, } }); case ResourceUriType.previousPage: return urlHelper.Link("GetUsers", new { parameter = new UserResourceParameter { Username = parameter.Username, searchQuery = parameter.searchQuery, Fields = parameter.Fields, PageNumber = parameter.PageNumber - 1, PageSize = parameter.PageSize, OrderBy = parameter.OrderBy, } }); default: case ResourceUriType.Current: return urlHelper.Link("GetUsers", new { parameter = new UserResourceParameter { Username = parameter.Username, searchQuery = parameter.searchQuery, Fields = parameter.Fields, PageNumber = parameter.PageNumber, PageSize = parameter.PageSize, OrderBy = parameter.OrderBy, } }); } } private object CreateLinksForUser(string user) { var links = new List<LinkDTO>(); links.Add(new LinkDTO(urlHelper.Link("GetUser", new { username = user }), "self", "GET")); return links; } /// <summary> /// Consructor of User Conroller /// </summary> /// <param name="userRepository">UserRepository</param> /// <param name="typeHelperService">typeHleper service to determine of a property exists on a type</param> /// <param name="urlHelper">urlhelper to help create links</param> /// <param name="propertyMappingService">propertymapping service to map the sort property to database property of the corresponding object</param> public UserController(UserRepository userRepository, ITypeHelperService typeHelperService, IUrlHelper urlHelper, IPropertyMappingService propertyMappingService)//, UserManager<IdentityUser> userManager) { this.userRepository = userRepository; this.typeHelperService = typeHelperService; this.propertyMappingService = propertyMappingService; this.urlHelper = urlHelper; // this.userManager = userManager; } /// <summary> /// Gets a User using username /// </summary> /// <param name="username">username</param> /// <response code="200">User entry retrieved</response> /// <response code="400">user retrieval parameter has missing/invalid values</response> /// <response code="500">Oops! Can't retrieve the user entry right now</response> [ProducesResponseType(typeof(User), 200)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [EnableCors("AnyGET")] [Authorize] [Authorize(Policy = "Reader")] [HttpGet("{username}", Name = "GetUser")] public async Task<IActionResult> GetUser(string username) { if (string.IsNullOrEmpty(username)) { return BadRequest(); } var result = await userRepository.GetEntity(username); if (result == null) { return NotFound(); } return Ok(result); } /// <summary> /// Gets Users and applies the search, sort, filter and pagedResult parameters. /// </summary> /// <param name="parameter">Parameter containing the details of the search, sort , filter and pagedResult</param> /// <response code="200">User entries retrieved</response> /// <response code="400">users retrieval parameter has missing/invalid values</response> /// <response code="500">Oops! Can't retrieve users entry right now</response> [ProducesResponseType(typeof(User), 200)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "Reader")] [EnableCors("AnyGET")] [HttpGet(Name = "GetUsers")] public IActionResult GetUsers([FromQuery] UserResourceParameter parameter) { if (!typeHelperService.TypeHasProperties<UserForDisplayDTO>(parameter.Fields)) return BadRequest(); if (!propertyMappingService.ValidMappingExistsFor<UserForDisplayDTO, User>(parameter.OrderBy)) return BadRequest(); var userList = userRepository.GetEntities(parameter); var mappedUserList = AutoMapper.Mapper.Map<IEnumerable<UserForDisplayDTO>>(userList); if (!parameter.Fields.Contains("username")) { parameter.Fields = parameter.Fields+", username"; } var usersForDisplay = mappedUserList.ShapeData<UserForDisplayDTO>(parameter.Fields); var result = usersForDisplay.Select(user => { var userAsDictionary = user as IDictionary<string, object>; var userLinks = CreateLinksForUser((string)userAsDictionary["Username"]); userAsDictionary.Add("links", userLinks); return userAsDictionary; }); var linksForUsersCollection = CreateLinksForUsers(parameter, userList.HasNext, userList.HasPrevious); var resultWithLinks = new { value = result, links = linksForUsersCollection}; return Ok(resultWithLinks); } /// <summary> /// Deletes a user using username /// </summary> /// <param name="username">username to be deleted</param> /// <response code="204">User entry deleted</response> /// <response code="400">user retrieval parameter has missing/invalid values</response> /// <response code="500">Oops! Can't delet user entry right now</response> [ProducesResponseType(204)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "SuperUser")] [EnableCors("default")] [HttpDelete("{username}", Name = "DeleteUser")] public IActionResult DeleteUser(string username) { if (string.IsNullOrEmpty(username)) { return BadRequest(); } if (!userRepository.DeleteEntity(username)) { return new StatusCodeResult(500); } return NoContent(); } /// <summary> /// Creates a User /// </summary> /// <param name="userForCreationDto">user details to be created</param> /// <response code="204">User entry created</response> /// <response code="400">user creation parameter has missing/invalid values</response> /// <response code="500">Oops! Can't create user entry right now</response> [ProducesResponseType(typeof(User),201)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "Writer")] [EnableCors("default")] [HttpPost( Name = "CreateUser")] public async Task<IActionResult> PostUser( [FromBody] UserForCreationDTO userForCreationDto) { if (userForCreationDto == null) { return BadRequest(); } if (!ModelState.IsValid) return new UnAcceptableEntity(ModelState); var user = AutoMapper.Mapper.Map<User>(userForCreationDto); user.RegistrationDate = DateTime.Now; var result = await userRepository.PostEntity(user); if (result == null) return new StatusCodeResult(500); var mappedResult = AutoMapper.Mapper.Map<UserForDisplayDTO>(result); return CreatedAtRoute("GetUser", new { username = userForCreationDto.Username }, mappedResult); } /// <summary> /// Updates a user /// </summary> /// <param name="username">username of the user to be updated</param> /// <param name="userForUpdateDto">the body of the user to be updated. This is a full update. So all the parameters to be updated shoudl be mentioned in addition to other parameters. If a parameter is null or missing, it will be updated to null</param> /// <response code="201">User entry updated</response> /// <response code="400">user creation parameter has missing/invalid values</response> /// <response code="500">Oops! Can't create user entry right now</response> [ProducesResponseType(typeof(User), 201)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "SuperUser")] [EnableCors("default")] [HttpPut("{username}", Name = "UpdateUser")] public async Task<IActionResult> UpdateUser(string username, [FromBody] UserForUpdateDTO userForUpdateDto) { if (userForUpdateDto == null) { return BadRequest(); } if (!ModelState.IsValid) { return new UnAcceptableEntity(ModelState); } var entity =await userRepository.GetEntity(username); if (entity == null) { return NotFound(); } var result = await userRepository.UpdateEntity(entity); if (result == null) { return new StatusCodeResult(500); } var mappedResult = AutoMapper.Mapper.Map<UserForDisplayDTO>(result); return CreatedAtRoute("GetUser", new { username = entity.Username }, mappedResult); } /// <summary> /// Partially updates a user /// </summary> /// <param name="user">username of the user to be updated</param> /// <param name="patchDocument">the patch documents containing the list of updates to be applied to a user</param> /// <response code="201">User entry updated</response> /// <response code="400">user creation parameter has missing/invalid values</response> /// <response code="500">Oops! Can't create user entry right now</response> [ProducesResponseType(typeof(User), 201)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "SuperUser")] [EnableCors("default")] [HttpPatch("{user}", Name = "PartiallyUpdateUser")] public async Task<IActionResult> PatchUser(string user, [FromBody] JsonPatchDocument<UserForUpdateDTO> patchDocument) { if (patchDocument == null) return BadRequest(); var entity = await userRepository.GetEntity(user); if (entity == null) return NotFound(); var userToPatch = AutoMapper.Mapper.Map<UserForUpdateDTO>(entity); patchDocument.ApplyTo(userToPatch); // add validation AutoMapper.Mapper.Map(userToPatch, entity); entity.Username = user; var updatedUser = userRepository.UpdateEntity(entity); if (updatedUser == null) throw new Exception($"patching user with username = {user} failed"); return CreatedAtRoute("GetUser", new { username = user }, updatedUser); } } }
using System.Web.Http; using Insurance.Model.Poco; using Insurance.Models.Principal; namespace Insurance.Controllers { public class BaseApiController : ApiController { public readonly IAuthentication Auth; public BaseApiController(IAuthentication auth) { Auth = auth; } public Contact Contact => ((UserIndentity)Auth.CurrentUser.Identity).User; } }
using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Internal; using Newtonsoft.Json; namespace TransactionApi.DataAccess.Data { public class Seeder { public static void SeedData(TransactionContext databaseContext) { if (databaseContext.Transactions.Any()) { return; } var userData = System.IO.File.ReadAllText("Data/transaction-seed.json"); var transactions = JsonConvert.DeserializeObject<List<Transaction>>(userData); databaseContext.AddRange(transactions); databaseContext.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Console2.From_026_To_050 { /* Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. */ public class _038_MultiplyStrings { /// <summary> /// Beside do a real multiplication is any other smart way to do it? /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <returns></returns> public string Multiply(string s1, string s2) { char[] c1 = s1.ToCharArray(); char[] c2 = s2.ToCharArray(); int[] n1 = new int[c1.Length]; int[] n2 = new int[c2.Length]; for (int i = 0; i < n1.Length; i++) { n1[i] = int.Parse(c1[i].ToString()); } for (int i = 0; i < n2.Length; i++) { n2[i] = int.Parse(c2[i].ToString()); } int[] res = new int[n1.Length + n2.Length + 5]; for (int i = 0; i < n1.Length; i++) { for (int j = 0; j < n2.Length; j++) { int pro = n1[i] * n2[j]; int OneDigit = pro % 10; int TenthDigit = (pro / 10) % 10; int res1 = OneDigit + res[i + j]; res[i + j] = res1 % 10; int carry = 0; if (res1 >= 10) carry = 1; int res2 = TenthDigit + res[i + j + 1] + carry; res[i + j + 1] = res2 % 10; carry = 0; if (res2 >= 10) carry = 1; res[i + j + 2] += carry; } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < res.Length; i++) { sb.Append(res[i].ToString()); } // need to trim down the end '0' return sb.ToString().TrimEnd(new char[] { '0' }); } } }
// // 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.Web.InternalServices { public class NotificationDTO { public int NotificationId { get; set; } } }
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace PIdentityJwt.Migrations { public partial class AddedModels : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "FunctionItems"); migrationBuilder.CreateTable( name: "MenuMasterDto", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Menu = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_MenuMasterDto", x => x.Id); }); migrationBuilder.CreateTable( name: "MenuMasters", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Menu = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_MenuMasters", x => x.Id); }); migrationBuilder.CreateTable( name: "Submenus", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Controller = table.Column<string>(nullable: true), Action = table.Column<string>(nullable: true), MenuMasterId = table.Column<int>(nullable: false), RoleId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Submenus", x => x.Id); table.ForeignKey( name: "FK_Submenus_MenuMasters_MenuMasterId", column: x => x.MenuMasterId, principalTable: "MenuMasters", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Submenus_Roles_RoleId", column: x => x.RoleId, principalTable: "Roles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Submenus_MenuMasterId", table: "Submenus", column: "MenuMasterId"); migrationBuilder.CreateIndex( name: "IX_Submenus_RoleId", table: "Submenus", column: "RoleId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "MenuMasterDto"); migrationBuilder.DropTable( name: "Submenus"); migrationBuilder.DropTable( name: "MenuMasters"); migrationBuilder.CreateTable( name: "FunctionItems", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Controller = table.Column<string>(nullable: true), Menu = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), UsersInRolesId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_FunctionItems", x => x.Id); table.ForeignKey( name: "FK_FunctionItems_UsersInRoles_UsersInRolesId", column: x => x.UsersInRolesId, principalTable: "UsersInRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_FunctionItems_UsersInRolesId", table: "FunctionItems", column: "UsersInRolesId"); } } }
namespace OverTheHillsAndFarAway { public enum Activities { WakeUp, Dinner, WatchTV, ByeBye } public interface ISubject { void Attach(IObserver obs); void Detach(IObserver obs); void Notify(); } }
using Innouvous.Utils; using Innouvous.Utils.MVVM; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Input; namespace ToDo.Client.ViewModels { class ParentSelectWindowViewModel : ViewModel { private ObservableCollection<TaskItemViewModel> tasks = new ObservableCollection<TaskItemViewModel>(); private CollectionViewSource viewsource; private Window window; private int? currentTaskId; //Prevent circular reference public ParentSelectWindowViewModel(int listId, int? currentTaskId, Window window) { this.window = window; this.currentTaskId = currentTaskId; Cancelled = true; viewsource = new CollectionViewSource(); viewsource.Source = tasks; SortDescriptions.SetSortDescription(viewsource.SortDescriptions, SortDescriptions.TaskItemsOrder); Workspace.API.LoadList(listId, tasks, currentTaskId); } public bool Cancelled { get; private set; } public TaskItemViewModel SelectedItem { get; set; } public ICollectionView Tasks { get { return viewsource.View; } } public ICommand CancelCommand { get { return new CommandHelper(() => { Cancelled = true; window.Close(); }); } } public ICommand ClearCommand { get { return new CommandHelper(() => { SelectedItem = null; Cancelled = false; window.Close(); }); } } public ICommand OKCommand { get { return new CommandHelper(Select); } } private void Select() { try { if (SelectedItem == null) throw new Exception("No parent selected."); else if (currentTaskId != null && SelectedItem.Data.TaskItemID == currentTaskId.Value) throw new Exception("Parent task cannot be itself."); this.Cancelled = false; window.Close(); } catch (Exception e) { MessageBoxFactory.ShowError(e); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Xamarin.Essentials; using ExpenseTracker.ViewModels; namespace ExpenseTracker { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddItem : ContentPage { AddItemViewModel viewModel; string catPick = ""; string incPick = ""; public AddItem() { InitializeComponent(); BindingContext = viewModel = new AddItemViewModel(); viewModel.User_ID = int.Parse(Preferences.Get("ExpenseT_UserID", "40")); PopulateCategoryPicker(); } public AddItem(ExpenseEntry expenseEntry, IncomeEntry incomeEntry) { InitializeComponent(); BindingContext = viewModel = new AddItemViewModel(); viewModel.User_ID = int.Parse(Preferences.Get("ExpenseT_UserID", "40")); if (expenseEntry != null) { viewModel.ID = expenseEntry.ID; viewModel.AccountType = "Expense"; viewModel.AccountName = expenseEntry.AccountName; viewModel.TransAmount = expenseEntry.ExpenseAmount.ToString("0.00"); viewModel.TransName = expenseEntry.ExpenseName; viewModel.IncomeAccount = expenseEntry.IncomeAccountName; viewModel.InAccVisible = true; catPick = expenseEntry.ExpenseCategory; incPick = expenseEntry.IncomeAccountName; } else if (incomeEntry != null) { viewModel.ID = incomeEntry.ID; viewModel.AccountType = "Income"; viewModel.AccountName = incomeEntry.AccountName; viewModel.Category = incomeEntry.IncomeCategory; viewModel.TransAmount = incomeEntry.IncomeAmount.ToString("0.00"); viewModel.TransName = incomeEntry.IncomeName; catPick = incomeEntry.IncomeCategory; } saveButton.Text = "Update"; PopulateCategoryPicker(); PopulateIncomeAccountPicker(); } public AddItem(string accountType, string accountName) { InitializeComponent(); BindingContext = viewModel = new AddItemViewModel(); viewModel.User_ID = int.Parse(Preferences.Get("ExpenseT_UserID", "40")); if (accountType == "Expense") viewModel.InAccVisible = true; else viewModel.InAccVisible = false; viewModel.AccountType = accountType; viewModel.AccountName = accountName; PopulateCategoryPicker(); PopulateIncomeAccountPicker(); } private void PopulateCategoryPicker() { if (Connectivity.NetworkAccess == NetworkAccess.Internet) { viewModel.IsBusy = true; viewModel.DataQuery.expenseSelect = "Select * From " + viewModel.AccountType + "Category "; viewModel.DataQuery.expenseWhere = " where user_Id = 40 or user_id = " + viewModel.User_ID; ObservableCollection<Exp_Inc_Category> picker = viewModel.DataQuery.ExecuteAQuery<Exp_Inc_Category>(); ObservableCollection<string> pickerList = new ObservableCollection<string>(); foreach (Exp_Inc_Category cat in picker) { pickerList.Add(cat.CategoryName); } viewModel.CategoryList = pickerList; viewModel.Category = catPick; viewModel.IsBusy = false; } else { DependencyService.Get<IToast>().Show("No Internet Connection."); } } private void PopulateIncomeAccountPicker() { if (Connectivity.NetworkAccess == NetworkAccess.Internet) { viewModel.IsBusy = true; viewModel.DataQuery.expenseSelect = "Select * From Account "; viewModel.DataQuery.expenseWhere = " where (user_id = " + viewModel.User_ID + " or user_id = 40) and AccountType_ID = 1"; ObservableCollection<Account> picker = viewModel.DataQuery.ExecuteAQuery<Account>(); ObservableCollection<string> pickerList = new ObservableCollection<string>(); foreach (Account acc in picker) { pickerList.Add(acc.AccountName); } viewModel.IncomeAccountList = pickerList; viewModel.IncomeAccount = incPick; viewModel.IsBusy = false; } else { DependencyService.Get<IToast>().Show("No Internet Connection."); } } async void OnSaveButtonClicked(object sender, EventArgs e) { try { viewModel.IsBusy = true; if (Connectivity.NetworkAccess == NetworkAccess.Internet) { if ((viewModel.IncomeAccount == "" && viewModel.AccountType == "Expense") || viewModel.Category == "" || viewModel.TransAmount == "") { await DisplayAlert("Missing Entry", "You must have an entry in each field.", "Ok"); return; } if (saveButton.Text == "Save") { if (viewModel.TransName.Contains("'")) { viewModel.TransName = viewModel.TransName.Replace("'", "''"); } if (viewModel.AccountName.Contains("'")) { viewModel.AccountName = viewModel.AccountName.Replace("'", "''"); } if (viewModel.AccountType == "Income") { viewModel.DataQuery.expenseSelect = "INSERT INTO " + viewModel.AccountType + " ([User_ID],[Account_ID],[IncomeAmount]," + "[IncomeDate],[IncomeCategory_ID],[Repeat],[RepeatPeriod_ID],[IncomeName]) VALUES (" + viewModel.User_ID + ", " + "(select id from Account where AccountName = '" + viewModel.AccountName + "' and User_ID = " + viewModel.User_ID + "), " + viewModel.TransAmount + ", '" + DateTime.Now + "', " + "(select ID from IncomeCategory where CategoryName = '" + viewModel.Category + "')," + " 0, 4, '" + viewModel.TransName + "')"; viewModel.DataQuery.expenseWhere = ""; int result = viewModel.DataQuery.AlterDataQuery(); viewModel.DataQuery.expenseSelect = "Select * From Totals "; viewModel.DataQuery.expenseWhere = "Where Account_id = (Select top (1) ID from Account where AccountName = '" + viewModel.AccountName + "' and User_ID = '" + viewModel.User_ID + "')"; ObservableCollection<Totals> totals = viewModel.DataQuery.ExecuteAQuery<Totals>(); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Totals] SET [Total] = " + (totals[0].Total + float.Parse(viewModel.TransAmount)).ToString("0.00"); viewModel.DataQuery.expenseWhere = " Where ID = " + totals[0].ID; int count = viewModel.DataQuery.AlterDataQuery(); } else if (viewModel.AccountType == "Expense") { viewModel.DataQuery.expenseSelect = "INSERT INTO " + viewModel.AccountType + " ([User_ID],[IncomeAccount_ID],[Account_ID],[ExpenseAmount]," + "[ExpenseDate],[ExpenseCategory_ID],[Repeat],[RepeatPeriod_ID],[ExpenseName]) VALUES (" + viewModel.User_ID + ", (select id from Account where AccountName = '" + viewModel.IncomeAccount + "' and user_id = " + viewModel.User_ID + "), (select id from Account where AccountName = '" + viewModel.AccountName + "' and User_ID = " + viewModel.User_ID + "), " + viewModel.TransAmount + ", '" + DateTime.Now + "', " + "(select ID from ExpenseCategory where (user_id = " + viewModel.User_ID + " or user_id = 40) and CategoryName = '" + viewModel.Category + "'), 0, 4, '" + viewModel.TransName + "')"; viewModel.DataQuery.expenseWhere = ""; int result = viewModel.DataQuery.AlterDataQuery(); viewModel.DataQuery.expenseSelect = "Select * From Totals "; viewModel.DataQuery.expenseWhere = "Where Account_id = (Select top (1) ID from Account where AccountName = '" + viewModel.AccountName + "' and User_ID = '" + viewModel.User_ID + "')"; ObservableCollection<Totals> totals = viewModel.DataQuery.ExecuteAQuery<Totals>(); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Totals] SET [Total] = " + (totals[0].Total + float.Parse(viewModel.TransAmount)).ToString("0.00"); viewModel.DataQuery.expenseWhere = " Where ID = " + totals[0].ID; int count = viewModel.DataQuery.AlterDataQuery(); viewModel.DataQuery.expenseSelect = "Select * From Totals "; viewModel.DataQuery.expenseWhere = "Where Account_id = (Select top (1) ID from Account where AccountName = '" + viewModel.IncomeAccount + "' and User_ID = '" + viewModel.User_ID + "')"; totals = viewModel.DataQuery.ExecuteAQuery<Totals>(); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Totals] SET [Total] = " + (totals[0].Total - float.Parse(viewModel.TransAmount)).ToString("0.00"); viewModel.DataQuery.expenseWhere = " Where ID = " + totals[0].ID; count = viewModel.DataQuery.AlterDataQuery(); } viewModel.IsBusy = false; } else if (saveButton.Text == "Update") { if (viewModel.TransName.Contains("'")) { viewModel.TransName = viewModel.TransName.Replace("'", "''"); } if (viewModel.AccountName.Contains("'")) { viewModel.AccountName = viewModel.AccountName.Replace("'", "''"); } if (viewModel.AccountType == "Expense") { viewModel.DataQuery.expenseSelect = "Select inc.[ID], inc.[User_ID], acc1.AccountName, inc.[IncomeAmount], inc.[IncomeDate]" + " ,ec.CategoryName as IncomeCategory, inc.[Repeat], RepeatPeriod=null, inc.[IncomeName] FROM[dbo].[Income] inc inner join Account acc1 on inc.Account_ID = acc1.ID" + " inner join IncomeCategory ec on inc.IncomeCategory_ID = ec.ID"; viewModel.DataQuery.expenseWhere = "Where account_id = (Select top (1) ID from Account where AccountName = '" + viewModel.IncomeAccount + "' and User_ID = '" + viewModel.User_ID + "')"; ObservableCollection<IncomeEntry> incomeEntry = viewModel.DataQuery.ExecuteAQuery<IncomeEntry>(); viewModel.DataQuery.expenseSelect = "SELECT ex.[ID], ex.[User_ID], acc1.AccountName, ex.[ExpenseAmount], acc2.AccountName as IncomeAccountName, ex.[ExpenseDate]" + " ,ec.CategoryName as ExpenseCategory, ex.[Repeat], RepeatPeriod=null, ex.expenseName FROM [dbo].[Expense] ex inner join Account acc1 on ex.Account_ID = acc1.ID" + " inner join Account acc2 on ex.IncomeAccount_ID = acc2.ID inner join ExpenseCategory ec on ex.ExpenseCategory_ID = ec.ID"; viewModel.DataQuery.expenseWhere = "Where ex.id = " + viewModel.ID; ObservableCollection<ExpenseEntry> entry = viewModel.DataQuery.ExecuteAQuery<ExpenseEntry>(); viewModel.DataQuery.expenseSelect = "Select * From Totals "; viewModel.DataQuery.expenseWhere = "Where Account_id = (Select top (1) ID from Account where AccountName = '" + incomeEntry[0].AccountName + "' and User_ID = '" + incomeEntry[0].User_ID + "')"; ObservableCollection<Totals> incTotals = viewModel.DataQuery.ExecuteAQuery<Totals>(); incTotals[0].Total -= (float)entry[0].ExpenseAmount; incTotals[0].Total += float.Parse(viewModel.TransAmount); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Totals] SET [Total] = " + incTotals[0].Total.ToString("0.00"); viewModel.DataQuery.expenseWhere = " Where ID = " + incTotals[0].ID; int count = viewModel.DataQuery.AlterDataQuery(); viewModel.DataQuery.expenseSelect = "Select * From Totals "; viewModel.DataQuery.expenseWhere = "Where Account_id = (Select top (1) ID from Account where AccountName = '" + entry[0].AccountName + "' and User_ID = '" + entry[0].User_ID + "')"; ObservableCollection<Totals> totals = viewModel.DataQuery.ExecuteAQuery<Totals>(); totals[0].Total -= (float)entry[0].ExpenseAmount; totals[0].Total += float.Parse(viewModel.TransAmount); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Totals] SET [Total] = " + totals[0].Total.ToString("0.00"); viewModel.DataQuery.expenseWhere = " Where ID = " + totals[0].ID; count = viewModel.DataQuery.AlterDataQuery(); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Expense] SET [IncomeAccount_ID] = (select ID from Account where user_id = " + viewModel.User_ID + " and AccountName = '" + viewModel.IncomeAccount + "'), [ExpenseAmount] = '" + viewModel.TransAmount + "', [ExpenseCategory_ID] = " + "(select ID from ExpenseCategory where (user_id = " + viewModel.User_ID + " or user_id = 40) and CategoryName = '" + viewModel.Category + "'), [ExpenseName] = '" + viewModel.TransName + "'"; viewModel.DataQuery.expenseWhere = " Where ID = " + viewModel.ID; count = viewModel.DataQuery.AlterDataQuery(); } else if (viewModel.AccountType == "Income") { viewModel.DataQuery.expenseSelect = "Select ex.[ID], ex.[User_ID], acc1.AccountName, ex.[IncomeAmount], ex.[IncomeDate]" + " ,ec.CategoryName as IncomeCategory, ex.[Repeat], RepeatPeriod=null, ex.[IncomeName] FROM[dbo].[Income] ex inner join Account acc1 on ex.Account_ID = acc1.ID" + " inner join IncomeCategory ec on ex.IncomeCategory_ID = ec.ID"; viewModel.DataQuery.expenseWhere = "Where ex.account_id = (Select top (1) ID from Account where AccountName = '" + viewModel.AccountName + "' and User_ID = '" + viewModel.User_ID + "')"; ObservableCollection<IncomeEntry> incomeEntry = viewModel.DataQuery.ExecuteAQuery<IncomeEntry>(); viewModel.DataQuery.expenseSelect = "Select * From Totals "; viewModel.DataQuery.expenseWhere = "Where Account_id = (Select top (1) ID from Account where AccountName = '" + incomeEntry[0].AccountName + "' and User_ID = '" + incomeEntry[0].User_ID + "')"; ObservableCollection<Totals> incTotals = viewModel.DataQuery.ExecuteAQuery<Totals>(); incTotals[0].Total -= (float)incomeEntry[0].IncomeAmount; incTotals[0].Total += float.Parse(viewModel.TransAmount); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Totals] SET [Total] = " + incTotals[0].Total.ToString("0.00"); viewModel.DataQuery.expenseWhere = " Where ID = " + incTotals[0].ID; int count = viewModel.DataQuery.AlterDataQuery(); viewModel.DataQuery.expenseSelect = "UPDATE [dbo].[Income] SET [IncomeAmount] = " + viewModel.TransAmount + ", [IncomeCategory_ID] = " + "(select ID from IncomeCategory where (user_id = " + viewModel.User_ID + " or user_id = 40) and CategoryName = '" + viewModel.Category + "'), [IncomeName] = '" + viewModel.TransName + "'"; viewModel.DataQuery.expenseWhere = " Where ID = " + viewModel.ID; count = viewModel.DataQuery.AlterDataQuery(); } int result = viewModel.DataQuery.AlterDataQuery(); if (result == 1) DependencyService.Get<IToast>().Show(viewModel.AccountName + " was successfully updated."); } } else { DependencyService.Get<IToast>().Show("No Internet Connection."); } } catch (Exception ex) { await DisplayAlert("Adding account failed", ex.Message, "OK"); viewModel.IsBusy = false; } await Navigation.PopAsync(); } async void OnCancelButtonClicked(object sender, EventArgs e) { await Navigation.PopAsync(); } private void PopulateOnEdit() { try { /*viewModel.IsBusy = true; viewModel.DataQuery.expenseSelect = "Select * From account "; viewModel.DataQuery.expenseWhere = "where id = " + accountID; viewModel.UsersInfo = viewModel.DataQuery.ExecuteAQuery<Account>(); viewModel.AccountDesc = viewModel.UsersInfo[0].Description; viewModel.AccountName = viewModel.UsersInfo[0].AccountName; int index = 0; foreach (AccountType accType in picker) { if (viewModel.UsersInfo[0].AccountType_ID == picker[index].ID) viewModel.AccountTypePicker = picker[index].TypeName; index++; } viewModel.IsBusy = false;*/ } catch (Exception ex) { DisplayAlert("Adding account failed", ex.Message, "OK"); viewModel.IsBusy = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using UnityEngine; public class Walking : MonoBehaviour { Animator animator; public float targetX, targetZ; public float speed; Vector3 currentPos; void Start() { animator = GetComponentInChildren<Animator>(); } void Update() { currentPos = transform.position; double distance = Math.Sqrt(Math.Pow((targetX - currentPos.x), 2) + Math.Pow((targetZ - currentPos.z), 2)); double slopeZ = (targetZ - currentPos.z) / distance; double slopeX = (targetX - currentPos.x) / distance; double angle = Math.Asin(slopeZ); angle = angle * 180 / Math.PI; //Vector3 to = new Vector3(0, (float)angle, 0); //transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime); if (distance > 0.01) { animator.SetBool("WalkingTrigger", true); transform.position += new Vector3((float)(Time.deltaTime * speed * slopeX), transform.position.y , (float)(Time.deltaTime* speed * slopeZ)); } else animator.SetBool("WalkingTrigger", false); } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; namespace Microsoft.PowerShell.EditorServices.Services.PowerShellContext { /// <summary> /// Provides details about a change in state of a PowerShellContext. /// </summary> public class SessionStateChangedEventArgs { /// <summary> /// Gets the new state for the session. /// </summary> public PowerShellContextState NewSessionState { get; private set; } /// <summary> /// Gets the execution result of the operation that caused /// the state change. /// </summary> public PowerShellExecutionResult ExecutionResult { get; private set; } /// <summary> /// Gets the exception that caused a failure state or null otherwise. /// </summary> public Exception ErrorException { get; private set; } /// <summary> /// Creates a new instance of the SessionStateChangedEventArgs class. /// </summary> /// <param name="newSessionState">The new session state.</param> /// <param name="executionResult">The result of the operation that caused the state change.</param> /// <param name="errorException">An exception that describes the failure, if any.</param> public SessionStateChangedEventArgs( PowerShellContextState newSessionState, PowerShellExecutionResult executionResult, Exception errorException) { this.NewSessionState = newSessionState; this.ExecutionResult = executionResult; this.ErrorException = errorException; } } }
using FatCat.Nes.OpCodes.AddressingModes; namespace FatCat.Nes.OpCodes.Branching { public class BranchIfOverFlowSet : BranchOpCode { public override string Name => "BVS"; protected override CpuFlag Flag => CpuFlag.Overflow; protected override bool FlagState => true; public BranchIfOverFlowSet(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { } } }
using System; using System.Collections.Generic; using System.Text; namespace BlumAPI.MyB.Versions { public enum VersionMyBusinessPos { V2011, V2012, V2017, V2019, V2020 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public abstract class productos : ScriptableObject { /* * productos: * clase padre de todos los productos que se crearan * * parametros: * nombre (string): nombre del producto * descripcion (string): descripcion del producto * precio (string): precio del producto */ public string titulo; public string descripcion; public Sprite icono; public int precio; }
using UnityEngine; using System.Collections; namespace Com.PDev.PCG.Server { public class Logger { public static void Log(string source, string text) { Debug.Log(source + ": " + text); } } }
using System.Collections.Generic; using System.Web.Mvc; namespace Web.Areas.Admin.ViewModels { public class CreateCourseScoViewModel { public string Title { get; set; } public int CourseId { get; set; } public int ScoId { get; set; } public string CatalogueNumber { get; set; } public int RequiredScoId { get; set; } public List<SelectListItem> RequiredSelectList { get; set; } public string ScoTitle { get; set; } public string Directory { get; set; } public string CourseTitle { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using System; public class ChangeHorizontalAngle : MonoBehaviour, IPointerClickHandler, CannonStateObserver { public CannonStateHandler stateHandler; [SerializeField] private float deltaValue; private float highestValue = 45.0f; private float lowestValue = -45.0f; private void changeHorizontalAngle(float increment_value) { CannonState state = stateHandler.getCannonState(); float newHorizontalAngle = state.horizontalAngle + increment_value; if (newHorizontalAngle >= this.lowestValue && newHorizontalAngle <= this.highestValue) { state.horizontalAngle = newHorizontalAngle; } else if (newHorizontalAngle < this.lowestValue) { state.horizontalAngle = this.lowestValue; } else if (newHorizontalAngle > this.highestValue) { state.horizontalAngle = this.highestValue; } state.horizontalAngle = (float)Math.Round(state.horizontalAngle, 1); stateHandler.setCannonState(state); } private void OnMouseDown() { // Michael: added !hasLanded condition (and getCannonState) CannonState state = stateHandler.getCannonState(); if(!state.hasLanded){ this.changeHorizontalAngle(this.deltaValue); } } public void OnPointerClick(PointerEventData pointerEventData) { // Michael: added !hasLanded condition (and getCannonState) CannonState state = stateHandler.getCannonState(); if(!state.hasLanded){ this.changeHorizontalAngle(this.deltaValue); } } public void applyChange(CannonState state){ gameObject.SetActive(!state.horizontalAngleIsLocked); } void Start() { stateHandler.subscribe(this); this.applyChange(this.stateHandler.getCannonState()); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Tracing; namespace Microsoft.DataStudio.Diagnostics { [EventSource(Name = "Microsoft-Atlas-ClientUXUsage", Guid = "93F442FC-C280-409B-B8B7-9D7792E0E7E2")] public class ClientUXUsageEventSource : AtlasBaseEventSource { public ClientUXUsageEventSource() { } public static ClientUXUsageEventSource Log { get { return EventSources.ClientUXUsageEventSource; } } [Event(1, Version = 1)] public void LogUsage(string eventType, string eventName, string eventData, DateTime clientTimeStamp, string moduleName, string loggerName, string category, string clientSessionId, string userPuid, Guid subscriptionId, string userAgent) { base.MyWriteEvent(1, eventType, eventName, eventData, clientTimeStamp, moduleName, loggerName, category, clientSessionId, userPuid, subscriptionId, userAgent); } [NonEvent] public void WriteUsage(string eventType, string eventName, string eventData, string moduleName, string loggerName, string category, DateTime clientTimeStamp, string clientSessionId, string userPuid, Guid subscriptionId, string userAgent) { MdsUtilities.MakeMdsCompatible(ref eventType); MdsUtilities.MakeMdsCompatible(ref eventName); MdsUtilities.MakeMdsCompatible(ref eventData); MdsUtilities.MakeMdsCompatible(ref clientTimeStamp); MdsUtilities.MakeMdsCompatible(ref moduleName); MdsUtilities.MakeMdsCompatible(ref loggerName); MdsUtilities.MakeMdsCompatible(ref category); MdsUtilities.MakeMdsCompatible(ref clientSessionId); MdsUtilities.MakeMdsCompatible(ref userPuid); MdsUtilities.MakeMdsCompatible(ref userAgent); this.LogUsage(eventType, eventName, eventData, clientTimeStamp, moduleName, loggerName, category, clientSessionId, userPuid, subscriptionId, userAgent); } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets.Modules.Managers.ZoneGenerator { public enum TypeOfEvent { Town, Quest, Battle } public class EventPoint : MonoBehaviour { public EventPoint() { } public void Initialize(GameObject obj, int PosX, TypeOfEvent type) { EventToActivate = obj; this.transform.position = new Vector3(PosX, 0, 0); PositionX = PosX; EventPointType = type; } public TypeOfEvent EventPointType; // public bool IsQuestEvent = false; // public bool IsTownEvent = false; //public bool IsBattleEvent = false; public GameObject EventToActivate; public int PositionX; } }