text
stringlengths
13
6.01M
using Microsoft.VisualStudio.TestTools.UnitTesting; using NGeoNames; using NGeoNames.Entities; using System.Linq; namespace NGeoNamesTests { [TestClass] public class ReverseGeoCodeTests { [TestMethod] public void ReverseGeoCode_RadialSearch_ReturnsCorrectResults() { // Read a file with data with points in and around London in a 20Km radius var data = GeoFileReader.ReadExtendedGeoNames(@"testdata\test_GB.txt").ToArray(); var rg = new ReverseGeoCode<ExtendedGeoName>(data); var center = rg.CreateFromLatLong(51.5286416, 0); //Exactly at 0 longitude so we test left/right of prime meridian Assert.AreEqual(47, data.Length); //File should contain 47 records total var expected_ids = new[] { 2640729, 2639577, 2642465, 2637627, 2633709, 2643339, 2634677, 2636503, 2652053, 2654710, 2643743, 2646003, 2643741, 2653941, 6690870, 2655775, 2651621, 2650497, 2656194, 2653266, 2648657, 2637433, 2652618, 2646057 }; // Search from the/a center in London for all points in a 10Km radius var searchresults = rg.RadialSearch(center, 100000.0).ToArray(); // Number of results should match length of expected_id array Assert.AreEqual(expected_ids.Length, searchresults.Length); // Check if each result is in the expected results array foreach (var r in searchresults) Assert.IsTrue(expected_ids.Contains(r.Id)); } [TestMethod] public void ReverseGeoCode_RadialSearch_ReturnsMaxCountResults() { // Read a file with data with points in and around London in a 20Km radius var data = GeoFileReader.ReadExtendedGeoNames(@"testdata\test_GB.txt").ToArray(); var rg = new ReverseGeoCode<ExtendedGeoName>(data); var center = rg.CreateFromLatLong(51.5286416, 0); //Exactly at 0 longitude so we test left/right of prime meridian var maxresults = 10; Assert.AreEqual(47, data.Length); //File should contain 47 records total var expected_ids = new[] { 2643741, 2646003, 2643743, 6690870, 2651621, 2655775, 2636503, 2634677, 2656194, 2653266 }; Assert.AreEqual(maxresults, expected_ids.Length); // Search from the/a center in London for all points in a 10Km radius, allowing only maxresults results var searchresults = rg.RadialSearch(center, 100000.0, maxresults).ToArray(); // Number of results should match length of expected_id array Assert.AreEqual(expected_ids.Length, searchresults.Length); // Check if each result is in the expected results array foreach (var r in searchresults) Assert.IsTrue(expected_ids.Contains(r.Id)); } [TestMethod] public void ReverseGeoCode_NearestNeighbourSearch_ReturnsCorrectResults() { // Read a file with data with points in and around London in a 20Km radius var data = GeoFileReader.ReadExtendedGeoNames(@"testdata\test_GB.txt").ToArray(); var rg = new ReverseGeoCode<ExtendedGeoName>(data); var center = rg.CreateFromLatLong(51.5286416, 0); //Exactly at 0 longitude so we test left/right of prime meridian Assert.AreEqual(47, data.Length); //File should contain 47 records total var expected_ids = new[] { 2640729, 2639577, 2642465, 2637627, 2633709, 2643339, 2634677, 2636503, 2652053, 2654710, 2643743, 2646003, 2643741, 2653941, 6690870, 2655775, 2651621, 2650497, 2656194, 2653266, 2648657, 2637433, 2652618, 2646057 }; // Search from the/a center in London for the first X points (where X == expected_ids.length) var searchresults = rg.NearestNeighbourSearch(center, expected_ids.Length).ToArray(); // Number of results should match length of expected_id array Assert.AreEqual(expected_ids.Length, searchresults.Length); // Check if each result is in the expected results array foreach (var r in searchresults) Assert.IsTrue(expected_ids.Contains(r.Id)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using System.ComponentModel; using yGet.EDFParser; namespace EDFViewer { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { private EdfViewModel edfViewModel = null; public Window1() { InitializeComponent(); edfViewModel = new EdfViewModel(); this.DataContext = edfViewModel; } private void Button_Click(object sender, RoutedEventArgs e) { OpenFileDialog browseReport = new OpenFileDialog(); browseReport.DefaultExt = ".xlsx"; browseReport.Filter = "Reports(.edf)|*.Edf"; Nullable<bool> result = browseReport.ShowDialog(); if (result == true) { edfViewModel.EDFFileName = browseReport.FileName; edfViewModel.InitializeEDFParser(browseReport.FileName); } } private void OnCheckDrawingSheetName(object sender, RoutedEventArgs e) { } private void OnCheckFunctionBlock(object sender, RoutedEventArgs e) { } private void OnCheckDrawingSheetComment(object sender, RoutedEventArgs e) { } } public class EdfViewModel: INotifyPropertyChanged { private String _edfFileName = String.Empty; private bool _IsDrawingSheetNamePresent; EDFParser edfParser; public EdfViewModel() { edfParser = null; } public String EDFFileName { get { return _edfFileName; } set { _edfFileName = value; if (null != _edfFileName) { OnPropertyChanged("EDFFileName"); } } } public void InitializeEDFParser(String fileName) { if (null != edfParser) { edfParser.Dispose(); } edfParser = new EDFParser(fileName); } public bool IsDrawingSheetNamePresent { get { return _IsDrawingSheetNamePresent; } set { _IsDrawingSheetNamePresent = value; OnPropertyChanged("IsDrawingSheetNamePresent"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
using MyForum.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyForum.Services.Contracts { public interface INewsService { Task Create(string name, string content, string imageUrl, string creatorId); IQueryable<News> GetAll(); News GetNewsById(string newsId); Task Edit(string newsId, string name, string content, string imageUrl); Task Delete(string newsId); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ClassWithArray { class Departament { private Worker[] workers;//приватный массив с объектами(рабочими) int index;//поле индекс массива public string Title { get; set; }//поле название департамента public Worker[] Workers//свойство-массив чтобы получать информацию о конкретном рабочем указывая индекс массива. { get { return workers; } // возвращение значения вовне set { workers = value; }// присвоение значения извне } public Worker this[int index]//возвращение значений через индексатор { get { return workers[index]; } // возвращение значения вовне set { workers[index] = value; }// присвоение значения извне } public Departament() { index = -1;//индекс массива workers = new Worker[1];//новый массив с 2мя ячейками } public void Add(Worker Item)//метод добавления рабочих { index++;//индекс массива увеличивается if (index >= workers.Length)//если индекс превышает размеры массива - массив увеличивается в 2 раза { Array.Resize(ref workers, workers.Length * 2); } workers[index] = Item;//в индекс массива записывается рабочий } public string GetInfoDepartament()//метод получения информации о рабочих { string res = string.Empty; for (int i = 0; i <= index; i++)//перебор рабочих в массиве и вывод данных на экран { res += $"{workers[i].Info()} \n";//вывод данных о каждом конкретном рабочем в массиве } return res; } public Worker GetInfoWorker(int index)//метод для выдачи информации по конкретному рабочему { return workers[index]; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Drawing; using System.Data; using System.Linq; using System.Text; namespace LTTQ { public class Grid { private class PointMass { public Vector2 Position; public Vector2 Velocity = Vector2.Zero; public double InverseMass; private Vector2 acceleration = Vector2.Zero; private double damping = 0.98; public PointMass(Vector2 position, double invMass) { Position = position; InverseMass = invMass; } public void ApplyForce(Vector2 force) { acceleration += force * InverseMass; } public void IncreaseDamping(double factor) { damping *= factor; } public void Update() { Velocity += acceleration; Position += Velocity; acceleration = Vector2.Zero; if (Velocity.LengthSquared() < 0.001 * 0.001) Velocity = Vector2.Zero; Velocity *= damping; damping = 0.98; } } private class SpringLine { public PointMass End1; public PointMass End2; public double TargetLength; public double Stiffness; public double Damping; public SpringLine(PointMass end1, PointMass end2, double stiffness, double damping) { End1 = end1; End2 = end2; Stiffness = stiffness; Damping = damping; TargetLength = Vector2.Distance(end1.Position, end2.Position); } public void Update() { var x = End1.Position - End2.Position; double length = x.Length(); if (length <= TargetLength) return; x = (x / length) * (length - TargetLength); var dv = End2.Velocity - End1.Velocity; var force = Stiffness * x - dv * Damping; End1.ApplyForce(-force); End2.ApplyForce(force); } } SpringLine[] springs; PointMass[,] points; Rectangle Size; public Vector2 Spacing; public Grid(Rectangle size, Vector2 spacing) { Size = size; Spacing = spacing; var springList = new List<SpringLine>(); int numColumns = (int)(size.Width / spacing.X) + 1; int numRows = (int)(size.Height / spacing.Y) + 1; points = new PointMass[numColumns, numRows]; PointMass[,] fixedPoints = new PointMass[numColumns, numRows]; int column = 0, row = 0; for (double y = size.Top; y <= size.Bottom; y += spacing.Y) { for (double x = size.Left; x <= size.Right; x += spacing.X) { points[column, row] = new PointMass(new Vector2(x, y), 1); fixedPoints[column, row] = new PointMass(new Vector2(x, y), 0); column++; } row++; column = 0; } for (int y = 0; y < numRows; y++) for (int x = 0; x < numColumns; x++) { if (x == 0 || y == 0 || x == numColumns - 1 || y == numRows - 1) springList.Add(new SpringLine(fixedPoints[x, y], points[x, y], 0.5, 0.1)); if (x > 0) springList.Add(new SpringLine(points[x - 1, y], points[x, y], 0.25, 0.05)); if (y > 0) springList.Add(new SpringLine(points[x, y - 1], points[x, y], 0.25, 0.05)); } springs = springList.ToArray(); } public void Update() { foreach (var spring in springs) spring.Update(); foreach (var mass in points) mass.Update(); } public void ApplyExplosiveForce(double force, Vector2 position, double radius) { foreach (var mass in points) { double dist2 = Vector2.DistanceSquared(position, mass.Position); if (dist2 < radius * radius) { mass.ApplyForce(100 * force * (mass.Position - position) / (10000 + dist2)); mass.IncreaseDamping(0.6f); } } } public Point ToPoint(Vector2 v) { Point result = new Point((int)v.X, (int)v.Y); return result; } public void Draw(PaintEventArgs e) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int width = points.GetLength(0); int height = points.GetLength(1); Pen pen = new Pen(Color.DarkBlue); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Point left = new Point(), up = new Point(); Point p = ToPoint(points[x, y].Position); if (x > 0) { left = ToPoint(points[x - 1, y].Position); var z = points[x, y].Position - points[x - 1, y].Position; double c = ((z.Length() - Spacing.X) / Spacing.X); c *= 500; c += 150; c = Clamp(c, 255, 0); e.Graphics.DrawLine(new Pen(Color.FromArgb(0, 0, 255 - (int)c)), left, p); } if (y > 0) { up = ToPoint(points[x, y - 1].Position); var z = points[x, y].Position - points[x, y - 1].Position; double c = ((z.Length() - Spacing.Y) / Spacing.Y); c *= 500; c += 150; c = Clamp(c, 255, 0); e.Graphics.DrawLine(new Pen(Color.FromArgb(0, 0, 255 - (int)c)), up, p); } } } e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; } public static T Clamp<T>(T value, T max, T min) where T : System.IComparable<T> { T result = value; if (value.CompareTo(max) > 0) result = max; if (value.CompareTo(min) < 0) result = min; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq.Mapping; namespace Kingdee.CAPP.Solidworks.RoutingPlugIn { [Table(Name = "PS_BusinessCategory")] public class BusinessCategory { [Column(IsPrimaryKey=true)] public string CategoryId { get; set; } [Column] public string ParentCategory { get; set; } [Column] public string CategoryCode { get; set; } [Column] public string CategoryName { get; set; } [Column] public string Remark { get; set; } [Column] public string CodeRuleId { get; set; } [Column] public int DisplaySeq { get; set; } [Column] public int DeleteFlag { get; set; } [Column] public string MajorFormat { get; set; } [Column] public string MinorFormat { get; set; } [Column] public string Separate { get; set; } [Column] public int ObjectOption { get; set; } [Column] public string CommonType { get; set; } [Column] public bool IsShared { get; set; } [Column] public bool IsShareAll { get; set; } [Column] public bool IsUseForProduct { get; set; } [Column] public string Creator { get; set; } [Column] public string FolderId { get; set; } [Column] public decimal ArtificialCost { get; set; } [Column] public decimal ProcessCostRadix { get; set; } [Column] public decimal ProcessCost { get; set; } [Column] public decimal AssisCost { get; set; } [Column] public int ArtificialCostType { get; set; } [Column] public string DocFolderId { get; set; } [Column] public bool IsFlowByEA { get; set; } [Column] public bool IsFlowByPStart { get; set; } [Column] public bool IsFlowByPEnd { get; set; } [Column] public int IsShowPic { get; set; } [Column] public bool IsBOMChange { get; set; } [Column] public string ProjectPrefixMode { get; set; } [Column] public int IsShowOldVersion { get; set; } [Column] public bool FreezeCanFinish { get; set; } [Column] public string ECNCFFolderId { get; set; } [Column] public string ECNDocFolderId { get; set; } [Column] public string ProcessId { get; set; } [Column] public string ECNBandProcessId { get; set; } [Column] public int ChildCount { get; set; } [Column] public bool IsAddTaskName { get; set; } [Column] public string K3CategoryCode { get; set; } [Column] public string ImportByK3 { get; set; } [Column] public int LinkageExtend { get; set; } [Column] public string ProjectChangeMan { get; set; } [Column] public string K3MaterialCode { get; set; } [Column] public int ShowExtend { get; set; } [Column] public string K3BOMGroup { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Account { /// <summary> /// 流水类型 /// </summary> public enum TransactionType1 { 钱, 积分 } }
using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using YFVIC.DMS.Model.Models.Settings; using YFVIC.DMS.Model.Models.HR; using YFVIC.DMS.Model.Models.FileInfo; namespace YFVIC.DMS.Model.Models.Common { public class DMSComm { /// <summary> /// 登录名转化 /// </summary> /// <param name="logon"></param> /// <returns></returns> public static string resolveLogon(string logon) { if (!string.IsNullOrEmpty(logon)) { if (logon.Contains(@".w|")) { return logon.Split('\\')[1].ToUpper(); } else if (logon.Contains(@"i:0#.f|dmsmembership|")) { return logon.Split('|')[2].ToUpper(); } else { return logon; } } else { return logon; } } /// <summary> /// 把cdsid转换为sharepoint用户的LoginName /// </summary> /// <param name="cdsid"></param> /// <returns></returns> public static string resolveCDSID(string cdsid) { if (!string.IsNullOrEmpty(cdsid)) { return "i:0#.f|dmsmembership|" + cdsid; // return "i:0#.w|visteon\\" + cdsid; //return "i:0#.w|ryan\\" + cdsid; } else { return cdsid; } } /// <summary> /// 获取文件夹名称 /// </summary> /// <param name="id"></param> /// <returns></returns> public static string GetFolderPath(string id) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SharepointDB"); using (SharepointDBDataContext db = new SharepointDBDataContext(setting.DefaultValue)) { AllDoc item = db.AllDocs.Where(p => p.Id == new Guid(id)).FirstOrDefault(); if (item != null) { return item.LeafName; } else { return ""; } } } /// <summary> /// 获取文件地址 /// </summary> /// <param name="id"></param> /// <returns></returns> public static string GetFilePath(string id) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SharepointDB"); SettingsEntity weburl = mgr.GetSystemSetting(SPContext.Current.Site.Url, "WebUrl"); using (SharepointDBDataContext db = new SharepointDBDataContext(setting.DefaultValue)) { AllDoc item = db.AllDocs.Where(p => p.Id == new Guid(id)).FirstOrDefault(); if (item != null) { return weburl.DefaultValue + "/" + item.DirName + "/" + item.LeafName; } else { return ""; } } } /// <summary> /// 获取本地文件地址 /// </summary> /// <param name="fileid"></param> /// <returns></returns> public static string GetLocalPath(string fileid) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity sourcepath = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SourcePath"); SettingsEntity weburl = mgr.GetSystemSetting(SPContext.Current.Site.Url, "WebUrl"); string path = fileid.Replace(sourcepath.DefaultValue, "").Replace("\\", "//"); return weburl.DefaultValue + path; } /// <summary> ///发布文件并获取版本号 /// </summary> /// <param name="weburl"></param> /// <param name="filepath"></param> /// <returns></returns> public static string PublishFile(string weburl, string filepath,string fileare) { string result = ""; if (fileare == "Sharepoint") { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(weburl)) { SPWeb web = site.OpenWeb(); web.AllowUnsafeUpdates = true; SPFile fileinfo = web.GetFile(new Guid(filepath)); fileinfo.Publish("后台发布"); web.AllowUnsafeUpdates = false; result = fileinfo.Versions.Count.ToString(); } }); } return result; } /// <summary> /// 是否超级管理员 /// </summary> /// <param name="sid"></param> /// <returns></returns> public static bool IsAdmin(string sid) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "Admin"); if (sid.ToLower() == setting.DefaultValue.ToLower()||sid=="SYSTEM") { return true; } else { return false; } } /// <summary> /// 是否SOA文件管理员 /// </summary> /// <param name="sid"></param> /// <returns></returns> public static bool IsSOAFileAdmin(string sid) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SOAFileAdmin"); string [] admins = setting.DefaultValue.ToLower().Split(','); int count = admins.Count(x => x.Equals(sid.ToLower())); if (count>0 || sid == "SYSTEM") { return true; } else { return false; } } /// <summary> /// 是否角色人员 /// </summary> /// <param name="company"></param> /// <param name="sid"></param> /// <returns></returns> public static bool IsCompanyAdmin(string org,string role, string sid) { OrgRoleMgr orgrolemgr = new OrgRoleMgr(); OrgRoleEntity orgrole = orgrolemgr.GetOrgrole(role,org); if (!string.IsNullOrEmpty(orgrole.UserAD)) { bool r = false; string[] users = orgrole.UserAD.Split(','); foreach (string user in users) { if (user.ToLower() == sid.ToLower()) { r = true; } } return r; } else { return false; } } /// <summary> ///获取文件大小 /// </summary> /// <param name="fileid"></param> /// <returns></returns> public static FileInfoEntity GetFileinfo(string fileid) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SharepointDB"); SettingsEntity weburl = mgr.GetSystemSetting(SPContext.Current.Site.Url, "WebUrl"); using (SharepointDBDataContext db = new SharepointDBDataContext(setting.DefaultValue)) { AllDoc item = db.AllDocs.Where(p => p.Id ==new Guid(fileid)).FirstOrDefault(); FileInfoEntity file = new FileInfoEntity(); file.FileSize = item.Size.ToString(); file.FileUrl =weburl.DefaultValue+ item.DirName + "/" + item.LeafName; file.UpDataTime = item.TimeLastModified.ToString(); return file; } } /// <summary> /// 获取本地文件大小 /// </summary> /// <param name="fileid"></param> /// <returns></returns> public static FileInfoEntity GetLocalFileInfo(string fileid) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity sourcepath = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SourcePath"); SettingsEntity weburl = mgr.GetSystemSetting(SPContext.Current.Site.Url, "WebUrl"); System.IO.FileInfo fileinfo = new System.IO.FileInfo(fileid); string path = fileid.Replace(sourcepath.DefaultValue, "").Replace("\\", "//"); FileInfoEntity file = new FileInfoEntity(); file.FileSize = fileinfo.Length.ToString(); file.FileUrl = weburl.DefaultValue + path; return file; } /// <summary> /// 设置文件名称 /// </summary> /// <param name="fileid"></param> /// <param name="filename"></param> /// <returns></returns> public static bool SetFileName(string fileid,string filename,string filearea) { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SharepointDB"); using (SharepointDBDataContext db = new SharepointDBDataContext(setting.DefaultValue)) { if (filearea == "Sharepoint") { AllDoc item = db.AllDocs.Where(p => p.Id == new Guid(fileid)).FirstOrDefault(); if (item != null) { item.LeafName = filename; db.SubmitChanges(); } } return true; } } const int GB = 1024 * 1024 * 1024;//定义GB的计算常量 const int MB = 1024 * 1024;//定义MB的计算常量 const int KB = 1024;//定义KB的计算常量 /// <summary> /// 字节转换为KB /// </summary> /// <param name="KSize"></param> /// <returns></returns> public static string ByteConversionGBMBKB(Int64 KSize) { if (KSize / GB >= 1)//如果当前Byte的值大于等于1GB return (Math.Round(KSize / (float)GB, 2)).ToString() + "GB";//将其转换成GB else if (KSize / MB >= 1)//如果当前Byte的值大于等于1MB return (Math.Round(KSize / (float)MB, 2)).ToString() + "MB";//将其转换成MB else if (KSize / KB >= 1)//如果当前Byte的值大于等于1KB return (Math.Round(KSize / (float)KB, 2)).ToString() + "KB";//将其转换成KGB else return KSize.ToString() + "Byte";//显示Byte值 } /// <summary> /// 添加组 /// </summary> /// <param name="weburl"></param> /// <param name="groupname"></param> /// <returns></returns> public static bool AddGroup(string weburl, string groupname,string cdsid) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(weburl)) { SPWeb web = site.OpenWeb(); SPGroup group = null; web.Site.AllowUnsafeUpdates = true; web.AllowUnsafeUpdates = true; SPUser user = web.EnsureUser(DMSComm.resolveCDSID(cdsid)); web.SiteGroups.Add(groupname, user, user, "项目成员组"); group = web.SiteGroups[groupname]; group.AddUser(user); SPRoleDefinition role = web.RoleDefinitions.GetByType(SPRoleType.Editor); SPRoleAssignment spRoleAssign = new SPRoleAssignment(group); spRoleAssign.RoleDefinitionBindings.Add(role); web.RoleAssignments.Add(spRoleAssign); web.AllowUnsafeUpdates = false; web.Site.AllowUnsafeUpdates = false; } }); return true; } /// <summary> /// 更新组 /// </summary> /// <param name="weburl"></param> /// <param name="groupname"></param> /// <returns></returns> public static bool UpdataGroup(string weburl, string groupname,string oldgroupname) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(weburl)) { SPWeb web = site.OpenWeb(); web.Site.AllowUnsafeUpdates = true; web.AllowUnsafeUpdates = true; SPGroup group = web.SiteGroups[oldgroupname]; group.Name = groupname; group.Update(); web.Update(); web.AllowUnsafeUpdates = false; web.Site.AllowUnsafeUpdates = false; } }); return true; } /// <summary> /// 删除组 /// </summary> /// <param name="weburl"></param> /// <param name="groupname"></param> /// <returns></returns> public static bool RemoveGroup(string weburl, string groupname) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(weburl)) { SPWeb web = site.OpenWeb(); web.Site.AllowUnsafeUpdates = true; web.AllowUnsafeUpdates = true; SPGroup group = web.SiteGroups[groupname]; web.SiteGroups.RemoveByID(group.ID); web.AllowUnsafeUpdates = false; web.Site.AllowUnsafeUpdates = false; } }); return true; } /// <summary> /// 添加组成员 /// </summary> /// <param name="weburl"></param> /// <param name="groupname"></param> /// <param name="cdsid"></param> /// <returns></returns> public static bool AddUserToGroup(string weburl, string groupname, string cdsid) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(weburl)) { SPWeb web = site.OpenWeb(); web.Site.AllowUnsafeUpdates = true; web.AllowUnsafeUpdates = true; SPGroup group; try { group = web.SiteGroups[groupname]; } catch { AddGroup(weburl, groupname, cdsid); group = web.SiteGroups[groupname]; } SPUser user = web.EnsureUser(resolveCDSID(cdsid)); group.AddUser(user); group.Update(); web.Update(); web.AllowUnsafeUpdates = false; web.Site.AllowUnsafeUpdates = false; } }); return true; } /// <summary> /// 删除组成员 /// </summary> /// <param name="weburl"></param> /// <param name="groupname"></param> /// <param name="cdsid"></param> /// <returns></returns> public static bool RemoveUserToGroup(string weburl, string groupname, string cdsid) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(weburl)) { SPWeb web = site.OpenWeb(); SPGroup group = web.SiteGroups[groupname]; web.AllowUnsafeUpdates = true; SPUser user = web.EnsureUser(resolveCDSID(cdsid)); group.RemoveUser(user); group.Update(); web.Update(); web.AllowUnsafeUpdates = false; } }); return true; } /// <summary> /// 获取管理员CDSID /// </summary> /// <returns></returns> public static string GetAdmin() { SettingsMgr mgr = new SettingsMgr(); SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "Admin"); return setting.DefaultValue; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GodControlls : MonoBehaviour { public bool Lift { get; private set; } public bool Lower { get; private set; } // Use this for initialization private void Start() { } private void FixedUpdate() { Lift = Input.GetMouseButton(0); Lower = Input.GetMouseButton(1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities; using DataAccessLayer; namespace BLL { public class RequestBusiness : IBusiness<Request> { UnitOfWork _uof; Employee emp; public RequestBusiness(Employee employee) { emp = employee; _uof = new UnitOfWork(); } public bool Add(Request item) { if (item!=null) { if (item.ProjectId<0) { throw new Exception("Talep oluştururken bir proje seçilmelidir"); } if (item.Type==null) { throw new Exception("Talep tipi mutlaka seçilmelidir"); } if (item.Description==null) { throw new Exception("Talep açıklama kısmı doldurulmalıdır"); } if (true) { _uof.RequestRepository.Add(item); return _uof.ApplyChanges(); } } return false; } public Request Get(int id) { if (id>0) { return _uof.RequestRepository.Get(id); } else { throw new Exception("Id değeri 0'dan büyük olmalıdır"); } } public ICollection<Request> GetAll() { if (_uof.RequestRepository.GetAll().Count!=0) { return _uof.RequestRepository.GetAll(); } throw new Exception("Listede kayıt bulunamadı"); } public bool Remove(Request item) { if (item!=null) { _uof.RequestRepository.Remove(item); return _uof.ApplyChanges(); } return false; } public bool Update(Request item) { if (item != null) { if (item.ProjectId < 0) { throw new Exception("Talep güncellenirken bir proje seçilmelidir"); } if (item.Type == null) { throw new Exception("Talep tipi mutlaka seçilmelidir"); } if (item.Description == null) { throw new Exception("Talep açıklama kısmı doldurulmalıdır"); } if (true) { _uof.RequestRepository.Update(item); return _uof.ApplyChanges(); } } return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using OrbisEngine.ItemSystem; public class TestComponent : ItemComponent { public TestComponent(IItem source) : base(source) {} public override void InitialiseComponent() { messageHandlers.Add("test", (message) => { TestMessage testMessage = message as TestMessage; if (testMessage == null) return; if (testMessage.Message == "TEST") { m_baseItem.SendMessage("test", new TestMessage("derp")); } }); } }
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 ProyectoBolera { public partial class ClientesForm : Form { public ClientesForm() { InitializeComponent(); } private void llenarDataGrid() { string query = String.Format($"SELECT idcliente AS Identificacion, nombre AS Nombre, apellido AS Apellido, correo, telefono FROM clientes"); DataSet ds = Conexion.getQuery(query); if (ds != null) { dtgClientes.DataSource = ds.Tables[0]; } } private void TxtCedula_KeyPress(object sender, KeyPressEventArgs e) { Validacion.soloNumeros(sender, e); } private void TxtNombre_KeyPress(object sender, KeyPressEventArgs e) { Validacion.soloTexto(sender, e); } private void TxtApellido_KeyPress(object sender, KeyPressEventArgs e) { Validacion.soloTexto(sender, e); } private void TxtTelefono_KeyPress(object sender, KeyPressEventArgs e) { Validacion.soloNumeros(sender, e); } private void registrarCliente() { string queryCount = String.Format($"SELECT COUNT(*) FROM clientes WHERE idcliente = '{txtCedula.Text}'"); if (!Validacion.validarSiExisteRegistro(queryCount)) { string query = String.Format($"INSERT INTO clientes VALUES ('{txtCedula.Text}','{txtNombre.Text}','{txtApellido.Text}','{dateNacimiento.Value.ToString()}','{txtEmail.Text}',{txtTelefono.Text})"); Conexion.getQuery(query); MessageBox.Show("Registro Existoso"); limpiarFormulario(); llenarDataGrid(); } else { MessageBox.Show("La cedula ya se encuentra registrada en la base de datos"); } } private void actualizarRegistro() { string query = String.Format($"UPDATE clientes SET nombre = '{txtNombre.Text}', apellido = '{txtApellido.Text}', fecha_nacimiento ='{dateNacimiento.Value.ToString()}', correo = '{txtEmail.Text}', telefono = '{txtTelefono.Text}' WHERE idempleado = '{txtCedula.Text}' WHERE idcliente = '{txtCedula.Text}'"); Conexion.getQuery(query); limpiarFormulario(); llenarDataGrid(); MessageBox.Show("Se ha actualizado el registro con exito"); } private void limpiarFormulario() { txtCedula.Text = ""; txtNombre.Text = ""; txtApellido.Text = ""; dateNacimiento.Text = ""; txtEmail.Text = ""; txtTelefono.Text = ""; } private void BtnRegistrar_Click(object sender, EventArgs e) { if (txtCedula.Text != "" && txtNombre.Text != "" && txtApellido.Text != "" && dateNacimiento.Text != "" && txtEmail.Text != "" && txtTelefono.Text != "") { if (Validacion.emailValid(txtEmail.Text)) { if (btnBuscar.Text == "Registrar") { registrarCliente(); } else { actualizarRegistro(); } } else { MessageBox.Show("Correo no valido"); } } else { MessageBox.Show("Aun hay compos sin completar"); } } private void RadioButton1_CheckedChanged(object sender, EventArgs e) { btnBuscar.Text = "Registrar"; txtCedula.Enabled = true; } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { btnBuscar.Text = "Actualizar"; txtCedula.Enabled = false; limpiarFormulario(); } private void ClientesForm_Load(object sender, EventArgs e) { llenarDataGrid(); llenarCombFiltrar(); } private void llenarCombFiltrar() { var items = new List<Options> { new Options() { Name="Identificacion", Value="clientes.idcliente"}, new Options() { Name="Nombre", Value="clientes.nombre"}, new Options() { Name="Apellido", Value="clientes.apellido"}, }; combFiltrar.DataSource = items; combFiltrar.DisplayMember = "Name"; combFiltrar.ValueMember = "Value"; } public class Options { public string Name { get; set; } public string Value { get; set; } } private void BtnBuscar_Click_1(object sender, EventArgs e) { string query = String.Format($"SELECT idcliente AS Identificacion, nombre AS Nombre, apellido AS Apellido, correo, telefono FROM clientes WHERE {combFiltrar.SelectedValue} LIKE '%{txtBuscar.Text}%'"); DataSet ds = Conexion.getQuery(query); if (ds != null) { dtgClientes.DataSource = ds.Tables[0]; } } private void DtgClientes_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { txtCedula.Text = dtgClientes.CurrentRow.Cells[0].Value.ToString(); txtNombre.Text = dtgClientes.CurrentRow.Cells[1].Value.ToString(); ; txtApellido.Text = dtgClientes.CurrentRow.Cells[2].Value.ToString(); ; txtEmail.Text = dtgClientes.CurrentRow.Cells[3].Value.ToString(); txtTelefono.Text = dtgClientes.CurrentRow.Cells[4].Value.ToString(); ; } private void TxtBuscar_TextChanged(object sender, EventArgs e) { } private void Label7_Click(object sender, EventArgs e) { } private void CombFiltrar_SelectedIndexChanged(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using VEE.Models.BasedeDatos; namespace VEE.Models { public class ResultadoViewModel { public IEnumerable<Resultadomodel> Resultados { get; set; } } }
using System.Collections; using System.Collections.Generic; using HTB.Database; namespace HTBExtras.XML { public class XmlChangedAktsResponseRecord : Record { public ArrayList AktIntIdList { get; set; } public XmlChangedAktsResponseRecord() { AktIntIdList = new ArrayList(); } public void SetAktIntIds(List<StringValueRec> list) { AktIntIdList.Clear(); AktIntIdList.AddRange(list); } } }
using Abp.Authorization.Roles; namespace Abp.Zero.EntityFramework.Repositories { public class AbpRoleRepository : AbpZeroEfRepositoryBase<AbpRole>, IAbpRoleRepository { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DoorMovement : MonoBehaviour { private void OnTriggerStay(Collider other) { if (other.tag == "Door1") { Animator anim = other.GetComponentInChildren<Animator>(); if (Input.GetKeyDown(KeyCode.E)) anim.SetTrigger("OpenClose"); } } }
using Newtonsoft.Json; using SampleApp.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Text; namespace SampleApp.Services { public class RecipeService : IRecipeServices { public ObservableCollection<RecipesModel> GetRecipesData() { //It will be useful api url and json file is available :) //string jsonFileName = "recipes.json"; //var assembly = typeof(MainPage).GetTypeInfo().Assembly; //Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}"); //using (var reader = new System.IO.StreamReader(stream)) //{ // var jsonString = reader.ReadToEnd(); // Converting JSON Array Objects into generic list // var recipes = JsonConvert.DeserializeObject<ObservableCollection<RecipesDTO>>(jsonString); // var recipeslist = new ObservableCollection<RecipesModel>(); // foreach (var item in recipes) // { // recipeslist.Add(new RecipesModel(item)); // } // return recipeslist; //} //Hard coded services var serviceResponse = new ObservableCollection<RecipesModel>() { new RecipesModel{ItemImage="ic_itemone",ItemName="Pancit palabok",Article="lesson1",Day="Monday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemthree",ItemName="Tab ng talangka",Article="lesson1",Day="Tuesday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemfour",ItemName="Pancit palabok",Article="lesson1",Day="Monday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemfive",ItemName="Tab ng talangka",Article="lesson1",Day="Tuesday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemtwo",ItemName="Pancit palabok",Article="lesson1",Day="Monday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemthree",ItemName="Tab ng talangka",Article="lesson1",Day="Tuesday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemone",ItemName="Pancit palabok",Article="lesson1",Day="Monday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemthree",ItemName="Tab ng talangka",Article="lesson1",Day="Tuesday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemfour",ItemName="Pancit palabok",Article="lesson1",Day="Monday",Title="How to make a @@@@@"}, new RecipesModel{ItemImage="ic_itemfive",ItemName="Tab ng talangka",Article="lesson1",Day="Tuesday",Title="How to make a @@@@@"}, }; return serviceResponse; } } }
using System; using SQLite; namespace ProctorCreekGreenwayApp { public class User { /** * Format of a table in the SQLite local database * Each method represents a column in the table */ /* Creates a unique ID for each user */ [PrimaryKey, AutoIncrement, NotNull] public int ID { get; set; } /* Whether or not user has notifications on or off */ public bool Notifications { get; set; } /* True/false for notifications about music */ public bool MusicNotifs { get; set; } /* True/false for notifications about history */ public bool HistoryNotifs { get; set; } /* True/false for notifications about food */ public bool FoodNotifs { get; set; } /* True/false for notifications about art */ public bool ArtNotifs { get; set; } /* True/false for notifications about nature */ public bool NatureNotifs { get; set; } /* True/false for notifications about architecture */ public bool ArchitectureNotifs { get; set; } } }
using Microsoft.EntityFrameworkCore; namespace Inventory.Infrastructure { public class InventoryContext : DbContext { public DbSet<Domain._Inventory.Entites.Inventory> Inventory { get; set; } public InventoryContext(DbContextOptions<InventoryContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new InventoryMapping()); base.OnModelCreating(modelBuilder); } } }
using UnityEngine; using System.Collections; public enum MapEventType { PlanetAdded, MapCleared, PlanetOwnerChanged, PlanetUpgrade }; public interface I_MapObserver { void OnMapEvent(MapEventType mapEventType, PlanetEntity planet); }
using System; using System.Collections.Generic; namespace Askii { public class Parser { public Template Parse(Dictionary<string, string> tokens){ return new Template{ Title = tokens["Title"], Icon = new IconParser().Parse(tokens["Icon"]), Message = tokens["Message"], Buttons = new ButtonParser().Parse(tokens["Buttons"]) }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using LINQ101MVC.Models; namespace LINQ101MVC.ViewModels { public class ProductSubCategoryViewModel : IDisposable { private readonly ApplicationDbContext _db = ApplicationDbContext.Create(); public ProductSubcategory ProductSubcategory { get;} public IEnumerable<ProductCategory> ProductCategories { get;} public ProductSubCategoryViewModel(ProductSubcategory subCategory) { ProductSubcategory = subCategory; ProductCategories = _db.ProductCategories; } public void Dispose() { _db?.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Inicia um novo cliente para calcular os dois valores calculocliente subtracao = new calculocliente(new subtracao()); calculocliente adicao = new calculocliente(new adicao()); Console.WriteLine("subtracao: " + subtracao.cauculo(10,1) + " adicao: " + adicao.cauculo(10,1)); Console.Read(); } } // Interface para estrategia public interface Strategy { //Define o metodo int calculo( int valor1, int valor2); } //Primeira estrategia class subtracao : Strategy { public int calculo(int valor1, int valor2) { //Define a lógica return valor1 - valor2; } } //Segunda estrategia class adicao : Strategy { public int calculo(int valor1, int valor2) { //Define a lógica return valor1 + valor2; } } //Cliente(Executa a estrategia) class calculocliente { private Strategy strategy; //Construtor atibui a estrategia para fazer a interface public calculocliente(Strategy calculate) { strategy = calculate; } //Executa a estrategia public int cauculo(int valor1, int valor2) { return strategy.calculo(valor1,valor2); } } }
using System.Data; namespace SimplySqlSchema { public interface IConnectionFactory { BackendType Backend { get; } IDbConnection GetConnection(string connectionString); } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace E_Exceptions { //custom exception type public class CreditCardWithdrawException : Exception { } class Program { static void Main(string[] args) { try { DirFileDemo(); } catch(Exception ex) { } } static void DirFileDemo() { //File.Copy("test.txt", @"Q:\tmp\test_copy.txt", overwrite:true); File.Copy("test.txt", "test_copy.txt", overwrite: true); File.Move("test_copy.txt", "test_copy_renamed.txt"); File.Delete("test_copy.txt"); if (File.Exists("test.txt")) { File.AppendAllText("test.txt", "bla"); } File.Replace("test_2.txt", "test_3.txt", "test_backup.txt"); bool existsDir = Directory.Exists(@"C:\tmp"); if (existsDir) { var files = Directory.EnumerateFiles(@"C:\tmp", "*.txt", SearchOption.AllDirectories); foreach(var file in files) { Console.WriteLine(file); } } //Directory.Delete() //string fullPath = Path.Combine(@"C:\tmp", "\\bla", "file.txt"); } static void FileDemo() { IEnumerable<string> lines = File.ReadLines("test.txt"); File.WriteAllText("test_2.txt", "My name is John"); File.WriteAllLines("test_3.txt", new string[] { "My name", "is John" }); File.WriteAllBytes("test_4.txt", new byte[] { 72, 101, 108, 108, 111 }); string alltext = File.ReadAllText("test_2.txt"); Console.WriteLine(alltext); string[] allLines = File.ReadAllLines("test_3.txt"); Console.WriteLine(allLines[0]); Console.WriteLine(allLines[1]); byte[] bytes = File.ReadAllBytes("test_4.txt"); Console.WriteLine(Encoding.ASCII.GetString(bytes)); Console.ReadLine(); Stream fs = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); try { string str = "Hello, World"; byte[] strInBytes = Encoding.ASCII.GetBytes(str); fs.Write(strInBytes, 0, strInBytes.Length); } catch (Exception ex) { Console.WriteLine($"Error: {ex.ToString()}"); } finally { fs.Close(); } Console.WriteLine("Now reading:"); using (Stream readingStream = new FileStream("test.txt", FileMode.Open, FileAccess.Read)) { byte[] temp = new byte[readingStream.Length]; int bytesToRead = (int)readingStream.Length; int bytesRead = 0; while (bytesToRead > 0) { int n = readingStream.Read(temp, bytesRead, bytesToRead); if (n == 0) break; bytesRead += n; bytesToRead -= n; } string str = Encoding.ASCII.GetString(temp, 0, temp.Length); Console.WriteLine(str); Console.ReadLine(); } } static void ExceptionsDemo() { FileStream file = null; try { file = File.Open("temp.txt", FileMode.Open); } catch (IOException ex) { Console.WriteLine(ex); } finally { if (file != null) file.Dispose(); } Console.ReadLine(); Console.WriteLine("Please input a number"); string result = Console.ReadLine(); int number = 0; try { number = int.Parse(result); } catch (OverflowException ex) { } catch (FormatException ex) { Console.WriteLine("A format exception has occured."); Console.WriteLine("Information is below:"); Console.WriteLine(ex.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine(number); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DialogueTrigger : MonoBehaviour{ public Dialogue dialogue; public bool clickE = false; public void TriggerDialogue() { FindObjectOfType<DialogueManager>().StartDialogue(dialogue); } private void OnTriggerEnter2D(Collider2D col) { if (!clickE && col.tag == "dialogue") { TriggerDialogue(); FindObjectOfType<PlayerMovement>().ableToMove = false; clickE = true; } } private void OnTriggerStay2D(Collider2D collision) { if (clickE && Input.GetKeyDown(KeyCode.E) && collision.tag == "dialogue") { TriggerDialogue(); FindObjectOfType<PlayerMovement>().ableToMove = false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Labo_2.Models { public class Contact { [Required(ErrorMessage="Gelieve een naam in te vullen.")] [DisplayName("Name")] public string Name { get; set; } [Required(ErrorMessage="Gelieve een title op te geven.")] [DisplayName("Title")] public string Title { get; set; } [Required(ErrorMessage="Gelieve een vraag op te geven.")] [DisplayName("Question")] public string Question { get; set; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace COMPOSE { class Program { static void Main(string[] args) { int n = lire(); int[] tab = former(n); afficher(tab,n) ; Console.WriteLine("\n"); Console.WriteLine("----------------"); Console.WriteLine("Le plus petit nombre est " + minmum(tab)); Console.WriteLine("Le plus grand nombre est " + maximum(tab)); former2(n); Console.ReadKey(); } private static void afficher(int[] tab,int n) { Console.Write($"Les nombres Formés par les chiffres de {n} sont :"); for (int i = 0; i < tab.Length; i++) { Console.Write($"{tab[i]} ,"); } } public static void Commencer(int[] list) { travaille(list, 0, list.Length - 1); } private static void echange(ref int a, ref int b) { if (a == b) return; a ^= b; b ^= a; a ^= b; } private static void travaille(int[] list, int current, int max) { int i; if (current == max) { foreach (var item in list) { Console.Write(Convert.ToString(item)); } Console.WriteLine(" "); } else for (i = current; i <= max; i++) { echange(ref list[current], ref list[i]); travaille(list, current + 1, max); // on descend echange(ref list[current], ref list[i]); } } private static void former2(int n) { int nb = factorille(n.ToString().Length); int[] tab = new int[nb]; int c = n / 100; int d = (n % 100) / 10; int u = n % 10; int[] list = new int[] { c, d, u }; Commencer(list); //int i = 0; //while (i < nb) //{ // tab[i] = n; // n = n * 10; // n = n + n % 10; // n = n / 10; // i++; // } // return tab; } private static int[] former(int n) { int nb = factorille(n.ToString().Length); int[] tab = new int[nb]; int c = n / 100; int d = (n % 100) / 10; int u = n % 10; tab[0] = n; tab[1] = (c * 100) + (u * 10) + d; tab[2] = (u * 100) + (d * 10) + c; tab[3] = (u * 100) + (c * 10) + d; tab[4] = (d * 100) + c * 10 + u; tab[5] = (d * 100) + (u * 10) + c; return tab; } private static int minmum(int[] tab) { int min = tab[0]; for (int i = 0; i < tab.Length; i++) { if (tab[i] < min) { min = tab[i]; } } return min; } private static int maximum(int[] tab) { int max = tab[0]; for (int i = 0; i < tab.Length; i++) { if (tab[i] > max) { max = tab[i]; } } return max; } public static int factorille(int n) { if (n == 0) { return 1; } else { return n * factorille(n - 1); } } private static int lire() { int n =0 ; do { try { Console.WriteLine("Donnez un entier non nul composé de trois chiffres"); n = int.Parse(Console.ReadLine()); } catch { Console.WriteLine("S'il vous plait donnez la bonne format d'un entier "); } } while (n < 100 || n > 999); return n; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp3 { /// <summary> /// Interaction logic for ExpenseReportPage.xaml /// </summary> public partial class ExpenseReportPage : Page { public ExpenseReportPage() { InitializeComponent(); } // Custom constructor to pass expense report data public ExpenseReportPage(object data) : this() { // Bind to expense report data. this.DataContext = data; //FOR TESTING PURPOSES /*Console.WriteLine("TRYING TO READ FILE"); Item item1 = new Item("item1", "companyname1", 1, new DateTime(2008,6,1)); Item item2 = new Item("item2", "companyname2", 2, new DateTime(2020, 12, 2)); SaveXml.Append("test.xml", item1); SaveXml.Append("test.xml", item2); Console.WriteLine("WRITTEN TO FILE"); List<Item> items = SaveXml.getAllItems("test.xml"); Console.WriteLine("No. of Items is " + items.Count); for(int i = 0; i < items.Count; i++) { Console.WriteLine(items[i]); } */ } } }
using FluentValidation; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit; namespace SFA.DAS.ProviderCommitments.Web.Validators { public class ReviewApprenticeshipUpdatesViewModelValidator : AbstractValidator<ReviewApprenticeshipUpdatesViewModel> { public ReviewApprenticeshipUpdatesViewModelValidator() { RuleFor(r => r.ApproveChanges).NotNull() .WithMessage("Confirm if you want to approve these changes") .When(z => z.IsValidCourseCode); RuleFor(r => r.ApproveAddStandardToTraining).NotNull() .WithMessage("You need to tell us if you want to add or reject the standard") .When(z => !z.IsValidCourseCode); } } }
namespace Mashup.Logic.Providers.Search { public class SearchResult { public SearchInnerResult d { get; set; } } }
namespace PH01PermutationWithoutRepetitions { using System; using System.Collections.Generic; using System.Linq; public class EntryPoint { public static void Main() { var input = Console.ReadLine().Split(); int n = input.Length; int[] p = new int[input.Length]; int i = 1; var result = new HashSet<string> { string.Join(" ", input) }; while (i < n) { if (p[i] < i) { int j = i % 2 == 0 ? 0 : p[i]; Swap(input, i, j); result.Add(string.Join(" ", input)); p[i]++; i = 1; } else { p[i] = 0; i++; } } Console.WriteLine(string.Join(Environment.NewLine, result.OrderBy(r => r))); } private static void Swap(string[] array, int firstIndex, int nextIndex) { var temp = array[firstIndex]; array[firstIndex] = array[nextIndex]; array[nextIndex] = temp; } } }
using Tomelt.Recipes.Models; namespace Tomelt.Recipes.Services { /// <summary> /// Provides information about the result of recipe execution. /// </summary> public interface IRecipeResultAccessor : IDependency { RecipeResult GetResult(string executionId); } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.ComponentModel; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Windows.Data; using System.Diagnostics; namespace SuspendAndResume { public enum ComputerState { Unknown, Offline, Online } public class Computer : INotifyPropertyChanged { private DateTime lastSeen; private string name; private ComputerState state; private IPAddress ipAddress; private bool discovered; public Dictionary<MacAddress, List<IPAddress>> NetworkInterfaces { get; set; } public string ID { get; set; } public string ServiceUrl { get; set; } public IPAddress IPAddress { get { return ipAddress; } set { if (value != ipAddress) { ipAddress = value; NotifyPropertyChanged("IPAddress"); } } } public DateTime LastSeen { get { return lastSeen; } set { discovered = true; if (value != lastSeen) { lastSeen = value; NotifyPropertyChanged("LastSeen"); } } } public string Name { get { return name; } set { if (value != name) { name = value; NotifyPropertyChanged("Name"); } } } public ComputerState State { get { return state; } set { if (value != state) { state = value; NotifyPropertyChanged("State"); } } } public event PropertyChangedEventHandler PropertyChanged; public Computer() { NetworkInterfaces = new Dictionary<MacAddress, List<IPAddress>>(); } public void StartDiscovery() { discovered = false; } public void StopDiscovery() { if (discovered) { State = ComputerState.Online; } else { State = ComputerState.Offline; } } private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } public void RefreshFrom(Computer computer) { Debug.Assert(computer.ID == this.ID); this.LastSeen = computer.LastSeen; this.ServiceUrl = computer.ServiceUrl; this.NetworkInterfaces = computer.NetworkInterfaces; this.IPAddress = computer.IPAddress; } } }
using System; namespace Dance_Hall { class Program { static void Main(string[] args) { double length = double.Parse(Console.ReadLine()); double width = double.Parse(Console.ReadLine()); double sideOfWardrobe = double.Parse(Console.ReadLine()); double areaOfHall = length * width; double areaOfBench = areaOfHall / 10; double areaOfWardrobe = sideOfWardrobe * sideOfWardrobe; double areaFreeInM2 = areaOfHall - (areaOfBench + areaOfWardrobe); double numberOfDancers = areaFreeInM2 / 0.704; Console.WriteLine(Math.Floor(numberOfDancers)); } } }
using BO; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebSport.Models { public class CreateEditOrganizerVM { public Organizer Organisateur { get; set; } public IEnumerable<Race> ListeCourses { get; set; } public List<int> MultiSelectListRaces { get; set; } } }
using Umbraco.Core.Composing; using Umbraco.Core.Models; namespace Vendr.Checkout.Pipeline.Implement.Tasks { internal class CreateVendrCheckoutNodesTask : IPipelineTask<InstallPipelineContext, InstallPipelineContext> { public InstallPipelineContext Process(InstallPipelineContext ctx) { using (var scope = Current.ScopeProvider.CreateScope()) { var vendrCheckoutPageContenType = Current.Services.ContentTypeService.Get(VendrCheckoutConstants.ContentTypes.Aliases.CheckoutPage); var vendrCheckoutStepPageContenType = Current.Services.ContentTypeService.Get(VendrCheckoutConstants.ContentTypes.Aliases.CheckoutStepPage); // Check to see if the checkout node already exists var filter = scope.SqlContext.Query<IContent>().Where(x => x.ContentTypeId == vendrCheckoutPageContenType.Id); var childNodes = Current.Services.ContentService.GetPagedChildren(ctx.SiteRootNodeId, 1, 1, out long totalRecords, filter); if (totalRecords == 0) { // Create the checkout page var checkoutNode = Current.Services.ContentService.CreateAndSave("Checkout", ctx.SiteRootNodeId, VendrCheckoutConstants.ContentTypes.Aliases.CheckoutPage); // Create the checkout steps pages CreateCheckoutStepPage(checkoutNode, "Customer Information", "Information", "Information"); CreateCheckoutStepPage(checkoutNode, "Shipping Method", "Shipping Method", "ShippingMethod"); CreateCheckoutStepPage(checkoutNode, "Payment Method", "Payment Method", "PaymentMethod"); CreateCheckoutStepPage(checkoutNode, "Review Order", "Review", "Review"); CreateCheckoutStepPage(checkoutNode, "Process Payment", "Payment", "Payment"); CreateCheckoutStepPage(checkoutNode, "Order Confirmation", "Confirmation", "Confirmation"); } scope.Complete(); } // Continue the pipeline return ctx; } private void CreateCheckoutStepPage(IContent parent, string name, string shortName, string stepType) { var checkoutStepNode = Current.Services.ContentService.Create(name, parent.Id, VendrCheckoutConstants.ContentTypes.Aliases.CheckoutStepPage); checkoutStepNode.SetValue("vendrShortStepName", shortName); checkoutStepNode.SetValue("vendrStepType", $"[\"{stepType}\"]"); Current.Services.ContentService.Save(checkoutStepNode); } } }
using System; namespace gView.Framework.system { static public class Numbers { public static IFormatProvider Nhi = global::System.Globalization.CultureInfo.InvariantCulture.NumberFormat; } }
using System; using System.Globalization; using TaxaJurosWebAPI.Models; namespace CalculaJurosWebAPI.Models { public class CalculaJuros { public string Resultado { get; set; } public string CalculaResultado(string valorinicial, string meses) { double r = 0.0; double val = 0.0; uint mes; bool msgError = false; double zero = 0.0; Taxa t = new Taxa(); //Verifica se o valor digitado é um número válido if ((!IsNumeric(valorinicial) && msgError == false) || !IsNumeric(meses)) { Resultado = "Valor e(ou) mês informado(s) inválido(s)"; msgError = true; } else { val = Double.Parse(valorinicial, CultureInfo.CurrentCulture); mes = uint.Parse(meses, CultureInfo.CurrentCulture); r = val * Math.Pow(1 + t.GetTaxa(), mes); Resultado = r.ToString("F2", CultureInfo.CurrentCulture); } //Verifica se o resultado excede o limite de caracteres esperados if ((Resultado.Length > 16 || r == (1 /zero)) && msgError == false) { Resultado = "Resultado excedeu o limte de caracteres de precisão"; msgError = true; } //Verifica se o valor inicial é maior que zero if (val <= 0 && msgError == false) { Resultado = "O valor informado deve ser superior a zero"; msgError = true; } return Resultado; } public static bool IsNumeric(string val) { double retNum; char[] valArray; bool isNum = Double.TryParse(Convert.ToString(val), System.Globalization.NumberStyles.Currency, System.Globalization.NumberFormatInfo.CurrentInfo, out retNum); valArray = val.ToCharArray(0, val.Length); foreach (char c in valArray) { if (!char.IsNumber(c)) { if (c == '.') isNum = false; } } return isNum; } } }
using AutoMapper; using Cognology.FlightBookingApp.Dto; using Cognology.FlightBookingApp.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web.Http; namespace Cognology.FlightBookingApp.Controllers.Api { public class BookingsController : ApiController { private readonly ApplicationDbContext _context; public BookingsController() { _context = new ApplicationDbContext(); } protected override void Dispose(bool disposing) { _context.Dispose(); } [Route("api/booking/search")] [HttpPost] public IHttpActionResult SearchBooking(BookingSearchDto bookingSearchDto) { if (!ModelState.IsValid || bookingSearchDto == null) { return BadRequest("Invalid Request"); } var bookingsQuery = _context.Bookings.Include(b => b.FlightInformation); if (bookingSearchDto.FlightNumber != null) { bookingsQuery = bookingsQuery .Where(b => b.FlightInformation.FlightNumber == bookingSearchDto.FlightNumber); } if (bookingSearchDto.PassengerName != null) { bookingsQuery = bookingsQuery .Where(b => b.PassengerName.ToLower().Contains(bookingSearchDto.PassengerName.ToLower())); } if (bookingSearchDto.Date != null) { bookingsQuery = bookingsQuery .Where(b => b.Date == bookingSearchDto.Date); } if (bookingSearchDto.ArrivalCity != null) { bookingsQuery = bookingsQuery .Where(b => b.FlightInformation.ArrivalCity.ToLower() == bookingSearchDto.ArrivalCity.ToLower()); } if (bookingSearchDto.DepartureCity != null) { bookingsQuery = bookingsQuery .Where(b => b.FlightInformation.DepartureCity.ToLower() == bookingSearchDto.DepartureCity.ToLower()); } var bookings = bookingsQuery.ToList(); return Ok(Mapper.Map<IEnumerable<Booking>, IEnumerable<BookingWithFlightInformationDto>>(bookings)); } [Route("api/booking/create")] [HttpPost] public IHttpActionResult CreateBooking(BookingDto bookingDto) { if (!ModelState.IsValid || bookingDto == null) { return BadRequest("Invalid Request"); } var flight = _context.Flights .Where(f => (f.FlightNumber == bookingDto.FlightNumber && f.StartTime == bookingDto.FlightStartTime && (f.AvailableSeats - bookingDto.NumberOfPassengers) >= 0)) .FirstOrDefault(); if(flight == null) { return NotFound(); } var bookingInfo = new Booking() { Date = DateTime.Now, PassengerName = bookingDto.PassengerName, NumberOfPassengers = bookingDto.NumberOfPassengers, FlightId = flight.Id }; _context.Bookings.Add(bookingInfo); flight.AvailableSeats = flight.AvailableSeats - bookingDto.NumberOfPassengers; _context.SaveChanges(); return Ok(true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Autofac; using Autofac.Integration.Mvc; using System.Web.Mvc; using System.Reflection; using SliceMvc.Infrastructure; using FluentValidation.Mvc; using FluentValidation; using SliceMvc.Infrastructure.Validation; namespace SliceMvc { internal class AutofacConfig { internal static void Register() { var builder = new ContainerBuilder(); // Register your MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); // OPTIONAL: Register model binders that require DI. builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase. builder.RegisterModule<AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages. builder.RegisterSource(new ViewRegistrationSource()); // OPTIONAL: Enable property injection into action filters. builder.RegisterFilterProvider(); // REGISTER TYPES HERE // REQUIRED: register all autofac modules builder.RegisterAssemblyModules(typeof(MvcApplication).Assembly); // REQUIRED: infrastucture registration builder.RegisterType<ControllerFactory>().As<IControllerFactory>(); builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>(); builder.RegisterType<ValidatorFactory>().As<IValidatorFactory>(); // Set the dependency resolver to be Autofac. var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
/*********************************************************************** * Module: Stars.cs * Author: Sladjana Savkovic * Purpose: Definition of the Class Model.Users.Stars ***********************************************************************/ using System; namespace Model.Users { public enum Stars { ONE = 0, TWO = 1, THREE = 2, FOUR = 3, FIVE = 4 } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. using FiiiChain.Entities; using System; using System.Collections.Generic; using Microsoft.Data.Sqlite; using System.Text; namespace FiiiChain.Data { public class InputDac : DataAccessComponent<InputDac> { public virtual long Insert(Input input) { const string SQL_STATEMENT = "INSERT INTO InputList " + "(TransactionHash, OutputTransactionHash, OutputIndex, Size, Amount, UnlockScript, AccountId, IsDiscarded, BlockHash) " + "VALUES (@TransactionHash, @OutputTransactionHash, @OutputIndex, @Size, @Amount, @UnlockScript, @AccountId, @IsDiscarded, @BlockHash);" + "SELECT LAST_INSERT_ROWID() newid;"; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Parameters.AddWithValue("@TransactionHash", input.TransactionHash); cmd.Parameters.AddWithValue("@OutputTransactionHash", input.OutputTransactionHash); cmd.Parameters.AddWithValue("@OutputIndex", input.OutputIndex); cmd.Parameters.AddWithValue("@Size", input.Size); cmd.Parameters.AddWithValue("@Amount", input.Amount); cmd.Parameters.AddWithValue("@UnlockScript", input.UnlockScript); if (string.IsNullOrWhiteSpace(input.AccountId)) { cmd.Parameters.AddWithValue("@AccountId", DBNull.Value); } else { cmd.Parameters.AddWithValue("@AccountId", input.AccountId); } cmd.Parameters.AddWithValue("@IsDiscarded", input.IsDiscarded); cmd.Parameters.AddWithValue("@BlockHash", input.BlockHash); cmd.Connection.Open(); //con.SynchronousNORMAL(); return Convert.ToInt64(cmd.ExecuteScalar()); } } public virtual void UpdateBlockAndDiscardStatus(long id, string blockHash, bool isDiscarded) { const string SQL_STATEMENT = "UPDATE InputList " + "SET IsDiscarded = @IsDiscarded, " + "BlockHash = @BlockHash " + "WHERE Id = @Id;"; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Parameters.AddWithValue("@IsDiscarded", isDiscarded); cmd.Parameters.AddWithValue("@BlockHash", blockHash); cmd.Parameters.AddWithValue("@Id", id); cmd.Connection.Open(); //con.SynchronousNORMAL(); cmd.ExecuteNonQuery(); } } public virtual List<Input> SelectByTransactionHash(string txHash) { const string SQL_STATEMENT = "SELECT * " + "FROM InputList " + "WHERE TransactionHash = @TransactionHash " + "AND IsDiscarded = 0 "; List<Input> result = null; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Parameters.AddWithValue("@TransactionHash", txHash); cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { result = new List<Input>(); while (dr.Read()) { Input input = new Input(); input.Id = GetDataValue<long>(dr, "Id"); input.TransactionHash = GetDataValue<string>(dr, "TransactionHash"); input.OutputTransactionHash = GetDataValue<string>(dr, "OutputTransactionHash"); input.OutputIndex = GetDataValue<int>(dr, "OutputIndex"); input.Size = GetDataValue<int>(dr, "Size"); input.Amount = GetDataValue<long>(dr, "Amount"); input.UnlockScript = GetDataValue<string>(dr, "UnlockScript"); input.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded"); input.AccountId = GetDataValue<string>(dr, "AccountId"); input.BlockHash = GetDataValue<string>(dr, "BlockHash"); result.Add(input); } } } return result; } public virtual List<Input> SelectFirstDiscardedByTransactionHash(string txHash) { const string SQL_STATEMENT = "SELECT * FROM InputList WHERE id IN ( " + "SELECT Id FROM InputList WHERE IsDiscarded = 1 AND TransactionHash = @TransactionHash " + "GROUP BY OutputIndex, OutputTransactionHash " + "HAVING COUNT(0) > 1)"; List<Input> result = null; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Parameters.AddWithValue("@TransactionHash", txHash); cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { result = new List<Input>(); while (dr.Read()) { Input input = new Input(); input.Id = GetDataValue<long>(dr, "Id"); input.TransactionHash = GetDataValue<string>(dr, "TransactionHash"); input.OutputTransactionHash = GetDataValue<string>(dr, "OutputTransactionHash"); input.OutputIndex = GetDataValue<int>(dr, "OutputIndex"); input.Size = GetDataValue<int>(dr, "Size"); input.Amount = GetDataValue<long>(dr, "Amount"); input.UnlockScript = GetDataValue<string>(dr, "UnlockScript"); input.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded"); input.AccountId = GetDataValue<string>(dr, "AccountId"); input.BlockHash = GetDataValue<string>(dr, "BlockHash"); result.Add(input); } } } return result; } public virtual Input SelectById(long id) { const string SQL_STATEMENT = "SELECT * " + "FROM InputList " + "WHERE Id = @Id " + "AND IsDiscarded = 0 "; Input input = null; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Parameters.AddWithValue("@Id", id); cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { input = new Input(); input.Id = GetDataValue<long>(dr, "Id"); input.TransactionHash = GetDataValue<string>(dr, "TransactionHash"); input.OutputTransactionHash = GetDataValue<string>(dr, "OutputTransactionHash"); input.OutputIndex = GetDataValue<int>(dr, "OutputIndex"); input.Size = GetDataValue<int>(dr, "Size"); input.Amount = GetDataValue<long>(dr, "Amount"); input.UnlockScript = GetDataValue<string>(dr, "UnlockScript"); input.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded"); input.AccountId = GetDataValue<string>(dr, "AccountId"); input.BlockHash = GetDataValue<string>(dr, "BlockHash"); } } return input; } } public virtual List<Input> SelectByOutputHash(string outputHash, int outputIndex) { const string SQL_STATEMENT = "SELECT * " + "FROM InputList " + "WHERE OutputTransactionHash = @OutputTransactionHash AND OutputIndex = @OutputIndex " + "AND IsDiscarded = 0 "; List<Input> items = new List<Input>(); using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Parameters.AddWithValue("@OutputTransactionHash", outputHash); cmd.Parameters.AddWithValue("@OutputIndex", outputIndex); cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { var input = new Input(); input.Id = GetDataValue<long>(dr, "Id"); input.TransactionHash = GetDataValue<string>(dr, "TransactionHash"); input.OutputTransactionHash = GetDataValue<string>(dr, "OutputTransactionHash"); input.OutputIndex = GetDataValue<int>(dr, "OutputIndex"); input.Size = GetDataValue<int>(dr, "Size"); input.Amount = GetDataValue<long>(dr, "Amount"); input.UnlockScript = GetDataValue<string>(dr, "UnlockScript"); input.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded"); input.AccountId = GetDataValue<string>(dr, "AccountId"); input.BlockHash = GetDataValue<string>(dr, "BlockHash"); items.Add(input); } } return items; } } public virtual List<string> GetCostUtxos() { const string SQL_STATEMENT = "select inputlist.OutputTransactionHash,inputlist.OutputIndex from inputlist inner join outputlist on inputlist.OutputTransactionHash = outputlist.transactionhash and inputlist.Outputindex = outputlist.[index]"; List<string> costUtxos = new List<string>(); using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { var key = GetDataValue<string>(dr, "OutputTransactionHash"); var value = GetDataValue<int>(dr, "OutputIndex"); costUtxos.Add($"{key }_{value }"); } } } return costUtxos; } public virtual long SelectTotalAmount(IEnumerable<string> hashIndexs) { var hi = $"('{string.Join("','", hashIndexs)}')"; var SQL_STATEMENT = "select sum(Amount) as TotalAmount from outputlist where TransactionHash||[Index] in " + hi; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { if (dr.IsDBNull(0)) return 0; else return GetDataValue<long>(dr, "TotalAmount"); } } } return 0; } public virtual int SelectUnSpentCount(IEnumerable<string> hashIndexs) { var hi = $"('{string.Join("','", hashIndexs)}')"; var SQL_STATEMENT = "select count(Amount) as TotalCount from outputlist join blocks on outputlist.BlockHash = blocks.Hash and blocks.IsDiscarded=0 " + "where outputlist.TransactionHash || outputlist.[Index] in " + hi + " and (select count(*) from inputList where OutputTransactionHash = TransactionHash and OutputIndex = [index]) =0"; using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString)) using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con)) { cmd.Connection.Open(); //con.SynchronousNORMAL(); using (SqliteDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { if (dr.IsDBNull(0)) return 0; else return GetDataValue<int>(dr, "TotalCount"); } } } return 0; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.IO; using RevStack.Pattern; namespace RevStack.IO { public interface IIORepository : IRepository<FileData,string> { IEnumerable<FileData> Get(string path, string searchPattern, SearchOption searchOption); Task<IEnumerable<FileData>> GetAsync(string path, string searchPattern, SearchOption searchOption); } }
namespace MtSac.LabFinal { interface IPayable { decimal GetWeeklyPayAmount(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProxyExample { class ProxyCustomerDataAccessObject : ICustomerDataAccessObject { CustomerDataAccessObject _customDataAccessObject = null; bool _authenticated = false; public ProxyCustomerDataAccessObject(int userId) { var authenticator = new Authenticator(); if (authenticator.AuthenticateUser(userId)) _customDataAccessObject = new CustomerDataAccessObject(); } public List<Customer> GetActiveCustomer() { if (_authenticated) return _customDataAccessObject.GetActiveCustomer(); else return new List<Customer>(); } } }
using System; namespace VirginMediaScenario.Models { internal class DisplayNameAttribute : Attribute { } }
using Biz; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace BIZ { public static class BizReg { public static bool Validate(string UserID,string PassWord) { Dictionary<string, object> FieldValues = new Dictionary<string, object>(); FieldValues.Add("NAME", UserID); FieldValues.Add("PASSWORD", PassWord); return Convert.ToInt32(BizCenter.DataAccessor.GetDataValue("ValidateReg", FieldValues, -1)) == 0 ? true : false; } } }
namespace PizzaMore.Utility { using System.IO; using Contracts; public class FileReader : IFileReader { public string ReadHtml(string path) { return File.ReadAllText(path); } } }
using System; using UnityEngine.Events; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// None generic Unity Event of type `ColliderPair`. Inherits from `UnityEvent&lt;ColliderPair&gt;`. /// </summary> [Serializable] public sealed class ColliderPairUnityEvent : UnityEvent<ColliderPair> { } }
using System; namespace DEV_4 { class EntryPoint { static void Main(string [] args) { bool duration = true; while (duration) { try { if (args.Length == 0) { Console.WriteLine("You did not enter values in the command line. Enter the sequence of integers: "); string enteredString = Console.ReadLine(); string[] stringSequence = enteredString.Split(' '); SequenseOfNumbers sequenceOfNumbers = new SequenseOfNumbers(); int[] sequence = sequenceOfNumbers.ConvertToInt(stringSequence); bool result = sequenceOfNumbers.IsSequenceNondecreasing(sequence); sequenceOfNumbers.OutputOfResult(result); } else { SequenseOfNumbers sequenceOfNumbers = new SequenseOfNumbers(); int[] sequence = sequenceOfNumbers.ConvertToInt(args); bool result = sequenceOfNumbers.IsSequenceNondecreasing(sequence); sequenceOfNumbers.OutputOfResult(result); } } catch (FormatException) { Console.WriteLine("Enter integers!!Try again: \n"); continue; } duration = false; } } } }
using Isop.Client; using Isop.Client.Json; using Isop.Gui.Adapters; using System; using System.Collections.Generic; using System.ComponentModel; namespace Isop.Gui.ViewModels { public class SelectClientViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _url; public string Url { get { return _url; } set { _url = value; PropertyChanged.SendPropertyChanged(this, "Url"); } } public event Action Loaded; public virtual void OnLoad() { if (Loaded != null) { Loaded.Invoke(); } } internal IClient GetClient() { if (BuildClient.CanLoad(Url)) { var build = new Build(); build.ConfigurationFrom(System.Reflection.Assembly.LoadFile(Url)); return new BuildClient(build); } if (JsonClient.CanLoad(Url)) { return new JsonClient(new IsopClient(new JsonHttpClient(), Url)); } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _12.Matrix { class MatrixCube { static void Main() { Console.Write("Enter a number (<20): "); byte userInput = byte.Parse(Console.ReadLine()); while (userInput > 20) { Console.WriteLine("Incorrect input! Enter new number: "); userInput = byte.Parse(Console.ReadLine()); } byte [,] cube = new byte [userInput, userInput]; for (int row = 1; row <= userInput; row++) { for (int col = row; col < row + userInput; col++) { Console.Write(" " + col); } Console.WriteLine(); } } } }
namespace Core.Entities { public class TrainInfo { public int FreeSeats { get; set; } public int TypeId { get; set; } public string Class { get; set; } public decimal Price { get; set; } public string Type { get; set; } public string TypeLoc { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; using log4net; namespace PaletteInstaller.utils { class RegistryTool { private static readonly ILog log = LogManager.GetLogger("RegistryTool"); public static readonly string DEFAULT = "N/A"; // The name of the key must include a valid root. private const string userRoot = "HKEY_LOCAL_MACHINE"; private const string subkey = "ISAT"; private string keyName; public RegistryTool(string secction) { keyName = subkey + "\\" + secction; } public string readString(string field) { string value = ""; RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\ISAT\\Palette", true); if (rk == null) rk = Registry.LocalMachine.CreateSubKey("SOFTWARE\\ISAT\\Palette"); value = (string)rk.GetValue(field, DEFAULT); return value; } public bool writeString(string field, string value) { bool result = true; try { RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\ISAT\\Palette", true); rk.SetValue(field, value); }catch(Exception ex) { log.Error("Registry Tool Error: " + ex.Message); result = false; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using Core.DAL; using System.ComponentModel.DataAnnotations; namespace Core.BIZ { public class TheKho { public TheKho() { } public TheKho(THEKHO thekho) { MaSoSach = thekho.masosach; SoLuong = thekho.soluong; NgayGhi = thekho.ngayghi; } public TheKho(THEKHO thekho,SACH sach) :this(thekho) { Sach = new Sach(sach); } #region Private Properties private Sach _sach; private static List<string> _searchKeys; #endregion #region Public Properties [Required] [DisplayName(TheKhoManager.Properties.MaSoSach)] public int MaSoSach { get; set; } [DisplayName(TheKhoManager.Properties.Sach)] public Sach Sach { get { if (_sach == null) { _sach = SachManager.find(this.MaSoSach); } return _sach; } set { _sach = value; } } [Required] [DisplayName(TheKhoManager.Properties.SoLuong)] public decimal SoLuong { get; set; } [Required] [DisplayName(TheKhoManager.Properties.NgayGhi)] public DateTime NgayGhi { get; set; } #endregion #region Services public static List<string> searchKeys() { if(_searchKeys == null) { _searchKeys = new List<string>(); _searchKeys.Add(nameof(TheKhoManager.Properties.MaSoSach)); _searchKeys.Add(nameof(SachManager.Properties.TenSach)); _searchKeys.Add(nameof(SachManager.Properties.TenTacGia)); _searchKeys.Add(nameof(TheKhoManager.Properties.SoLuong)); _searchKeys.Add(nameof(TheKhoManager.Properties.NgayGhi)); } return _searchKeys; } #endregion #region Override Methods public override string ToString() { return this.Sach.TenSach; } #endregion } }
// ----------------------------------------------------------------------- // <copyright file="ServiceCollectionExtensions.cs"> // Copyright (c) Michal Pokorný. All Rights Reserved. // </copyright> // ----------------------------------------------------------------------- namespace Pentagon.Extensions.Localization.EntityFramework { using Entities; using EntityFrameworkCore.Extensions; using Interfaces; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Persistence; [PublicAPI] public static class ServiceCollectionExtensions { [NotNull] public static IServiceCollection AddEfCultureLocalization([NotNull] this IServiceCollection services, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) { services.AddCulture(); services.AddStoreTransient<CultureEntity>(); services.AddStoreTransient<CultureResourceEntity>(); services.TryAdd(ServiceDescriptor.Describe(typeof(ICultureRetriever), typeof(CultureService), serviceLifetime)); services.TryAdd(ServiceDescriptor.Describe(typeof(ICultureStore), typeof(CultureService), serviceLifetime)); return services; } } }
using System; namespace SortingArrayOfObjects { public class Demo1 { public static void Run() { int[] intArray = { 10, 90, 70, 50, 30, 20, 40, 60, 80, 100 }; Console.WriteLine("Sebelum diurutkan:"); foreach (int i in intArray) { Console.Write("{0} ", i); } Array.Sort(intArray); Console.WriteLine("\n\nSetelah diurutkan:"); foreach (int i in intArray) { Console.Write("{0} ", i); } } } }
namespace Sentry.Android.AssemblyReader.Tests; public class AndroidAssemblyReaderTests { private readonly ITestOutputHelper _output; public AndroidAssemblyReaderTests(ITestOutputHelper output) { _output = output; } private IAndroidAssemblyReader GetSut(bool isAssemblyStore, bool isCompressed) { #if ANDROID var logger = new TestOutputDiagnosticLogger(_output); return AndroidHelpers.GetAndroidAssemblyReader(logger)!; #else var apkPath = Path.GetFullPath(Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "..", "..", "..", "TestAPKs", $"android-Store={isAssemblyStore}-Compressed={isCompressed}.apk")); _output.WriteLine($"Checking if APK exists: {apkPath}"); File.Exists(apkPath).Should().BeTrue(); string[] supportedAbis = {"x86_64"}; return AndroidAssemblyReaderFactory.Open(apkPath, supportedAbis, logger: (message, args) => _output.WriteLine(message, args)); #endif } [SkippableTheory] [InlineData(false)] [InlineData(true)] public void CreatesCorrectReader(bool isAssemblyStore) { #if ANDROID Skip.If(true, "It's unknown whether the current Android app APK is an assembly store or not."); #endif using var sut = GetSut(isAssemblyStore, isCompressed: true); if (isAssemblyStore) { Assert.IsType<AssemblyReader.AndroidAssemblyStoreReader>(sut); } else { Assert.IsType<AssemblyReader.AndroidAssemblyDirectoryReader>(sut); } } [SkippableTheory] [InlineData(false)] [InlineData(true)] public void ReturnsNullIfAssemblyDoesntExist(bool isAssemblyStore) { using var sut = GetSut(isAssemblyStore, isCompressed: true); Assert.Null(sut.TryReadAssembly("NonExistent.dll")); } [SkippableTheory] [InlineData(false, true, "Mono.Android.dll")] [InlineData(false, false, "Mono.Android.dll")] [InlineData(false, true, "System.Runtime.dll")] [InlineData(false, false, "System.Runtime.dll")] [InlineData(true, true, "Mono.Android.dll")] [InlineData(true, false, "Mono.Android.dll")] [InlineData(true, true, "System.Runtime.dll")] [InlineData(true, false, "System.Runtime.dll")] public void ReadsAssembly(bool isAssemblyStore, bool isCompressed, string assemblyName) { #if ANDROID // No need to run all combinations - we only test the current APK which is (likely) compressed assembly store. Skip.If(!isAssemblyStore); Skip.If(!isCompressed); #endif using var sut = GetSut(isAssemblyStore, isCompressed); var peReader = sut.TryReadAssembly(assemblyName); Assert.NotNull(peReader); Assert.True(peReader.HasMetadata); var headers = peReader.PEHeaders; Assert.True(headers.IsDll); headers.MetadataSize.Should().BeGreaterThan(0); Assert.NotNull(headers.PEHeader); headers.PEHeader.SizeOfImage.Should().BeGreaterThan(0); var debugDirs = peReader.ReadDebugDirectory(); debugDirs.Length.Should().BeGreaterThan(0); } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Windows.Forms; namespace WindowsFormsApp { public partial class Form1 : Form { dynamic res; string input; localhost.WebService myLib; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { myLib = new localhost.WebService(); } private void Button1_Click(object sender, EventArgs e) { input = textBox1.Text; using (WaitForm frm = new WaitForm(StartFibonnaci)) { frm.ShowDialog(); } MessageBox.Show(res.ToString(), "Fibonnaci"); } private void StartFibonnaci() { res = myLib.Fibonnaci(input); } private void Button2_Click(object sender, EventArgs e) { input = textBox6.Text; using (WaitForm frm = new WaitForm(StartConvertXml)) { frm.ShowDialog(); } try { JToken parsedJson = JToken.Parse(res); var beautified = parsedJson.ToString(Formatting.Indented); textBox7.Text = beautified; } catch (Exception ex) { textBox7.Text = ex.Message; } } private void StartConvertXml() { res = myLib.XmlToJson(input); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; public class ChangeScene : MonoBehaviour { public string destinationSceneName; public void Go() { SceneManager.LoadScene(destinationSceneName); } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Controllers; namespace Robot.Backend { // This is a simple filter to collect usage stats for the ApiController class. // It could be generalised to include all Controllers and/or to provide more // data such as success/failure counts. public class ApiUsage { public long Count { get; private set; } public void IncrementCount() { Count += 1; } } public class ApiUsageFilter : IActionFilter { readonly Dictionary<string, ApiUsage> _actionCounts = new Dictionary<string, ApiUsage>(); public IDictionary<string, ApiUsage> ActionCounts => _actionCounts; public void OnActionExecuting(ActionExecutingContext context) { } public void OnActionExecuted(ActionExecutedContext context) { if (context.Controller is Controllers.ApiController _) { if (context.ActionDescriptor is ControllerActionDescriptor descriptor) { if (!_actionCounts.TryGetValue(descriptor.ActionName, out var usage)) { usage = new ApiUsage(); _actionCounts[descriptor.ActionName] = usage; } usage.IncrementCount(); } } } } }
using PhotonInMaze.Common.Controller; using PhotonInMaze.Common.Flow; using PhotonInMaze.Common.Model; using System.Collections.Generic; using UnityEngine; namespace PhotonInMaze.Maze { internal partial class PathToGoalManager : FlowUpdateBehaviour, IPathToGoalManager { [SerializeField] private Material pathLine, pathCurve, pathEnd; internal Dictionary<IMazeCell, GameObject> pathToGoalFloors { get; private set; } private struct FloorState { public float yRotation; public Material material; public FloorState(float yRotation, Material material) { this.yRotation = yRotation; this.material = material; } } private void PaintPathToGoal() { LinkedListNode<IMazeCell> current = PathToGoal.First; while(current != null) { GameObject currentFloor = pathToGoalFloors[current.Value]; Renderer renderer = currentFloor.GetComponent<Renderer>(); LinkedListNode<IMazeCell> next = current.Next, previous = current.Previous; FloorState floorState = new FloorState(); if(previous == null) { floorState = InitEnd(current.Value, next.Value); } else if(next == null) { floorState = InitEnd(current.Value, previous.Value); } else { floorState = InitFloor(current, next, previous); } currentFloor.transform.rotation = Quaternion.Euler(0f, floorState.yRotation, 0f); renderer.material = floorState.material; current = next; } GameFlowManager.Instance.Flow.NextState(); } private FloorState InitEnd(IMazeCell current, IMazeCell related) { if(related.Row < current.Row) { return new FloorState(90f, pathEnd); } else if(related.Row > current.Row) { return new FloorState(270f, pathEnd); } else if(related.Column < current.Column) { return new FloorState(180f, pathEnd); } else { return new FloorState(0f, pathEnd); } } private FloorState InitFloor(LinkedListNode<IMazeCell> current, LinkedListNode<IMazeCell> next, LinkedListNode<IMazeCell> previous) { FloorState floorState = new FloorState(); if(current.Value.Row < next.Value.Row) { if(previous.Value.Row < current.Value.Row) { floorState = new FloorState(90f, pathLine); } else { floorState = new FloorState(previous.Value.Column < current.Value.Column ? 180f : -90f, pathCurve); } } else if(current.Value.Row > next.Value.Row) { if(previous.Value.Row > current.Value.Row) { floorState = new FloorState(90f, pathLine); } else { floorState = new FloorState(previous.Value.Column < current.Value.Column ? 90f : 0f, pathCurve); } } else if(current.Value.Column < next.Value.Column) { if(previous.Value.Column < current.Value.Column) { floorState = new FloorState(0f, pathLine); } else { floorState = new FloorState(previous.Value.Row < current.Value.Row ? 0 : -90f, pathCurve); } } else if(current.Value.Column > next.Value.Column) { if(previous.Value.Column > current.Value.Column) { floorState = new FloorState(0f, pathLine); } else { floorState = new FloorState(previous.Value.Row < current.Value.Row ? 90f : 180f, pathCurve); } } return floorState; } } }
using System; namespace Assets.Scripts.Mathx { public static class Mathematic { /// <summary> /// Sayıyı verilen değerin katlarına yuvarlar /// </summary> /// <param name="value">Verilecek değer</param> /// <param name="multiple">Yuvarlanacak kat</param> /// <returns></returns> public static float RoundToMultiple(float value, float multiple) { return (float) Math.Round(value / multiple) * multiple; } } }
using Android.Graphics; using Android.Views; using Xamarin.Forms; namespace AsNum.XFControls.Droid { public static class Helper { public static Typeface ToTypeface(this string fontfamilary) { try { return Typeface.CreateFromAsset(Forms.Context.Assets, fontfamilary); } catch { return Typeface.Default; } } public static GravityFlags ToHorizontalGravityFlags(this Xamarin.Forms.TextAlignment alignment) { if (alignment == Xamarin.Forms.TextAlignment.Center) return GravityFlags.AxisSpecified; return alignment == Xamarin.Forms.TextAlignment.End ? GravityFlags.Right : GravityFlags.Left; } public static GravityFlags ToVerticalGravityFlags(this Xamarin.Forms.TextAlignment alignment) { if (alignment == Xamarin.Forms.TextAlignment.Start) return GravityFlags.Top; return alignment == Xamarin.Forms.TextAlignment.End ? GravityFlags.Bottom : GravityFlags.CenterVertical; } } }
using Backend.Model; using Backend.Model.Pharmacies; using IntegrationAdaptersTenderService.Controllers; using IntegrationAdaptersTenderService.Repository.Implementation; using IntegrationAdaptersTenderService.Service; using IntegrationAdaptersTenderService.Service.RabbitMqTenderingService; using Moq; using System; using System.Collections.Generic; using Xunit; namespace IntegrationAdaptersTests.IntegrationTests { public class TenderControllerTest { [Fact] public void PushDrugList_Invalid_List() { DbContextInMemory testData = new DbContextInMemory(); MyDbContext context = testData._context; TenderServiceController controller = new TenderServiceController(new TenderService(new MySqlTenderRepository(context)), new TenderMessageService(new MySqlTenderMessageRepository(context)), new Mock<IRabbitMqTenderingService>().Object); controller.CreateTender(new TenderDTO()); Assert.True(context.Tenders.Find(2) == null); } [Fact] public void PushDrugList_Valid_List() { DbContextInMemory testData = new DbContextInMemory(); MyDbContext context = testData._context; TenderServiceController controller = new TenderServiceController(new TenderService(new MySqlTenderRepository(context)), new TenderMessageService(new MySqlTenderMessageRepository(context)), new Mock<IRabbitMqTenderingService>().Object); controller.CreateTender(new TenderDTO() { Name = "tender-2", EndDate = new DateTime(2021, 5, 5), Drugs = new List<TenderDrug>() { new TenderDrug() { DrugId = 1, Quantity = 5 } } }); Assert.True(context.Tenders.Find(2) != null); } [Fact] public void CloseTender_Valid_Id() { DbContextInMemory testData = new DbContextInMemory(); MyDbContext context = testData._context; TenderServiceController controller = new TenderServiceController(new TenderService(new MySqlTenderRepository(context)), new TenderMessageService(new MySqlTenderMessageRepository(context)), new Mock<IRabbitMqTenderingService>().Object); controller.CloseTender(1); Assert.True(context.Tenders.Find(1).IsClosed); } } }
using System; using System.Collections.Generic; using DAL.Models; namespace BLL.Contracts { public interface IRatingService { void AddRating(Rating rating); void Edit(Rating rating); IEnumerable<Rating> GetAll(); double CountRatingByMovieId(Guid movieId); void DeleteByMovieIdAndUserId(Guid movieId, string userId); } }
using UnityEngine; namespace Hackathon { public class Puppet : TimeBehaviour { [SerializeField] private Transform[] wayPoints; private new Animation animation; protected virtual void Awake() { animation = GetComponent<Animation>(); } protected virtual void Start() { var puppeteer = FindObjectOfType<Puppeteer>(); timeline.recordingDuration = puppeteer.lifetime; timeline.Do(true, forward: () => { animation.Play(); }, backward: () => { }); } public void Position(float normalizedPos) { if (wayPoints.Length == 0) return; Transform secondClosestPoint = wayPoints[0]; Transform closestPoint = wayPoints[0]; for (int i = 1; i < wayPoints.Length; i++) { if ((wayPoints[i].position - transform.position).magnitude < (closestPoint.position - transform.position).magnitude) { secondClosestPoint = closestPoint; closestPoint = wayPoints[i]; } } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using FootballTAL.BusinessLogic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Reflection; using FootballTAL.DataAccess; using Moq; namespace FootballTAL.BusinessLogic.Tests { [TestClass()] public class FootballClubArray_Tests { string validFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Resources\football.csv"); string FileMissingHeader = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Resources\football_NoTitle.csv"); string FileWrongColumnCount = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Resources\football_ColumnCountErr.csv"); string FileCellError = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Resources\football_CellError.csv"); [TestMethod()] public void GetFootballClubList_FootballClubListIsNull() { var tester = new FootballClubArray(); Assert.AreEqual(false,tester.GetContainsError()); } [TestMethod()] public void GetFootballClubList_ValidInput() { var tester = new FootballClubArray(); var output=tester.GetFootballClubList(new CSVFileReading(validFile)); Assert.AreEqual(20, output.Count); Assert.AreEqual(0, output.Where(i => i.ErrorFound).Count()); Assert.AreEqual(false, tester.GetContainsError()); } [TestMethod()] public void GetFootballClubList_MissingHeader() { var tester = new FootballClubArray(); var ouput = tester.GetFootballClubList(new CSVFileReading(FileMissingHeader)); Assert.AreEqual(20, ouput.Count); Assert.AreEqual(0, ouput.Where(i => i.ErrorFound).Count()); Assert.AreEqual(false, tester.GetContainsError()); } [TestMethod()] public void GetFootballClubList_CellFormatError() { var tester = new FootballClubArray(); var ouput = tester.GetFootballClubList(new CSVFileReading(FileCellError)); Assert.AreEqual(20, ouput.Count); Assert.AreEqual(2, ouput.Where(i => i.ErrorFound).Count()); Assert.AreEqual(true, tester.GetContainsError()); } [TestMethod()] public void GetFootballClubList_WrongColumnCount() { var tester = new FootballClubArray(); var ouput = tester.GetFootballClubList(new CSVFileReading(FileCellError)); Assert.AreEqual(20, ouput.Count); Assert.AreEqual(2, ouput.Where(i=>i.ErrorFound).Count()); Assert.AreEqual(true, tester.GetContainsError()); } [TestMethod()] public void GetFootballClubList_moq() { var list = new List<string[]>(); list.Add(new string[] { "1. ClubName", "1", "2", "3", "4", "5", "-", "6", "7" }); list.Add(new string[] { "1. ClubName", "11", "22", "33", "44", "55", "-", "66", "77" }); var mock = new Mock<IFileReading>(); mock.Setup(x => x.ReadFile()).Returns(list); var tester = new FootballClubArray(); var ouput = tester.GetFootballClubList(mock.Object); Assert.AreEqual(mock.Object.ReadFile().Count, 2); Assert.AreEqual(ouput.Count,2); Assert.AreEqual( ouput.Where(i => i.ErrorFound).Count(),0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using CIPMSBC; /// <summary> /// Summary description for AppRouteDisplayManager /// </summary> public class AppRouteDisplayManager { /// <summary> /// An abstration to check if an app status has eligible status or not. This is better than check on each program. /// </summary> /// <returns></returns> public static bool IsAppEligible() { var flag = false; var statusObj = HttpContext.Current.Session["STATUS"]; if (statusObj != null) { var status = (StatusInfo)Convert.ToInt32(statusObj); if (status == StatusInfo.SystemEligible || status == StatusInfo.EligibleCampCoupon || status == StatusInfo.EligiblePendingSchool || status == StatusInfo.Eligibledayschool || status == StatusInfo.EligiblePendingNumberOfDays || status == StatusInfo.EligiblePJLottery ) { flag = true; } } return flag; } }
 using System.Collections.Generic; using System.Linq; using SantaWorkshop.Models.Presents.Contracts; using SantaWorkshop.Repositories.Contracts; namespace SantaWorkshop.Repositories { class PresentRepository : IRepository<IPresent> { private readonly List<IPresent> _models; public PresentRepository() { this._models = new List<IPresent>(); } public IReadOnlyCollection<IPresent> Models => this._models; public void Add(IPresent model) { this._models.Add(model); } public bool Remove(IPresent model) { return this._models.Remove(model); } public IPresent FindByName(string name) { return this._models.FirstOrDefault(p => p.Name == name); } } }
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 MySql.Data.MySqlClient; namespace Miniprojet.Administrateur.Tarif { public partial class Supprimer : Form { public Supprimer() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { Administrateur a = new Administrateur(); this.Hide(); a.Show(); } private void button1_Click(object sender, EventArgs e) { string Insertion1 = "delete from tarification where Id_tarif =?"; MySqlCommand cmd1 = new MySqlCommand(Insertion1, ManipulationBD.Cnn); MySqlParameter p1 = new MySqlParameter("Id_tarif", textBox6.Text); cmd1.Parameters.Add(p1); try { ManipulationBD.ConnectionDataBase(); cmd1.ExecuteNonQuery(); cmd1.Parameters.Clear(); MessageBox.Show("Suppression effectuez"); } catch (Exception r) { MessageBox.Show(r.Message); } finally { ManipulationBD.DecoonectionDataBase(); } } private void button3_Click(object sender, EventArgs e) { ManipulationBD.ConnectionDataBase(); listView1.Items.Clear(); MySqlCommand cmd = new MySqlCommand(" Select * from tarification", ManipulationBD.Cnn); using (MySqlDataReader read = cmd.ExecuteReader()) { while(read.Read()) { string ID = read["Id_tarif"].ToString(); string Cat = read["categorie"].ToString(); string TC = read["tarif_chauff"].ToString(); string TL = read["tarif_loc_jr"].ToString(); string TH = read["tarif_loc_jr"].ToString(); string TKm = read["tarif_km_parc"].ToString(); string DT = read["date_tarif"].ToString(); listView1.Items.Add(new ListViewItem(new[] { ID, Cat, TC,TL, TH, TKm, DT })); } } ManipulationBD.DecoonectionDataBase(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WcfServiceHost.ITS_Service { using Entity; using Repository.ITSRepo; using DTO.ITSDTO; using System.ServiceModel; public class FirmaKoliService : ITS_ServiceBase<FirmaKoliRepo , FirmaKoli, FirmaKoliDTO>, IFirmaKoliService { } [ServiceContract] public interface IFirmaKoliService : IServiceBase<FirmaKoliDTO> { } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using NSec.Cryptography; using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.Framework { public class RandomNumber { public static byte[] Generate(int size) { return RandomGenerator.Default.GenerateBytes(size); } } }
using Common.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Contracts { public interface IDbLocalController { void Connect(string code); void Create(string code); LocalController GetLocalController(string code); void TurnOnLCGenerators(string code); void ShutDownGenerators(string code); List<LocalController> ReadAll(); bool IsCodeFree(string code); bool IsOnline(string code); void ShutDown(string code); void SaveChanges(Generator generator); } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using ZaventDotNetInterview.Models; namespace ZavenDotNetInterview.Abstract { public interface IRepository<TEntity> where TEntity : BaseEntityModel { TEntity Get(Guid id); IEnumerable<TEntity> GetAll(); Guid Add(TEntity entity); } }
using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Infrastructure; using SFA.DAS.ProviderCommitments.Web.Authentication; using SFA.DAS.ProviderCommitments.Web.Extensions; namespace SFA.DAS.ProviderCommitments.Web.Authorization { /// <summary> /// If the current route contains a {ProviderId} parameter (case is not sensitive) then this handler /// will block access if the UkPrn value for the current user does not equal the provider id specified in /// the route. /// </summary> /// <remarks> /// This only checks route parameters. Query parameters are not inspected. /// </remarks> public class ProviderHandler : AuthorizationHandler<ProviderRequirement> { private readonly IActionContextAccessor _actionContextAccessor; public ProviderHandler(IActionContextAccessor actionContextAccessor) { _actionContextAccessor = actionContextAccessor; } protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ProviderRequirement requirement) { var actionContext = _actionContextAccessor.ActionContext; if (!HasServiceAuthorization(context)) { context.Fail(); } else if (actionContext.RouteData.Values.TryGetValue("ProviderId", out var providerIdSpecifiedInRoute)) { var currentUsersProviderId = context.User.Claims.FirstOrDefault(claim => claim.Type == ProviderClaims.Ukprn); if (currentUsersProviderId == null) { context.Fail(); } else if (currentUsersProviderId.Value != providerIdSpecifiedInRoute.ToString()) { context.Fail(); } else { context.Succeed(requirement); } } return Task.CompletedTask; } private bool HasServiceAuthorization(AuthorizationHandlerContext context) { var serviceClaims = context.User.FindAll(c => c.Type.Equals(ProviderClaims.Service)); return serviceClaims.Any(claim => claim.Value.IsServiceClaim()); } } }
using EduHome.Models.Base; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EduHome.Models.Entity { public class Subscribe:BaseEntity { public string Title { get; set; } public string Text { get; set; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using CIPMSBC; public partial class Enrollment_ReturningCamper : System.Web.UI.Page { private SrchCamperDetails _objCamperDet = new SrchCamperDetails(); protected void Page_Load(object sender, EventArgs e) { //Populate DataGrid if (IsPostBack != true) { PopulateGrid(); } } private void PopulateGrid() { DataSet dsCamper = new DataSet(); dsCamper =(DataSet)Session["DSCamperDetails"]; gvReturningCamper.DataSource = dsCamper; gvReturningCamper.DataBind(); } protected void gvReturningCamper_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "FJCID") { string strFJCID = e.CommandArgument.ToString(); Session["FJCID"] = strFJCID; string strRedirURL = "Step1.aspx?check=popup"; string link="Step1.aspx"; string strScript = "<script language=javascript>window.close();if (window.opener && !window.opener.closed) { window.opener.location.reload( true ); } window.location='" + strRedirURL + "'; </script>"; if (!ClientScript.IsStartupScriptRegistered("clientScript")) { ClientScript.RegisterStartupScript(Page.GetType(), "clientScript", strScript); } } } }
using Gap.NetFest.Core.Models; using System; using System.Collections.Generic; using System.Text; namespace Gap.NetFest.Core.Interface { public interface IInvoice { bool SaveInvoice(Invoice invoiceSimulation); bool SaveInvoice(string invoiceSimulation); string DequeueMessage(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float gas=10000f; public LayerMask layerMask; public GameObject explotionPrefab; [SerializeField][Range(0, 50)] float speedForce; [SerializeField] [Range(0, 50)] float speedRotation; public delegate void ZoomCamera(bool isInside); public ZoomCamera ZoomAction; [SerializeField] [Range(0, 3)] float lerpTime; private Camera camera; private Vector3 CameraInitialPosition; [Range(0,5)]public float Distancex,Distancey; private bool canZoom = false; void Start() { camera = Camera.main; CameraInitialPosition = camera.transform.position; } void Update() { Movement(); Zoom(); } public void Movement() { Vector2 Movement = GetComponent<Rigidbody2D>().velocity; if (!GameManager.GetInstance().pause) { GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None; if (Input.GetKey(KeyCode.UpArrow) && gas >= 0) { GetComponent<Rigidbody2D>().AddForce(new Vector2(-transform.rotation.z, speedForce * Time.deltaTime)); GetComponentInChildren<Animator>().SetTrigger("Flying"); gas--; } else { GetComponentInChildren<Animator>().ResetTrigger("Flying"); } if (Input.GetKey(KeyCode.LeftArrow)) { transform.Rotate(0, 0, speedRotation * Time.deltaTime); } if (Input.GetKey(KeyCode.RightArrow)) { transform.Rotate(0, 0, -speedRotation * Time.deltaTime); } } else { GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePosition; } } public void ZoomInOut(bool isInside) { if (isInside) { camera.transform.position = Vector3.MoveTowards(camera.transform.position, new Vector3(transform.position.x, transform.position.y,camera.transform.position.z), 1);// zoom camera.orthographicSize = 5; canZoom = true; } else if(!isInside) { camera.transform.position = Vector3.MoveTowards(camera.transform.position, CameraInitialPosition, 1); //de-zoom camera.orthographicSize = 7; } } public void Zoom() { if (Physics2D.OverlapCircle(new Vector2(transform.position.x, transform.position.y), 1f,layerMask)) { ZoomAction = ZoomInOut; ZoomAction(true); } else if (ZoomAction != null) { ZoomAction(false); } } void OnDisable() { if (!this.gameObject.scene.isLoaded) return; Instantiate(explotionPrefab, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity); } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TwingateExrc.Tests; namespace TwingateExrc { class Program { static void Main(string[] args) { AsyncTest.Run(); FragmentationTest.Run(); MemoryOverflowTest.Run(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; namespace M101DotNet.WebApp.Models { public class User { // XXX WORK HERE // create an object suitable for insertion into the user collection // The homework instructions will tell you the schema that the documents // must follow. Make sure to include Name and Email properties. public string Name { get; set; } public string Email { get; set; } public MongoDB.Bson.ObjectId _id { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Different { internal class Exc10 { public static void MainExc10() { Random rnd = new Random(); //Hashtable ht = new Hashtable(); SortedList ht = new SortedList(); int n = 8; int a = 1; int b = 2; int c; char val = Convert.ToChar(rnd.Next(65, 90)); ht.Add(a, val); val = Convert.ToChar(rnd.Next(65, 90)); ht.Add(b, val); for (int i = 1; i <= n; i++) { c = a + b; a = b; b = c; val = Convert.ToChar(rnd.Next(65, 90)); ht.Add(c, val); } ICollection keys = ht.Keys; ICollection values = ht.Values; foreach (int i in keys) { Console.Write(i+"\t"); } Console.WriteLine(); foreach (char i in ht.Values) { Console.Write(i+"\t"); } Console.WriteLine(); } } }
using OnlineGallery.Areas.Identity.Data; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace OnlineGallery.Models { [Table("AuctionRecord")] public class AuctionRecord { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id", TypeName = "int")] public int Id { get; set; } [Key] [DisplayName("Auction Period")] [Column("AuctionId", TypeName = "int")] public int? AuctionId { get; set; } [ForeignKey("AuctionId")] public Auction Auction { get; set; } [Key] [DisplayName("User")] [Column("UserId", TypeName = "nvarchar(450)")] public string UserId { get; set; } [ForeignKey("UserId")] public ApplicationUser User { get; set; } [Required(ErrorMessage = "- Price can not be empty")] [Column("BidPrice", TypeName = "int")] public int? BidPrice { get; set; } [Column("Day", TypeName = "datetime")] public DateTime? Day { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using Sirenix.OdinInspector; using UnityEngine; public class UnitAttributes : MonoBehaviour { public bool DestroyOnDeath = false; public UpgradableAttribute Health; // Start is called before the first frame update private void OnTriggerEnter(Collider other) { if (other.CompareTag("Weapon")) { Debug.Log($"{gameObject.name} got Hit"); if (this.Health.Reduce(5)) { //Dead Debug.Log($"{gameObject.name} is dead"); if (this.DestroyOnDeath) { Destroy(gameObject); } } } } } [System.Serializable] public struct UpgradableAttribute { [SerializeField,OnValueChanged("Initialize"),DisableInPlayMode] private int _MaxValue; /// <summary> /// The maximum value this attribute can be. /// </summary> public int MaxValue => this._MaxValue; [SerializeField,ReadOnly] private int _CurrentValue; /// <summary> /// The amount the attribute current holds. /// </summary> public int CurrentValue => this._CurrentValue; public float Percentage => CurrentValue / (float)MaxValue; public UpgradableAttribute(int maxValue, int currentValue) { this._MaxValue = maxValue; this._CurrentValue = currentValue; } private void Initialize() { this._CurrentValue = this._MaxValue; } /// <summary> /// Subtract the amount given by the current value. The current value never becomes negative. /// </summary> /// <param name="amount">How much is to reduce from the current value.</param> /// <returns>If the current value reduced to zero.</returns> public bool Reduce(int amount) { int correctedAmount = Mathf.Clamp(amount, 0, this._CurrentValue); this._CurrentValue -= correctedAmount; return this._CurrentValue == 0; } public void Increase(int amount) { int correctAmount = Mathf.Clamp(amount, 0, CurrentValue - MaxValue); this._CurrentValue = correctAmount; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.Common; namespace EasyDev.BL.Services { public class ServiceValidationException :ExceptionBase, IException { public ServiceValidationException(string msg) : base(msg) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Geometry { /// <summary> /// Given 2 rectangles, check whether they intersect or not /// </summary> public class RectangleIntersection { /// <summary> /// We need to find whether rectangles a and b are intersecting /// </summary> /// <param name="a">one of the rectangles</param> /// <param name="b">one of the rectangles</param> /// <returns></returns> public static bool IsIntersecting(Rectangle a, Rectangle b) { return (a.TopLeft.Xcoordinate < b.BottomRight.Xcoordinate) && (b.TopLeft.Xcoordinate < a.BottomRight.Xcoordinate) && (a.TopLeft.Ycoordinate > b.BottomRight.Ycoordinate) && (a.BottomRight.Ycoordinate < b.TopLeft.Ycoordinate); } public static void TestRectangleIntersection() { Rectangle rect1 = new Rectangle(new Point(1, 5), new Point(7, 2)); Rectangle rect2 = new Rectangle(new Point(5, 3), new Point(10, 1)); Console.WriteLine("The intersection is : {0}", IsIntersecting(rect1, rect2)); Console.WriteLine("The intersection is : {0}", IsIntersecting(rect2, rect1)); } } public class Rectangle { public Point TopLeft { get; set; } public Point BottomRight { get; set; } public Rectangle(Point topLeft, Point bottomRight) { TopLeft = topLeft; BottomRight = bottomRight; } } }
using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; namespace Thesis { public sealed class MaterialManager { private static readonly MaterialManager _instance = new MaterialManager(); public static MaterialManager Instance { get { return _instance; } } private static bool _isInitialized; private Dictionary<string, Material> _materials; private Dictionary<string, List<Material>> _collections; private MaterialManager () { _materials = new Dictionary<string,Material>(); _collections = new Dictionary<string,List<Material>>(); _isInitialized = false; } public void Init () { if (!_isInitialized) { CreateDoorShutter(); CreateWindowBalcony(); CreateRoofRelated(); CreateWalls(); CreateCity(); Material mat; foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_comp_decor")) { mat = new Material(Shader.Find("Transparent/Cutout/Diffuse")); mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_comp_decor", mat); } foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_comp_decor_simple")) { mat = new Material(Shader.Find("Diffuse")); mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_comp_decor_simple", mat); } mat = new Material(Shader.Find("Diffuse")); mat.name = "ComponentFrame"; mat.color = new Color32(186, 189, 189, 255); Add(mat.name, mat); // lines mat = new Material(Shader.Find("VertexLit")); mat.name = "line_block"; mat.SetColor("_Color", Color.green); mat.SetColor("_SpecColor", Color.green); mat.SetColor("_Emission", Color.green); Add(mat.name, mat); mat = new Material(Shader.Find("VertexLit")); mat.name = "line_lot"; mat.SetColor("_Color", Color.cyan); mat.SetColor("_SpecColor", Color.cyan); mat.SetColor("_Emission", Color.cyan); Add(mat.name, mat); mat = new Material(Shader.Find("VertexLit")); mat.name = "line_sidewalk"; mat.SetColor("_Color", Color.red); mat.SetColor("_SpecColor", Color.red); mat.SetColor("_Emission", Color.red); Add(mat.name, mat); //Testing(); _isInitialized = true; } } public void Unload () { foreach (Material m in _materials.Values) Object.DestroyImmediate(m, true); _materials.Clear(); foreach (List<Material> l in _collections.Values) { foreach (Material m in l) Object.DestroyImmediate(m, true); l.Clear(); } _collections.Clear(); _isInitialized = false; } public void Add (string name, Material material) { if (!_materials.ContainsKey(name)) { material.name = name; _materials.Add(name, material); } } public void AddToCollection (string name, Material material) { if (_collections.ContainsKey(name)) { if (!_collections[name].Contains(material)) { material.name = name; _collections[name].Add(material); } } else { var list = new List<Material>(); material.name = name; list.Add(material); _collections.Add(name, list); } } public void Add (string name, string shaderName, ProceduralTexture texture) { if (!_materials.ContainsKey(name)) { var mat = new Material(Shader.Find(shaderName)); mat.name = name; mat.mainTexture = texture.content; _materials.Add(mat.name, mat); } } public void AddToCollection (string collectionName, string shaderName, ProceduralTexture texture) { var mat = new Material(Shader.Find(shaderName)); mat.mainTexture = texture.content; if (_collections.ContainsKey(collectionName)) { mat.name = collectionName + "_" + (_collections[collectionName].Count + 1).ToString(); _collections[collectionName].Add(mat); } else { mat.name = collectionName + "_1"; var list = new List<Material>(); list.Add(mat); _collections.Add(collectionName, list); } } public void Set (string name, Material material) { if (_materials.ContainsKey(name)) _materials[name] = material; } public Material FindByTextureName (string name) { foreach (Material m in _materials.Values) { if (m.mainTexture != null) if (m.mainTexture.name == name) return m; } foreach (List<Material> l in _collections.Values) foreach (Material m in l) { if (m.mainTexture != null) if (m.mainTexture.name == name) return m; } return null; } public Material Get (string name) { return _materials.ContainsKey(name) ? _materials[name] : null; } public List<Material> GetCollection (string name) { return _collections.ContainsKey(name) ? _collections[name] : null; } private void CreateDoorShutter () { foreach (Color color in ColorManager.Instance.GetCollection("col_components")) { foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_door")) { Material mat = new Material(Shader.Find("Diffuse")); mat.color = color; mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_door", mat); } foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_shutter")) { Material mat = new Material(Shader.Find("Diffuse")); mat.color = color; mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_shutter", mat); } } } private void CreateWindowBalcony () { foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_window")) MaterialManager.Instance.AddToCollection("mat_window", "Diffuse", tex); foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_balcony_door")) MaterialManager.Instance.AddToCollection("mat_balcony_door", "Diffuse", tex); MaterialManager.Instance.Add("mat_balcony_rail", "Transparent/Cutout/Diffuse", TextureManager.Instance.Get("tex_balcony")); } private void CreateRoofRelated() { if (TextureManager.Instance.GetCollection("tex_roof") != null) foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_roof")) { Material mat = new Material(Shader.Find("Diffuse")); mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_roof", mat); } if (TextureManager.Instance.GetCollection("tex_roof_base") != null) foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_roof_base")) { Material mat = new Material(Shader.Find("Diffuse")); mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_roof_base", mat); } if (TextureManager.Instance.GetCollection("tex_roof_decor") != null) foreach (ProceduralTexture tex in TextureManager.Instance.GetCollection("tex_roof_decor")) { Material mat = new Material(Shader.Find("Transparent/Cutout/Diffuse")); mat.mainTexture = tex.content; MaterialManager.Instance.AddToCollection("mat_roof_decor", mat); } } private void CreateWalls () { Material mat; foreach (Color color in ColorManager.Instance.GetCollection("col_walls")) { mat = new Material(Shader.Find("Diffuse")); mat.color = color; AddToCollection("mat_walls", mat); } } private void CreateCity () { Material mat = new Material(Shader.Find("Diffuse")); mat.color = new Color32(55, 55, 55, 255); _instance.Add("mat_road", mat); mat = new Material(Shader.Find("Diffuse")); mat.color = Color.gray; _instance.Add("mat_sidewalk", mat); mat = new Material(Shader.Find("Diffuse")); mat.color = new Color32(0, 55, 0, 255); _instance.Add("mat_lot", mat); } private void Testing () { Material m = new Material(Shader.Find("Diffuse")); m.mainTexture = TextureManager.Instance.Get("tile3").content; MaterialManager.Instance.Add("mat_roof", m); Material n = new Material(Shader.Find("Diffuse")); n.mainTexture = TextureManager.Instance.Get("tex_roof_base").content; MaterialManager.Instance.Add("mat_roof_base", n); m = new Material(Shader.Find("Transparent/Cutout/Diffuse")); m.mainTexture = TextureManager.Instance.Get("decor").content; MaterialManager.Instance.Add("mat_decor", m); } } } // namespace Thesis
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OE.Service.TaskCore { public class TaskItemContent { public int TaskID { get; set; } public CCF.Task.TaskBase Task { get; set; } public AppDomain TaskDomain { get; set; } public DateTime? lastRunTime { get; set; } public string BaseDir { get; set; } public TaskItem TaskConfig { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shipwreck.TypeScriptModels.Declarations { public abstract class Signature { internal abstract void WriteSignature(TextWriter writer); } }
#region License /* * Copyright 2002-2010 the original author or authors. * * 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. */ #endregion using Erlang.NET; using Spring.Erlang.Support.Converter; namespace Spring.Erlang.Core { /// <summary> /// An erlang operations interface. /// </summary> /// <author>Mark Pollack</author> public interface IErlangOperations { /// <summary> /// Executes the specified action. /// </summary> /// <typeparam name="T">Type T.</typeparam> /// <param name="action">The action.</param> /// <returns>An object.</returns> /// <remarks></remarks> T Execute<T>(ConnectionCallbackDelegate<T> action); /// <summary> /// Executes the erlang RPC. /// </summary> /// <param name="module">The module.</param> /// <param name="function">The function.</param> /// <param name="args">The args.</param> /// <returns>An object.</returns> /// <remarks></remarks> OtpErlangObject ExecuteErlangRpc(string module, string function, OtpErlangList args); /// <summary> /// Executes the erlang RPC. /// </summary> /// <param name="module">The module.</param> /// <param name="function">The function.</param> /// <param name="args">The args.</param> /// <returns>An object.</returns> /// <remarks></remarks> OtpErlangObject ExecuteErlangRpc(string module, string function, params OtpErlangObject[] args); /// <summary> /// Executes the RPC. /// </summary> /// <param name="module">The module.</param> /// <param name="function">The function.</param> /// <param name="args">The args.</param> /// <returns>An object.</returns> /// <remarks></remarks> OtpErlangObject ExecuteRpc(string module, string function, params object[] args); /// <summary> /// Executes the and convert RPC. /// </summary> /// <param name="module">The module.</param> /// <param name="function">The function.</param> /// <param name="converterToUse">The converter to use.</param> /// <param name="args">The args.</param> /// <returns>An object.</returns> /// <remarks></remarks> object ExecuteAndConvertRpc(string module, string function, IErlangConverter converterToUse,params object[] args); /// <summary> /// Executes the and convert RPC. /// </summary> /// <param name="module">The module.</param> /// <param name="function">The function.</param> /// <param name="args">The args.</param> /// <returns>An object.</returns> /// <remarks></remarks> object ExecuteAndConvertRpc(string module, string function, params object[] args); } }
using ArcOthelloBG.Exceptions; using ArcOthelloBG.Logic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArcOthelloBG { /// <summary> /// Class that handle undo redo of a board state /// </summary> class UndoRedo { private Stack<OthelloState> actionDone; private Stack<OthelloState> actionToRedo; /// <summary> /// constructoe /// </summary> public UndoRedo() { this.actionDone = new Stack<OthelloState>(); this.actionToRedo = new Stack<OthelloState>(); } /// <summary> /// do an action and stack it /// </summary> /// <param name="state">state of the board to stack</param> public void DoAction(OthelloState state) { this.actionDone.Push(state); this.actionToRedo.Clear(); } /// <summary> /// Undo an action /// </summary> /// <returns>state of the board after action undon</returns> public OthelloState Undo(OthelloState stateUndone) { if(this.actionDone.Count > 0) { OthelloState state = this.actionDone.Pop(); this.actionToRedo.Push(stateUndone); return state; } else { throw new StackEmptyException("no action done"); } } /// <summary> /// Redo the first undone actions /// </summary> /// <returns>state of the board of the action</returns> public OthelloState Redo(OthelloState state) { if (this.actionToRedo.Count > 0) { OthelloState stateToRedo = this.actionToRedo.Pop(); this.actionDone.Push(state); return stateToRedo; } else { throw new StackEmptyException("no action to redo"); } } /// <summary> /// get the number of actions already done /// </summary> /// <returns>nb of actions</returns> public int GetNbUndoActions() { return this.actionDone.Count; } /// <summary> /// get the nb of actions undone /// </summary> /// <returns>nb of actions</returns> public int GetNbRedoActions() { return this.actionToRedo.Count; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Thingy.WebServerLite.Api { public interface IUser { ////string IpAddress { get; set; } ////string Password { get; set; } string[] Roles { get; } string UserId { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class KeyAmount : MonoBehaviour { public int Keys = 0; public Text Text; public DoorDetection hasKey; // Start is called before the first frame update void Start() { //Gets the text component Text = GetComponent<Text>(); } // Update is called once per frame void Update() { //Makes the text component display the amount of keys the player has Text.text = ("Keys: " + Keys); } //Adds a key whenever the AddKey method is invoked public void AddKey() { Keys += 1; } //This method is used when the player interacts with a locked door. If the player has a key, it will remove 1 key, and activate the method for the doors script public void LockedDoorCheck() { if (Keys >= 1) { hasKey.ActivateDoor(); Keys--; } } }
using BusinessLayer.Interfaces; using DALLayer.DataRepository; using DomainModels; using DomainModels.SharedModels; using System; using System.Collections.Generic; namespace BusinessLayer { public class CustomerBL: ICustomerBL { private readonly ICutomerDAL iuser; public CustomerBL(ICutomerDAL userRegister) { iuser = userRegister; } public List<Customers> GetCustomerDetails() { return iuser.RegisteredCustomer(); } public Object LoginUser(LoginModel customermodel) { ResponseBL response = new ResponseBL(); if (customermodel != null) { var user = iuser.CheckUser(customermodel); if (user != null) { response.Status = "success"; response.obj = user; return user; } else response.Status = "Invalid User"; } else response.Status = "Error"; return response; } public Customers Register(Customers data) { if(data != null) { iuser.AddCustomer(data); } return null; } public Customers CustomerById(int cd) { return iuser.GetCustomerById(cd); } public Customers Update(Customers updateData) { return iuser.UpdateData(updateData); } public ResponseBL DeleteUser(int id) { ResponseBL status = new ResponseBL(); iuser.DeleteCustomer(id); status.Status = "success"; return status; } public Customers CustomerByName(string uname) { return iuser.CutomerByNameDAl(uname); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Xml; using System.Xml.Serialization; using Breeze.AssetTypes; using Breeze.AssetTypes.XMLClass; using Breeze.Helpers; using Breeze.Screens; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Newtonsoft.Json; namespace Breeze.AssetTypes.DataBoundTypes { public class KeyedAsset : DataboundAsset { public void Update(KeyedAsset da, KeyedAsset asset) { //throw new NotImplementedException(); } public bool IsDirty { get; set; } } public class DataboundContainterAsset : DataboundAsset { public DataboundValue<List<DataboundAsset>> Children { get; set; } = new DataboundValue<List<DataboundAsset>>(new List<DataboundAsset>()); public void SetChildrenOriginToMyOrigin() { if (Children.Value != null) { foreach (var child in Children.Value) { child.ParentPosition = new FloatRectangle(this.ActualPosition.AdjustForMargin(Margin)); //child.Position.Value = new FloatRectangle(this.Position.Value.X,this.Position.Value.Y,child.Position.Value.Width,child.Position.Value.Height); } } } public void SetChildrenOriginToMyOrigin(FloatRectangle actualPosition) { if (Children.Value != null) { foreach (var child in Children.Value) { child.ParentPosition = actualPosition; //child.Position.Value = new FloatRectangle(this.Position.Value.X,this.Position.Value.Y,child.Position.Value.Width,child.Position.Value.Height); } } } } public class Binding { public DataboundAsset.DataboundValue Property { get; set; } public string BoundTo { get; set; } public BindType Direction { get; set; } } public class DataboundAssetWhereChildIsContentAsset : DataboundAsset { public virtual void LoadContent(string child) { throw new NotImplementedException(); } } public partial class DataboundAsset { public override string ToString() { return XName + ", Type:" + this.GetType().ToString() + ", ActualPosition:" + this.ActualPosition+", Position:"+this.Position.ToString() + ", ParentName:" + this.ParentAsset?.XName; } public class AssetAttribute : Attribute { public string XMLName; public AssetAttribute(string xmlName) { XMLName = xmlName; } } public bool IsHiddenOrParentHidden() { var isHidden = IsHidden.Value(); if (!isHidden && ParentAsset!=null) { isHidden = ParentAsset.IsHiddenOrParentHidden(); } return isHidden; } public DataboundValue<bool> IsHidden { get; set; } = new DataboundValue<bool>(); public string Key { get; set; } public int ZIndex { get; set; } = 0; public FloatRectangle? Clip { get; set; } = null; public Rectangle? ScissorRect { get; set; } public virtual void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null) { throw new NotImplementedException(); } public DataboundValue<string> XName { get; set; } = new DataboundValue<string>(); public DataboundValue<Thickness> Margin { get; set; } = new DataboundValue<Thickness>(); [XmlIgnore] public FloatRectangle? ParentPosition { get; set; } public DataboundValue<FloatRectangle> Position { get; set; } = new DataboundValue<FloatRectangle>(); [XmlIgnore] public FloatRectangle ActualPosition { get { if (ParentPosition == null) { return Position.Value(); } return Position.Value().ConstrainTo(ParentPosition.Value); } } [XmlIgnore] public Vector2 ActualSize { get; set; } = Vector2.Zero; public List<Binding> Bindings { get; set; } = new List<Binding>(); public List<KeyValuePair<string, object>?> DataBindings = new List<KeyValuePair<string, object>?>(); public void Bind<T>(DataboundAsset.DataboundValue<T> databoundValue, string bindingName) { if (DataBindings.Any(x => x != null && x.Value.Value == databoundValue)) { DataBindings.RemoveAll(x => x != null && x.Value.Value == databoundValue); } DataBindings.Add(new KeyValuePair<string, object>(bindingName, databoundValue)); } public void Bind(DataboundAsset.DataboundValue databoundValue, string bindingName) { if (DataBindings.Any(x => x != null && x.Value.Value == databoundValue)) { DataBindings.RemoveAll(x => x != null && x.Value.Value == databoundValue); } DataBindings.Add(new KeyValuePair<string, object>(bindingName, databoundValue)); } public bool Set<T>(ref T input, T newValue, [CallerMemberName] string callerMemberName = "") { if (!input.Equals(newValue)) { var db = DataBindings.FirstOrDefault(t => t != null && t.Value.Key == callerMemberName); if (db == null) { throw new Exception("Binding not found"); } DataboundValue<T> dbv = (DataboundValue<T>)db.Value.Value; dbv.Value = newValue; return true; } else { return false; } } public class DataboundEvent<T> { [XmlIgnore] public Action<T> Action { get; set; } private string _event; public string Event { get { return _event; } set { _event = value; } } public void Fire(T args) { Action?.Invoke(args); } } public abstract class DataboundValue { public DataboundAsset ParentAsset; public string BoundTo { get; set; } = null; public bool Invert { get; set; } = false; public BindType BindingDirection { get; set; } = BindType.OneWay; [XmlIgnore] public Guid Id = Guid.NewGuid(); [XmlIgnore] public Action<object> OnReverseBindGeneric; public void SetReverseBindActionAsObject(Action<object> action) { this.OnReverseBindGeneric = action; } public object ObjectValue { get; set; } } public void LoadFromXml(XmlAttributeCollection childNodeAttributes) { PropertyInfo[] props = this.GetType().GetAllProperties(); foreach (PropertyInfo propertyInfo in props) { AssetAttribute attr = propertyInfo.GetCustomAttribute<AssetAttribute>(); if (attr != null) { if (childNodeAttributes.GetNamedItem(attr.XMLName)?.Value != null) { string temp = childNodeAttributes.GetNamedItem(attr.XMLName)?.Value; if (temp != null) { DataboundValue temp2 = DataboundAssetExtensions.GetDBValue(temp, propertyInfo.PropertyType.GenericTypeArguments.First()); propertyInfo.SetValue(this, temp2); } } } else { string name = propertyInfo.Name; string temp = childNodeAttributes.GetNamedItem(name)?.Value; if (temp != null) { DataboundValue temp2 = DataboundAssetExtensions.GetDBValue(temp, propertyInfo.PropertyType.GenericTypeArguments.First()); propertyInfo.SetValue(this, temp2); } } } } public static DataboundAsset CreateFromXml(XmlAttributeCollection childNodeAttributes, Type type, DataboundAsset parentAsset, BaseScreen baseScreen) { DataboundAsset asset = (DataboundAsset)Activator.CreateInstance(type); var assetType = asset.GetType(); PropertyInfo[] tprops = assetType.GetProperties(); PropertyInfo[] props = tprops.Where(propertyInfo => propertyInfo.GetMethod.ReturnType.AssemblyQualifiedName.Contains("DataboundValue")).ToArray(); List<string> childNodeNames = new List<string>(); foreach (object childNodeAttribute in childNodeAttributes) { childNodeNames.Add(((XmlAttribute)childNodeAttribute).Name); } Dictionary<string,PropertyInfo> prps = new Dictionary<string, PropertyInfo>(); foreach (PropertyInfo propertyInfo in props) { AssetAttribute attr = propertyInfo.GetCustomAttribute<AssetAttribute>(); string name = propertyInfo.Name; if (attr != null) { name = attr.XMLName; } prps.Add(name, propertyInfo); } Breeze.VirtualizedDataContext embeddedDataContext = new VirtualizedDataContext(); foreach (string s in childNodeNames) { if (prps.ContainsKey(s)) { PropertyInfo p = prps[s]; string temp = childNodeAttributes.GetNamedItem(s)?.Value; if (temp != null) { DataboundValue temp3 = (DataboundValue)DataboundAssetExtensions.GetDBerValue(temp, p.PropertyType.GenericTypeArguments.First()); p.SetValue(asset, temp3); } } else { if (s.StartsWith("x_")) { string propName = s.Substring(2); string temp = childNodeAttributes.GetNamedItem(s)?.Value; string propType = temp.Split('|').First(); string value = temp.Split('|').Last(); Type deftype = Type.GetType(propType) ?? Type.GetType("System." + propType); if (temp != null) { DataboundValue temp3 = (DataboundValue)DataboundAssetExtensions.GetDBerValue(value, deftype); embeddedDataContext.Store.Add(propName, value); } } else { throw new Exception("Could not find prop: " + s); } } } if (embeddedDataContext.Store.Count > 0) { asset.VirtualizedDataContext = embeddedDataContext; asset.VirtualizedDataContext.Screen = baseScreen; } return asset; } } //public static class DataboundAssetExtensions //{ // public static void Bind<T>(this DataboundAsset asset, DataboundAsset.DataboundValue<T> databoundValue, string bindingName) // { // } //} }
using System; using System.Data.Entity.Validation; using System.Linq; using GringottsDatabase.Models; namespace GringottsDatabase { class Program { static void Main() { var dumbledore = new WizardDeposits() { FirstName = "Albus", LastName = "Dumbledore", Age = 150, MagicWandCreator = "Antioch Peverell", MagicWandSize = 15, DepositStartDate = new DateTime(2016, 10, 20), DepositExpirationDate = new DateTime(2020, 10, 20), DepositAmount = 20000.24m, DepositCharge = 0.2m, IsDepositExpired = false }; var context = new WizardDepositsContext(); try { //context.WizardDepositses.Add(dumbledore); context.WizardDepositses.Count(); context.SaveChanges(); } catch (DbEntityValidationException edb) { foreach (var eve in edb.EntityValidationErrors) { foreach (var eveValidationError in eve.ValidationErrors) { Console.WriteLine(eveValidationError.ErrorMessage); } } } } } }
using System; namespace ManaMist.Utility { public class Coordinate { public int x { get; set; } public int y { get; set; } public Coordinate(int x, int y) { this.x = x; this.y = y; } public override bool Equals(object obj) { Coordinate coordinate = obj as Coordinate; return coordinate.x == this.x && coordinate.y == this.y; } public override int GetHashCode() { return x ^ y; } public override string ToString() { return string.Format("({0} , {1})", this.x, this.y); } public int Distance(Coordinate coord) { return Math.Abs(this.x - coord.x) + Math.Abs(this.y - coord.y); } public bool IsNextTo(Coordinate coord) { return Distance(coord) == 1; } public bool IsDiagonal(Coordinate coord) { return Math.Abs(this.x - coord.x) == 1 && Math.Abs(this.y - coord.y) == 1; } public bool IsAdjacent(Coordinate coord) { return IsNextTo(coord) || IsDiagonal(coord); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace WebAPI.Migrations { public partial class settingAttributeDomainModel : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Name", table: "Customers", maxLength: 30, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "MobileNo", table: "Customers", maxLength: 10, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Email", table: "Customers", maxLength: 25, nullable: true, oldClrType: typeof(string), oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Name", table: "Customers", nullable: true, oldClrType: typeof(string), oldMaxLength: 30, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "MobileNo", table: "Customers", nullable: true, oldClrType: typeof(string), oldMaxLength: 10, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Email", table: "Customers", nullable: true, oldClrType: typeof(string), oldMaxLength: 25, oldNullable: true); } } }