text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arboles { class arboles { private Nodo Inicio; private Nodo Fin; private Nodo Raiz; private Nodo inicioPila; private Nodo finalPila; private Nodo num; public void agregarLista(Nodo A) { if (Inicio == null) { Inicio = A; } else agregar(A, Inicio); } private void agregar(Nodo A, Nodo final) { if (final.siguiente == null) { final.siguiente = A; A.Anterior = final; Fin = A; } else agregar(A, final.siguiente); } private void apilar(Nodo A) { if (inicioPila == null) inicioPila = A; else agregarAPila(A, inicioPila); } private void agregarAPila(Nodo A, Nodo final) { if (final.siguiente == null) { final.siguiente = A; A.Anterior = final; finalPila = A; } else agregarAPila(A, final.siguiente); } private string retirar() { string numm; numm = Convert.ToString(finalPila.resultado); finalPila = finalPila.Anterior; if (finalPila != null) { finalPila.siguiente = null; } return numm; } public void crearArbol() { Raiz = null; string tecl; Nodo arbolC = Inicio, cAnterior = null, cSiguiente = null; while (arbolC != null) { cSiguiente = arbolC.siguiente; tecl = Convert.ToString(arbolC.resultado); if (tecl == "*" ) { Raiz = arbolC; arbolC.Izquierda = arbolC.Anterior; arbolC.Derecha = arbolC.siguiente; eliminarNodos(arbolC, cAnterior, cSiguiente); } if (tecl == "/") { Raiz = arbolC; arbolC.Izquierda = arbolC.Anterior; arbolC.Derecha = arbolC.siguiente; eliminarNodos(arbolC, cAnterior, cSiguiente); } cAnterior = arbolC; arbolC = arbolC.siguiente; } arbolC = Inicio; cAnterior = null; cSiguiente = null; while (arbolC != null) { cSiguiente = arbolC.siguiente; tecl = Convert.ToString(arbolC.resultado); if (tecl == "+") { Raiz = arbolC; arbolC.Izquierda = arbolC.Anterior; arbolC.Derecha = arbolC.siguiente; eliminarNodos(arbolC, cAnterior, cSiguiente); } if (tecl == "-") { Raiz = arbolC; arbolC.Izquierda = arbolC.Anterior; arbolC.Derecha = arbolC.siguiente; eliminarNodos(arbolC, cAnterior, cSiguiente); } cAnterior = arbolC; arbolC = arbolC.siguiente; } Inicio = null; } private void eliminarNodos(Nodo arbolC, Nodo cAnterior, Nodo cSiguiente) { if (arbolC.Anterior != Inicio) { arbolC.Anterior = cAnterior.Anterior; cAnterior.Anterior.siguiente = arbolC; } else { Inicio = Inicio.siguiente; Inicio.Anterior = null; } if (arbolC.siguiente != Fin) { arbolC.siguiente = cSiguiente.siguiente; cSiguiente.siguiente.Anterior = arbolC; } else { Fin.Anterior.siguiente = null; Fin = Fin.Anterior; } } public string PostOrden() { if (Raiz == null) return ""; else return postOrder(Raiz); } private string postOrder(Nodo t) { string lista = ""; if (t.Izquierda != null) { lista+=postOrder(t.Izquierda); } if (t.Derecha != null) { lista += postOrder(t.Derecha); } lista += t.ToString(); return lista; } public string postOrdenNotacion() { Nodo arbolCreado = Inicio; int aux = 0,nu1,nu2; string res = "", operat,operat2; while (arbolCreado != null) { if (Char.IsNumber(Convert.ToChar(arbolCreado.resultado)) == true) { num = new Nodo (arbolCreado.resultado); apilar(num); } else { operat = arbolCreado.ToString(); nu1 = Convert.ToInt32(retirar()); nu2 = Convert.ToInt32(retirar()); switch (operat) { case "/": aux = nu2 / nu1; break; case "*": aux = nu2 * nu1; break; case "-": aux = nu2 - nu1; break; case "+": aux = nu2 + nu1; break; } operat2=Convert.ToString(aux); num = new Nodo(operat2); apilar(num); } arbolCreado = arbolCreado.siguiente; if (arbolCreado == null) res = Convert.ToString(retirar()); } inicioPila = null; finalPila = null; Inicio = null; return res; } public string PreOrden() { if (Raiz == null) return ""; else return PreOrder(Raiz); } private string PreOrder(Nodo t) { string listas = ""; listas += t.ToString(); if (t.Izquierda != null) { listas += PreOrder(t.Izquierda); } if (t.Derecha != null) { listas += PreOrder(t.Derecha); } return listas; } public string preOrdenNotacion() { Nodo arbolCreado = Fin; int aux = 0,nu1,nu2; string res = "",operat,operat2; while (arbolCreado != null) { if (Char.IsNumber(Convert.ToChar(arbolCreado.resultado)) == true) { num = new Nodo(arbolCreado.resultado); apilar(num); } else { operat = arbolCreado.ToString(); nu1 = Convert.ToInt32(retirar()); nu2 = Convert.ToInt32(retirar()); switch (operat) { case "/": aux = nu1 / nu2; break; case "*": aux = nu1 * nu2; break; case "-": aux = nu1 - nu2; break; case "+": aux = nu1 - nu2; break; } operat2 = Convert.ToString(aux); num = new Nodo(operat2); apilar(num); } arbolCreado = arbolCreado.Anterior; if (arbolCreado == null) { res = Convert.ToString(retirar()); } } inicioPila = null; finalPila = null; Inicio = null; return res; } public string imprimir() { string Lista = ""; Nodo datoc = inicioPila; while (datoc != null) { Lista += datoc.ToString(); datoc = datoc.siguiente; } return Lista; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Blatella.Common {//comentario public class Return<T> { #region properties /// <summary> /// /// </summary> public bool theresError { get; set; } /// <summary> /// /// </summary> public string message { get; set; } /// <summary> /// /// </summary> public Error error { get; set; } /// <summary> /// /// </summary> public T data { get; set; } #endregion #region constructors /// <summary> /// /// </summary> [DebuggerHidden] public Return() { InitializeValues(); } #endregion #region private methods [DebuggerHidden] private void InitializeValues() { theresError = false; message = string.Empty; error = new Error(); } #endregion } }
namespace Voronov.Nsudotnet.BuildingCompanyIS.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddValueTypeColumns : DbMigration { public override void Up() { AddColumn("bcis.BuildingAttributes", "ValueType", c => c.Int(nullable: false)); AddColumn("bcis.VehicleAttributes", "ValueType", c => c.Int(nullable: false)); CreateIndex("bcis.VehicleAttributeValues", "VehicleId"); AddForeignKey("bcis.VehicleAttributeValues", "VehicleId", "bcis.Vehicles", "Id"); } public override void Down() { DropForeignKey("bcis.VehicleAttributeValues", "VehicleId", "bcis.Vehicles"); DropIndex("bcis.VehicleAttributeValues", new[] { "VehicleId" }); DropColumn("bcis.VehicleAttributes", "ValueType"); DropColumn("bcis.BuildingAttributes", "ValueType"); } } }
using System; namespace BusinessRuleModels { public class VideoModel : RuleModel { } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows; using ADOX; namespace HZGZDL.YZFJKGZXFXY.Common { /// <summary> /// Access操作类 /// </summary> public class AccessDbSetHelper<T> where T:class,new() { //Database connection strings private static StringBuilder strCmd_Select = new StringBuilder(); private static StringBuilder strCmd_Insert = new StringBuilder(); private static StringBuilder strCmd_Update = new StringBuilder(); private static StringBuilder strCmd_Delete = new StringBuilder(); static string root_path = (System.AppDomain.CurrentDomain.BaseDirectory) + "DataBase\\"; static string mdb_path = root_path + "Fra.mdb"; private static readonly string strConnection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mdb_path; // Hashtable to store cached parameters private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); #region 创建数据库 和表 public bool CreateDataBase(T entity) { //TransFormer 参数初始化 Catalog catalog = new Catalog(); if (!Directory.Exists(root_path)) { Directory.CreateDirectory(root_path); } //数据库不存在则创建 if (!File.Exists(mdb_path)) { try { catalog.Create(strConnection); } catch (System.Exception ex) { MessageBox.Show("Access数据库初始化失败:" + ex.Message + "\r\n准备安装数据库组件:\r\n" + root_path + "Lib\r\n安装后请重启软件"); RunCmd2(""); System.Windows.Application.Current.Shutdown(0); System.Environment.Exit(0); System.Environment.Exit(0); } } //创建表格 try { //测试信息表格 CreateTable(entity, catalog); } //若异常 则表格已存在 catch (Exception ex) { MessageBox.Show("OleHelper行号58:" + ex.Message); return false; } return true; } void CreateTable(T entity, Catalog catalog) { ADODB.Connection cn = new ADODB.Connection(); cn.Open(strConnection, null, null, -1); catalog.ActiveConnection = cn; Table table = new Table(); var DI = ClassPropertyHelper.GetPropertyNameAndValue<T>(entity); var DIT = ClassPropertyHelper.GetPropertyNameAndType<T>(entity); table.Name = ClassPropertyHelper.GetClassName<T>(entity); for (int i = 0; i < DI.Count; i++) { if (DI.ElementAt(i).Key == "ID") { ADOX.Column column = new ADOX.Column(); column.ParentCatalog = catalog; column.Name = "ID"; column.Type = DataTypeEnum.adInteger; column.DefinedSize = 32; column.Properties["AutoIncrement"].Value = true; table.Columns.Append(column, DataTypeEnum.adInteger, 32); table.Keys.Append("PrimaryKey", ADOX.KeyTypeEnum.adKeyPrimary, "ID", "", ""); } else { table.Columns.Append(DI.ElementAt(i).Key, ConverType(DIT.ElementAt(i).Value), 64); } } try { catalog.Tables.Append(table); } catch (Exception ex) { //MessageBox.Show("OleHelper行号92:" + ex.Message); } finally { cn.Close(); } } #endregion #region 通用的实体增删查改 #region 拼接CMD字符串 //插入命令创建 string Create_CMD_Insert(T entity) { strCmd_Insert.Clear(); strCmd_Insert.Append("insert into [" + ClassPropertyHelper.GetClassName<T>(entity) + "](["); var DI = ClassPropertyHelper.GetPropertyNameAndValue<T>(entity); for (int i = 0; i < DI.Count; i++) { if (DI.ElementAt(i).Key == "ID") { continue; } if (i == DI.Count - 1) { strCmd_Insert.Append(DI.ElementAt(i).Key + "])"); break; } strCmd_Insert.Append(DI.ElementAt(i).Key + "],["); } strCmd_Insert.Append(" values("); for (int i = 0; i < DI.Count; i++) { if (DI.ElementAt(i).Key == "ID") { continue; } if (i == DI.Count - 1) { strCmd_Insert.Append("@"+ DI.ElementAt(i).Key + ")"); break; } strCmd_Insert.Append("@" + DI.ElementAt(i).Key + ","); } return strCmd_Insert.ToString(); } //Update命令创建 string Create_CMD_Update(T entity,int Id) { strCmd_Update.Clear(); strCmd_Update.Append("update [" + ClassPropertyHelper.GetClassName<T>(entity) + "] set "); var DI = ClassPropertyHelper.GetPropertyNameAndValue<T>(entity); for (int j = 0; j < DI.Count; j++) { if (DI.ElementAt(j).Key == "ID") { continue; } if (j == DI.Count - 1) { strCmd_Update.Append("["+DI.ElementAt(j).Key + "]=@" + DI.ElementAt(j).Key + ""); break; } strCmd_Update.Append("[" + DI.ElementAt(j).Key + "]=@" + DI.ElementAt(j).Key + ", "); } strCmd_Update.Append(" where [ID]=@ID"); return strCmd_Update.ToString(); } //Delete删除命令创建 string Create_CMD_Delete(T entity ,int Id) { strCmd_Delete.Clear(); strCmd_Delete.Append("delete from [" + ClassPropertyHelper.GetClassName<T>(entity)); strCmd_Delete.Append("] where ID="+Id); return strCmd_Delete.ToString(); } #endregion #region 类型转换 OleDbType ConverOleType(string SystemType) { switch (SystemType) { case "Int32": return OleDbType.Integer; case "String": return OleDbType.LongVarWChar; case "Double": return OleDbType.Double; case "DateTime": return OleDbType.Date; case "Boolean": return OleDbType.Boolean; default: return OleDbType.LongVarWChar; } } DataTypeEnum ConverType(string SystemType) { switch (SystemType) { case "Int32": return DataTypeEnum.adInteger; case "String": return DataTypeEnum.adLongVarWChar; case "Double": return DataTypeEnum.adDouble; case "DateTime": return DataTypeEnum.adDate; case "Boolean": return DataTypeEnum.adBoolean; default: return DataTypeEnum.adLongVarWChar; } } #endregion #region 创建Parmeters OleDbParameter[] CreateParameters(T entity) { var DI = ClassPropertyHelper.GetPropertyNameAndValue<T>(entity); var DIT = ClassPropertyHelper.GetPropertyNameAndType<T>(entity); OleDbParameter[] parameters = new OleDbParameter[DI.Count-1]; for (int i = 0; i < DI.Count-1; i++) { OleDbParameter para = new OleDbParameter(); para.OleDbType = ConverOleType(DIT.ElementAt(i+1).Value); para.ParameterName = DI.ElementAt(i+1).Key; para.Value = StingToSysType(DIT.ElementAt(i+1).Value,DI.ElementAt(i+1).Value); parameters[i] = para; } return parameters; } object StingToSysType(string type, string value) { switch (type) { case "Int32": return int.Parse(value); case "String": return value; case "Double": return double.Parse(value); case "DateTime": return DateTime.Parse(value); case "Boolean": return Boolean.Parse(value); default: return value; } } #endregion #region 插入 public void Insert(T entity) { ExecuteNonQuery(Create_CMD_Insert(entity),CreateParameters(entity)); } #endregion #region 查询数据 重载 public T Select(Func<T, bool> whereLambda) { var list = SelectAll(); var entity = list.Where<T>(whereLambda).Select(T=>T); return entity.FirstOrDefault(); } public List<T> SelectList(Func<T, bool> whereLambda) { var list = SelectAll(); var entity = list.Where<T>(whereLambda).Select(T => T); return entity.ToList<T>(); } /// <summary> /// 查询变压器参数 /// </summary> /// <param name="Filed_Name"></param> /// <param name="Filed_Value"></param> /// <returns></returns> public List<T> SelectAll() { strCmd_Select.Clear(); T entity = new T(); strCmd_Select.Append("select * from [" + ClassPropertyHelper.GetClassName<T>(entity) + " ] "); return PutAllVal(entity, ExecuteDataSet(strCmd_Select.ToString())); } #endregion #region 修改数据 public void Update(T entity,int Id) { try { var DI = ClassPropertyHelper.GetPropertyNameAndValue<T>(entity); var DIT = ClassPropertyHelper.GetPropertyNameAndType<T>(entity); OleDbParameter[] parameters = new OleDbParameter[DI.Count]; var temp = CreateParameters(entity); for(int i=0;i<DI.Count-1;i++) { parameters[i]=temp[i]; } OleDbParameter para = new OleDbParameter(); para.OleDbType = OleDbType.Integer; para.ParameterName ="ID"; para.Value = Id; parameters[DI.Count-1] = para; ExecuteNonQuery(Create_CMD_Update(entity, Id), parameters); } catch (Exception error) { MessageBox.Show(error.Message); } } #endregion #region 删除数据 public void Delete(T entity,int Id) { try { ExecuteNonQuery(Create_CMD_Delete(entity,Id)); } catch (Exception error) { MessageBox.Show(error.Message); } } #endregion #region DataSetToModel List<T> PutAllVal(T entity, DataSet ds) { List<T> lists = new List<T>(); if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { lists.Add(PutVal(new T(), row)); } } return lists; } T PutVal(T entity, DataRow row){ //初始化 如果为null if (entity == null) { entity = new T(); } //得到类型 Type type = typeof(T); //取得属性集合 PropertyInfo[] pi = type.GetProperties(); foreach (PropertyInfo item in pi) { //给属性赋值 if (row[item.Name] != null && row[item.Name] != DBNull.Value) { if (item.PropertyType == typeof(System.Nullable<System.DateTime>)) { item.SetValue(entity, Convert.ToDateTime(row[item.Name].ToString()), null); } else { item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null); } } } return entity; } #endregion #endregion #region shell安装Access环境 static bool RunCmd2(string cmdStr) { Process proc = null; try { proc = new Process(); proc.StartInfo.WorkingDirectory = root_path + "Libs"; proc.StartInfo.FileName = "AccessDatabaseEngine.exe"; //proc.StartInfo.Arguments = string.Format("10");//this is argument // proc.StartInfo.CreateNoWindow = true; proc.Start(); // proc.StandardInput.AutoFlush = true; proc.WaitForExit(); proc.Close(); return true; } catch (Exception ex) { return false; } } #endregion #region ExecuteNonQuery /**/ /// <summary> /// Execute a OleDbCommand (that returns no resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OleDbParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OleDbConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-OleDb command</param> /// <param name="commandParameters">an array of OleDbParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection conn = new OleDbConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /**/ /// <summary> /// 使用默认连接 /// </summary> /// <param name="cmdType">命令文本类型</param> /// <param name="cmdText">命令文本</param> /// <param name="commandParameters">参数集</param> /// <returns>int</returns> public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection conn = new OleDbConnection(strConnection)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /**/ /// <summary> /// 使用默认连接,CommandType默认为StoredProcedure /// </summary> /// <param name="cmdText">存储过程名</param> /// <param name="commandParameters">参数集</param> /// <returns>int</returns> private static int ExecuteNonQuery(string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection conn = new OleDbConnection(strConnection)) { PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /**/ /// <summary> /// Execute a OleDbCommand (that returns no resultset) against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OleDbParameter("@prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-OleDb command</param> /// <param name="commandParameters">an array of OleDbParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OleDbConnection connection, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /**/ /// <summary> /// Execute a OleDbCommand (that returns no resultset) using an existing OleDb Transaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OleDbParameter("@prodid", 24)); /// </remarks> /// <param name="trans">an existing OleDb transaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-OleDb command</param> /// <param name="commandParameters">an array of OleDbParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OleDbTransaction trans, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } public static int ExecuteNonQuery(string cmdText) { using (OleDbConnection conn = new OleDbConnection(strConnection)) { OleDbCommand cmd = new OleDbCommand(); cmd.CommandText = cmdText; cmd.CommandType = CommandType.Text; if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; return cmd.ExecuteNonQuery(); } } /**/ /// <summary> /// Execute a OleDbCommand that returns a resultset against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// OleDbDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new OleDbParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OleDbConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-OleDb command</param> /// <param name="commandParameters">an array of OleDbParamters used to execute the command</param> /// <returns>A OleDbDataReader containing the results</returns> #endregion #region ExecuteReader public static OleDbDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); OleDbConnection conn = new OleDbConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } /**/ /// <summary> /// 使用默认连接 /// </summary> /// <param name="cmdType">命令文本类型</param> /// <param name="cmdText">命令文本</param> /// <param name="commandParameters">参数集</param> /// <returns>OleDbDataReader</returns> public static OleDbDataReader ExecuteReader(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); OleDbConnection conn = new OleDbConnection(strConnection); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } /**/ /// <summary> /// 使用默认连接,CommandType默认为StoredProcedure /// </summary> /// <param name="cmdText">存储过程名</param> /// <param name="commandParameters">参数集</param> /// <returns>OleDbDataReader</returns> public static OleDbDataReader ExecuteReader(string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); OleDbConnection conn = new OleDbConnection(strConnection); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, CommandType.StoredProcedure, cmdText, commandParameters); OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } #endregion #region ExecuteScalar /**/ /// <summary> /// Execute a OleDbCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new OleDbParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OleDbConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-OleDb command</param> /// <param name="commandParameters">an array of OleDbParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection connection = new OleDbConnection(connectionString)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /**/ /// <summary> /// 使用定义好的连接字符串 /// </summary> /// <param name="cmdType">命令文本类型</param> /// <param name="cmdText">命令文本</param> /// <param name="commandParameters">参数集</param> /// <returns>object</returns> public static object ExecuteScalar(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection connection = new OleDbConnection(strConnection)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /**/ /// <summary> /// 使用定义好的连接字符串,CommandType默认为StoredProcedure /// </summary> /// <param name="cmdText">存储过程名</param> /// <param name="commandParameters">参数集</param> /// <returns>object</returns> public static object ExecuteScalar(string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection connection = new OleDbConnection(strConnection)) { PrepareCommand(cmd, connection, null, CommandType.StoredProcedure, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /**/ /// <summary> /// Execute a OleDbCommand that returns the first column of the first record against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new OleDbParameter("@prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-OleDb command</param> /// <param name="commandParameters">an array of OleDbParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(OleDbConnection connection, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters) { OleDbCommand cmd = new OleDbCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } #endregion #region ExecuteDataSet /**/ /// <summary> /// 返加dataset /// </summary> /// <param name="connectionString">连接字符串</param> /// <param name="cmdType">命令类型,如StoredProcedure,Text</param> /// <param name="cmdText">the stored procedure name or T-OleDb command</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText) { OleDbConnection OleDbDataConn = new OleDbConnection(connectionString); OleDbCommand OleDbComm = new OleDbCommand(cmdText, OleDbDataConn); OleDbComm.CommandType = cmdType; OleDbDataAdapter OleDbDA = new OleDbDataAdapter(OleDbComm); DataSet DS = new DataSet(); OleDbDA.Fill(DS); return DS; } /**/ /// <summary> /// 使用定义好的连接字符串 /// </summary> /// <param name="cmdType">命令文本类型</param> /// <param name="cmdText">命令文本</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText) { OleDbConnection OleDbDataConn = new OleDbConnection(strConnection); OleDbCommand OleDbComm = new OleDbCommand(cmdText, OleDbDataConn); OleDbComm.CommandType = cmdType; OleDbDataAdapter OleDbDA = new OleDbDataAdapter(OleDbComm); DataSet DS = new DataSet(); OleDbDA.Fill(DS); return DS; } /**/ /// <summary> /// 使用定义好的连接字符串,CommandType默认为StoredProcedure /// </summary> /// <param name="cmdText">存储过程名</param> /// <returns>object</returns> public static DataSet ExecuteDataSet(string cmdText) { OleDbConnection OleDbDataConn = new OleDbConnection(strConnection); OleDbCommand OleDbComm = new OleDbCommand(cmdText, OleDbDataConn); OleDbComm.CommandType = CommandType.Text; OleDbDataAdapter OleDbDA = new OleDbDataAdapter(OleDbComm); DataSet DS = new DataSet(); OleDbDA.Fill(DS); return DS; } /**/ /// <summary> /// 返加dataset /// </summary> /// <param name="connectionString">连接字符串</param> /// <param name="cmdType">命令类型,如StoredProcedure,Text</param> /// <param name="cmdText">the stored procedure name or T-OleDb command</param> /// <param name="OleDbparams">参数集</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] OleDbparams) { OleDbConnection OleDbDataConn = new OleDbConnection(connectionString); OleDbCommand OleDbComm = AddOleDbParas(OleDbparams, cmdText, cmdType, OleDbDataConn); OleDbDataAdapter OleDbDA = new OleDbDataAdapter(OleDbComm); DataSet DS = new DataSet(); OleDbDA.Fill(DS); return DS; } public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params OleDbParameter[] OleDbparams) { OleDbConnection OleDbDataConn = new OleDbConnection(strConnection); OleDbCommand OleDbComm = AddOleDbParas(OleDbparams, cmdText, cmdType, OleDbDataConn); OleDbDataAdapter OleDbDA = new OleDbDataAdapter(OleDbComm); DataSet DS = new DataSet(); OleDbDA.Fill(DS); return DS; } /**/ /// <summary> /// 使用定义好的连接字符串,CommandType默认为StoredProcedure /// </summary> /// <param name="cmdText">存储过程名</param> /// <param name="commandParameters">参数集</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(string cmdText, params OleDbParameter[] OleDbparams) { OleDbConnection OleDbDataConn = new OleDbConnection(strConnection); OleDbCommand OleDbComm = AddOleDbParas(OleDbparams, cmdText, CommandType.Text, OleDbDataConn); OleDbDataAdapter OleDbDA = new OleDbDataAdapter(OleDbComm); DataSet DS = new DataSet(); OleDbDA.Fill(DS); return DS; } #endregion #region CacheParameters /**/ /// <summary> /// add parameter array to the cache /// </summary> /// <param name="cacheKey">Key to the parameter cache</param> /// <param name="cmdParms">an array of OleDbParamters to be cached</param> public static void CacheParameters(string cacheKey, params OleDbParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } #endregion #region GetCachedParameters /**/ /// <summary> /// Retrieve cached parameters /// </summary> /// <param name="cacheKey">key used to lookup parameters</param> /// <returns>Cached OleDbParamters array</returns> public static OleDbParameter[] GetCachedParameters(string cacheKey) { OleDbParameter[] cachedParms = (OleDbParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; OleDbParameter[] clonedParms = new OleDbParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (OleDbParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } #endregion #region PrepareCommand /**/ /// <summary> /// Prepare a command for execution /// </summary> /// <param name="cmd">OleDbCommand object</param> /// <param name="conn">OleDbConnection object</param> /// <param name="trans">OleDbTransaction object</param> /// <param name="cmdType">Cmd type e.g. stored procedure or text</param> /// <param name="cmdText">Command text, e.g. Select * from Products</param> /// <param name="cmdParms">OleDbParameters to use in the command</param> private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, CommandType cmdType, string cmdText, OleDbParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (OleDbParameter parm in cmdParms) cmd.Parameters.Add(parm); } } #endregion #region AddOleDbParas /**/ /// <summary> /// 获得一个完整的Command /// </summary> /// <param name="OleDbParas">OleDb的参数数组</param> /// <param name="CommandText">命令文本</param> /// <param name="IsStoredProcedure">命令文本是否是存储过程</param> /// <param name="OleDbDataConn">数据连接</param> /// <returns></returns> private static OleDbCommand AddOleDbParas(OleDbParameter[] OleDbParas, string cmdText, CommandType cmdType, OleDbConnection OleDbDataConn) { OleDbCommand OleDbComm = new OleDbCommand(cmdText, OleDbDataConn); OleDbComm.CommandType = cmdType; if (OleDbParas != null) { foreach (OleDbParameter p in OleDbParas) { OleDbComm.Parameters.Add(p); } } return OleDbComm; } #endregion } }
using System; namespace OCP.User.Backend { /** * @since 14.0.0 */ public interface ICheckPasswordBackend { /** * @since 14.0.0 * * @param string uid The username * @param string password The password * @return string|bool The uid on success false on failure */ string checkPassword(string loginName, string password); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthbarController : MonoBehaviour { public RectTransform Bar; private float initialWidth; private void Start() { initialWidth = Bar.sizeDelta.x; } public void SetHealthbar(float current, float max ) { Bar.sizeDelta = new Vector2( (current / max) * initialWidth, Bar.sizeDelta.y); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { //classify a gameObject as a player }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MyMusicWebsite.Models; namespace MyMusicWebsite.Repositories { public class MusicDataRepo: IMusicDataRepo { private MyDbContext _context; public MusicDataRepo(MyDbContext context) { _context = context; } public async Task<List<Artist>> GetArtists() { var artists = await _context.Artists.ToListAsync(); return artists; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("DrawMorphedCardSpell")] public class DrawMorphedCardSpell : SuperSpell { public DrawMorphedCardSpell(IntPtr address) : this(address, "DrawMorphedCardSpell") { } public DrawMorphedCardSpell(IntPtr address, string className) : base(address, className) { } public bool AddPowerTargets() { return base.method_11<bool>("AddPowerTargets", Array.Empty<object>()); } public void BeginEffects() { base.method_8("BeginEffects", Array.Empty<object>()); } public void DoActionNow() { base.method_8("DoActionNow", Array.Empty<object>()); } public void FindOldAndNewCards() { base.method_8("FindOldAndNewCards", Array.Empty<object>()); } public void OnAction(SpellStateType prevStateType) { object[] objArray1 = new object[] { prevStateType }; base.method_8("OnAction", objArray1); } public void OnAllTasksComplete(PowerTaskList taskList, int startIndex, int count, object userData) { object[] objArray1 = new object[] { taskList, startIndex, count, userData }; base.method_8("OnAllTasksComplete", objArray1); } public void OnRevealTasksComplete(PowerTaskList taskList, int startIndex, int count, object userData) { object[] objArray1 = new object[] { taskList, startIndex, count, userData }; base.method_8("OnRevealTasksComplete", objArray1); } public Card m_newCard { get { return base.method_3<Card>("m_newCard"); } } public float m_NewCardHoldTime { get { return base.method_2<float>("m_NewCardHoldTime"); } } public Card m_oldCard { get { return base.method_3<Card>("m_oldCard"); } } public float m_OldCardHoldTime { get { return base.method_2<float>("m_OldCardHoldTime"); } } public int m_revealTaskIndex { get { return base.method_2<int>("m_revealTaskIndex"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public sealed class GWorld { public static GWorld Instance { get; } = new GWorld(); static WorldStates world; static ResourceQueue patients; static ResourceQueue cubicles; static ResourceQueue offices; static ResourceQueue toilets; static ResourceQueue puddles; /// <summary> /// string = ResourceType /// </summary> static Dictionary<string, ResourceQueue> resources = new Dictionary<string, ResourceQueue>(); static GWorld() { world = new WorldStates(); patients = new ResourceQueue("","", world); resources.Add(ResourceType.Patients, patients); cubicles = new ResourceQueue(ObjectTag.Cubicle, WorldStateName.FreeCubicle, world); resources.Add(ResourceType.Cubicles, cubicles); offices = new ResourceQueue(ObjectTag.Office, WorldStateName.FreeOffice, world); resources.Add(ResourceType.Offices, offices); toilets = new ResourceQueue(ObjectTag.Toilet, WorldStateName.FreeToilet, world); resources.Add(ResourceType.Toilets, toilets); puddles = new ResourceQueue(ObjectTag.Puddle, WorldStateName.FreePuddle, world); resources.Add(ResourceType.Puddles, puddles); Time.timeScale = 5; } public ResourceQueue GetQueue(string type) { return resources[type]; } private GWorld() { } public WorldStates GetWorld() { return world; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Extensions; public class Cutable : MonoBehaviour { public GameObject Part; public List<Sprite> LS; public Vector3 offsetpart; public ScoreCut sc = null; private int state = 0; private SpriteRenderer srperso; public delegate void Cuted(); public event Cuted action; void Start() { ScoreCut sctmp = GameObject.FindObjectOfType<ScoreCut>(); sc = gameObject.GetComponent<ScoreCut>() ?? gameObject.AddComponent<ScoreCut>(); if(sctmp != null) { sc.MaxScore = sctmp.MaxScore; sc.ScoreDecay = sctmp.ScoreDecay; sc.MinScore = sctmp.MinScore; } srperso = gameObject.GetComponent<SpriteRenderer>() ?? gameObject.AddComponent<SpriteRenderer>(); if(LS.Count > 0) srperso.sprite = LS[0]; } public void Cut() { if(state < LS.Count) { Vector2 r = Random.insideUnitCircle; Instantiate(Part,transform.position + offsetpart + (new Vector3(r.x,r.y,0))*0.2f,Quaternion.Euler(0,0,Random.Range (-30,30))); // transform.position += offsetself; state += 1; if(state == LS.Count) { Vector2 rr = Random.insideUnitCircle; Vector3 rean = new Vector3(0,0,Random.Range (-30,30)); Quaternion rqu = new Quaternion(); rqu.eulerAngles = rean; Instantiate(Part,transform.position + offsetpart + (new Vector3(rr.x,rr.y,0))*0.2f,rqu); srperso.sprite = null; Destroy(this.gameObject); action(); } else srperso.sprite = LS[state]; } this.DataLog("Cutting " + gameObject.name); sc.EndCut(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows; namespace FullContact__ { class FileInput { public ZipPostalCodeDbEntities ZipCodes { get; private set; } public BLHCustomerDbEntities BLHDb { get; private set; } public FileInput() { ZipCodes = new ZipPostalCodeDbEntities(); BLHDb = new BLHCustomerDbEntities(); } public void ReadZipCodes(string file) { using (StreamReader reader = new StreamReader(file)) { reader.ReadLine(); while (!reader.EndOfStream) { ZipCodeTable zip = new ZipCodeTable(); string line = reader.ReadLine(); string[] splitLine = line.Split(','); zip.ZipCode = splitLine[0].Substring(1, splitLine[0].Length - 2); zip.State = splitLine[3].Substring(1, splitLine[3].Length - 2); zip.City = splitLine[2].Substring(1, splitLine[2].Length - 2); ZipCodes.ZipCodeTables.AddObject(zip); } try { ZipCodes.SaveChanges(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Unable to save", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } } public void ReadCustomers(string path) { using (StreamReader reader = new StreamReader(path)) { while (!reader.EndOfStream) { BLHCustomer customer = CreateCustomerFromLine(reader.ReadLine()); BLHDb.BLHCustomers.AddObject(customer); } BLHDb.SaveChanges(); } } public void ReadCatalog(string path) { using (StreamReader readFile = new StreamReader(path)) { readFile.ReadLine(); while (!readFile.EndOfStream) { string line = readFile.ReadLine(); Catalog catalog = CreateCatalogFromLine(line); BLHDb.Catalogs.AddObject(catalog); } BLHDb.SaveChanges(); } } private Catalog CreateCatalogFromLine(string line) { string[] data = line.Split(','); decimal price; decimal.TryParse(data[4], out price); Catalog catalog = new Catalog(); catalog.ProductName = data[0]; catalog.Category = data[1]; catalog.ShortDescription = data[2]; catalog.FullDescription = data[3]; catalog.Price = price; return catalog; } private BLHCustomer CreateCustomerFromLine(string line) { BLHCustomer customer = new BLHCustomer(); string[] splitCustomer = line.Split(','); customer.FirstName = splitCustomer[0]; customer.LastName = splitCustomer[1]; customer.Address = splitCustomer[2]; customer.Apt = splitCustomer[3]; customer.City = splitCustomer[4]; customer.State = splitCustomer[5]; customer.Zip = splitCustomer[6]; customer.Phone = splitCustomer[7]; customer.Email = splitCustomer[8]; customer.AVS = splitCustomer[9]; customer.Birthday = splitCustomer[10]; return customer; } } }
using System.Collections.Generic; using UnityEditor; using UnityEditor.AnimatedValues; using UnityEngine; [CustomEditor(typeof(LocalizedText))] [CanEditMultipleObjects] public class LocalizedTextEditor : Editor { private Vector2 scrollValues; private AnimBool showValuesAutoComplete; private string zhString; private GUIStyle contentStyle; public void OnEnable() { showValuesAutoComplete = new AnimBool(true); showValuesAutoComplete.valueChanged.AddListener(Repaint); contentStyle = EditorStyles.miniButtonLeft; contentStyle.fontSize = 12; contentStyle.alignment = TextAnchor.MiddleLeft; } private void DrawValuesAutoComplete(SerializedProperty property, string stringValue) { Dictionary<string, string> localizedStrings = LocalizationImporter.GetLanguageValues(stringValue); if (localizedStrings.Count == 0) { localizedStrings = LocalizationImporter.GetLanguagesContains(stringValue); } showValuesAutoComplete.target = EditorGUILayout.Foldout(showValuesAutoComplete.target, "Auto-Complete"); if (EditorGUILayout.BeginFadeGroup(showValuesAutoComplete.faded)) { EditorGUI.indentLevel++; float height = EditorGUIUtility.singleLineHeight * (Mathf.Min(localizedStrings.Count, 6) + 1); this.scrollValues = EditorGUILayout.BeginScrollView(this.scrollValues, GUILayout.Height(height)); foreach (KeyValuePair<string, string> local in localizedStrings) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(local.Key); if (GUILayout.Button(local.Value, contentStyle)) { property.stringValue = local.Key; this.zhString = local.Value; GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); EditorGUI.indentLevel--; } EditorGUILayout.EndFadeGroup(); } public override void OnInspectorGUI() { EditorGUI.BeginChangeCheck(); serializedObject.Update(); SerializedProperty iterator = serializedObject.GetIterator(); LocalizedText text = target as LocalizedText; if (text != null) { if (this.zhString != text.GetText()) { this.zhString = text.GetText(); } text.SerializeZhText(this.zhString); } for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false) { if (iterator.name == "m_zhText") { EditorGUILayout.LabelField("zhText", iterator.stringValue, new GUILayoutOption[0]); } else if (iterator.name == "m_key") { EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]); string key = iterator.stringValue; string localizedString = LocalizationImporter.GetLanguages(key); if (string.IsNullOrEmpty(zhString)) { zhString = localizedString; } EditorGUILayout.LabelField("中文", localizedString, new GUILayoutOption[0]); if (!string.IsNullOrEmpty(zhString) && zhString != localizedString) { DrawValuesAutoComplete(iterator, zhString); } } } serializedObject.ApplyModifiedProperties(); if (EditorGUI.EndChangeCheck()) { if (text != null) { text.OnLocalize(); } } } }
using System; using System.Collections.Generic; namespace OzoMvc.Models { public partial class Oprema { public Oprema() { PosaoOprema = new HashSet<PosaoOprema>(); Transakcija = new HashSet<Transakcija>(); } public int InventarniBroj { get; set; } public string Naziv { get; set; } public double? KupovnaVrijednost { get; set; } public double? KnjigovodstvenaVrijednost { get; set; } public double VrijemeAmortizacije { get; set; } public int VrstaId { get; set; } public int ReferentniId { get; set; } public int SkladisteId { get; set; } public virtual ReferentniTip Referentni { get; set; } public virtual Skladište Skladiste { get; set; } public virtual VrstaOpreme Vrsta { get; set; } public virtual ICollection<PosaoOprema> PosaoOprema { get; set; } public virtual ICollection<Transakcija> Transakcija { get; set; } } }
using System; using Bindable.Linq.Helpers; using NUnit.Framework; namespace Bindable.Linq.Tests.Unit.Helpers { /// <summary> /// This class contains unit tests for the <see cref="T:StateScope" />. /// </summary> [TestFixture] public sealed class StateScopeTests { /// <summary> /// Tests that entering a scope multiple times puts it into the state. /// </summary> [Test] public void StateScopeEntranceTest() { var scope = new StateScope(); Assert.AreEqual(false, scope.IsWithin); using (scope.Enter()) { Assert.AreEqual(true, scope.IsWithin); using (scope.Enter()) { Assert.AreEqual(true, scope.IsWithin); } Assert.AreEqual(true, scope.IsWithin); } Assert.AreEqual(false, scope.IsWithin); } /// <summary> /// Tests that entering a scope multiple times raises events. /// </summary> [Test] public void StateScopeEntranceTriggersCallback() { var eventsRaised = 0; Action callback = () => eventsRaised++; var scope = new StateScope(callback); Assert.AreEqual(0, eventsRaised); using (scope.Enter()) { // Went from false to true - so it should have raised Assert.AreEqual(1, eventsRaised); using (scope.Enter()) { // Already in - no raise Assert.AreEqual(1, eventsRaised); } // Still in - no raise Assert.AreEqual(1, eventsRaised); } // Left - raise Assert.AreEqual(2, eventsRaised); } } }
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using HackathonDemo.Models; namespace HackathonDemo.Controllers { public class SiteHomeController : Controller { // GET: Product public ActionResult Index() { var products = SetupProducts(); return View(products); } public ActionResult GetReturnProducts() { var products = SetupProducts().Where(p => p.IsReturned); return View(products); } private static List<Product> SetupProducts() { var products = new List<Product> { new Product { ProductId = 12345, ProductTitle = "Knitted Swing Dress With Zip Neck", Image = "http://images.asos-media.com/products/asos-knitted-swing-dress-with-zip-neck/8011669-1-blue?$XXL$&amp;wid=513&amp;fit=constrain", Price = 6000, discountedprice = 6000, Colour = "Blue", Details = "Body: 53% Polyester, 21% Acrylic, 20% Nylon, 6% Wool.", LookAfterMe = "Machine Wash According To Instructions On Care Label", Size = new List<string> {"UK 8", "UK 6"}, IsReturned = true }, new Product { ProductId = 12346, ProductTitle = "Boohoo Tab Side Lace Maxi Dress", Image = "http://images.asos-media.com/products/boohoo-tab-side-lace-maxi-dress/8508300-1-peach?$XXL$&amp;wid=513&amp;fit=constrain", Price = 6050, discountedprice = 6050, Colour = "Peach", Details = "Outer: 97% Polyester, 3% Elastane, Inner: 95% Viscose, 5% Elastane.", LookAfterMe = "Machine Wash According To Instructions On Care Label", Size = new List<string> {"UK 8", "UK 12"} }, new Product { ProductId = 12347, ProductTitle = "Pimkie Floral Print Cami Dress", Image = "http://images.asos-media.com/products/pimkie-floral-print-cami-dress/8518510-1-bluepattern?$XXL$&amp;wid=513&amp;fit=constrain", Price = 7000, Colour = "Blue pattern", Details = "Main: 100% Viscose.", LookAfterMe = "Machine Wash According To Instructions On Care Label", Size = new List<string> {"UK 10", "UK 12"} } }; return products; } } }
using UnityEngine; public class MergeRoad : Road { public Road RoadA1, RoadA2, RoadB; private void Start() { Type = RoadType.Merge; } }
using Castle.DynamicProxy; using Core.CrossCuttingConcern.Caching; using Core.Utilities.Interceptors; using Core.Utilities.IOC; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.DependencyInjection; namespace Core.Aspects.Autofac.Caching { public class CacheAspect : MethodInterception { private int _duration; private ICacheManager _cacheManager; public CacheAspect(int duration = 60) { _duration = duration; _cacheManager = ServiceTool.ServiceProvider.GetService<ICacheManager>(); // neden direk constructure içerisined veremiyoruz ? Çünkü aspectleri katmanları dikine kesiyor. // CoreModule da tutuyoruz IOC sini. } public override void Intercept(IInvocation invocation) { //burası reflection. Key imizi üretmek için path ini belirliyorsun. Northwind.Business.IProductService.GetAll diyelim.. var methodName = string.Format($"{invocation.Method.ReflectedType.FullName}.{invocation.Method.Name}"); var arguments = invocation.Arguments.ToList(); // argument parametreler demek bunları listeye çevirir. var key = $"{methodName}({string.Join(",", arguments.Select(x => x?.ToString() ?? "<Null>"))})"; //string joinle virgül koyarak yan yana yazar. yoksa null basar. if (_cacheManager.IsAdd(key)) // IsAdd ile kontrol eder eğer cache de varsa returnvalue yani o değeri döndür neyi veritabanından çektiğimiz veriyi // cachmanager da get ile o veriyi getirir. yoksa proceed et sürdür. { invocation.ReturnValue = _cacheManager.Get(key); return; } invocation.Proceed(); _cacheManager.Add(key, invocation.ReturnValue, _duration); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Web { /// <summary> /// Provides extension methods for <c>IPublishedElement</c>. /// </summary> public static class PublishedElementExtensions { // lots of debates about accessing dependencies (IPublishedValueFallback) from extension methods, ranging // from "don't do it" i.e. if an extension method is relying on dependencies, a proper service should be // created instead, to discussing method injection vs service locator vs other subtleties, see for example // this post http://marisks.net/2016/12/19/dependency-injection-with-extension-methods/ // // point is, we do NOT want a service, we DO want to write model.Value<int>("alias", "fr-FR") and hit // fallback somehow - which pretty much rules out method injection, and basically anything but service // locator - bah, let's face it, it works // // besides, for tests, Current support setting a fallback without even a container // private static IPublishedValueFallback PublishedValueFallback => Current.PublishedValueFallback; #region IsComposedOf /// <summary> /// Gets a value indicating whether the content is of a content type composed of the given alias /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The content type alias.</param> /// <returns>A value indicating whether the content is of a content type composed of a content type identified by the alias.</returns> public static bool IsComposedOf(this IPublishedElement content, string alias) { return content.ContentType.CompositionAliases.Contains(alias); } #endregion #region HasProperty /// <summary> /// Gets a value indicating whether the content has a property identified by its alias. /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <returns>A value indicating whether the content has the property identified by the alias.</returns> /// <remarks>The content may have a property, and that property may not have a value.</remarks> public static bool HasProperty(this IPublishedElement content, string alias) { return content.ContentType.GetPropertyType(alias) != null; } #endregion #region HasValue /// <summary> /// Gets a value indicating whether the content has a value for a property identified by its alias. /// </summary> /// <remarks>Returns true if <c>GetProperty(alias)</c> is not <c>null</c> and <c>GetProperty(alias).HasValue</c> is <c>true</c>.</remarks> public static bool HasValue(this IPublishedElement content, string alias, string culture = null, string segment = null) { var prop = content.GetProperty(alias); return prop != null && prop.HasValue(culture, segment); } // fixme - .Value() refactoring - in progress // missing variations... /// <summary> /// Returns one of two strings depending on whether the content has a value for a property identified by its alias. /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="valueIfTrue">The value to return if the content has a value for the property.</param> /// <param name="valueIfFalse">The value to return if the content has no value for the property.</param> /// <returns>Either <paramref name="valueIfTrue"/> or <paramref name="valueIfFalse"/> depending on whether the content /// has a value for the property identified by the alias.</returns> public static IHtmlString IfValue(this IPublishedElement content, string alias, string valueIfTrue, string valueIfFalse = null) { return content.HasValue(alias) ? new HtmlString(valueIfTrue) : new HtmlString(valueIfFalse ?? string.Empty); } #endregion #region Value /// <summary> /// Gets the value of a content's property identified by its alias. /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The value of the content's property identified by the alias, if it exists, otherwise a default value.</returns> /// <remarks> /// <para>The value comes from <c>IPublishedProperty</c> field <c>Value</c> ie it is suitable for use when rendering content.</para> /// <para>If no property with the specified alias exists, or if the property has no value, returns <paramref name="defaultValue"/>.</para> /// <para>If eg a numeric property wants to default to 0 when value source is empty, this has to be done in the converter.</para> /// <para>The alias is case-insensitive.</para> /// </remarks> public static object Value(this IPublishedElement content, string alias, string culture = null, string segment = null, Fallback fallback = default, object defaultValue = default) { var property = content.GetProperty(alias); // if we have a property, and it has a value, return that value if (property != null && property.HasValue(culture, segment)) return property.GetValue(culture, segment); // else let fallback try to get a value if (PublishedValueFallback.TryGetValue(content, alias, culture, segment, fallback, defaultValue, out var value)) return value; // else... if we have a property, at least let the converter return its own // vision of 'no value' (could be an empty enumerable) - otherwise, default return property?.GetValue(culture, segment); } #endregion #region Value<T> /// <summary> /// Gets the value of a content's property identified by its alias, converted to a specified type. /// </summary> /// <typeparam name="T">The target property type.</typeparam> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The value of the content's property identified by the alias, converted to the specified type.</returns> /// <remarks> /// <para>The value comes from <c>IPublishedProperty</c> field <c>Value</c> ie it is suitable for use when rendering content.</para> /// <para>If no property with the specified alias exists, or if the property has no value, or if it could not be converted, returns <c>default(T)</c>.</para> /// <para>If eg a numeric property wants to default to 0 when value source is empty, this has to be done in the converter.</para> /// <para>The alias is case-insensitive.</para> /// </remarks> public static T Value<T>(this IPublishedElement content, string alias, string culture = null, string segment = null, Fallback fallback = default, T defaultValue = default) { var property = content.GetProperty(alias); // if we have a property, and it has a value, return that value if (property != null && property.HasValue(culture, segment)) return property.Value<T>(culture, segment); // else let fallback try to get a value if (PublishedValueFallback.TryGetValue(content, alias, culture, segment, fallback, defaultValue, out var value)) return value; // else... if we have a property, at least let the converter return its own // vision of 'no value' (could be an empty enumerable) - otherwise, default return property == null ? default : property.Value<T>(culture, segment); } #endregion #region Value or Umbraco.Field - WORK IN PROGRESS // fixme - .Value() refactoring - in progress // trying to reproduce Umbraco.Field so we can get rid of it // // what we want: // - alt aliases // - recursion // - default value // - before & after (if value) // // convertLineBreaks: should be an extension string.ConvertLineBreaks() // stripParagraphs: should be an extension string.StripParagraphs() // format: should use the standard .ToString(format) // // see UmbracoComponentRenderer.Field - which is ugly ;-( // recurse first, on each alias (that's how it's done in Field) // // there is no strongly typed recurse, etc => needs to be in ModelsBuilder? // that one can only happen in ModelsBuilder as that's where the attributes are defined // the attribute that carries the alias is in ModelsBuilder! //public static TValue Value<TModel, TValue>(this TModel content, Expression<Func<TModel, TValue>> propertySelector, ...) // where TModel : IPublishedElement //{ // PropertyInfo pi = GetPropertyFromExpression(propertySelector); // var attr = pi.GetCustomAttribute<ImplementPropertyAttribute>(); // var alias = attr.Alias; // return content.Value<TValue>(alias, ...) //} // recurse should be implemented via fallback // todo - that one should be refactored, missing culture and so many things public static IHtmlString Value<T>(this IPublishedElement content, string aliases, Func<T, string> format, string alt = "") { if (format == null) format = x => x.ToString(); var property = aliases.Split(',') .Where(x => string.IsNullOrWhiteSpace(x) == false) .Select(x => content.GetProperty(x.Trim())) .FirstOrDefault(x => x != null); return property != null ? new HtmlString(format(property.Value<T>())) : new HtmlString(alt); } #endregion #region ToIndexedArray public static IndexedArrayItem<TContent>[] ToIndexedArray<TContent>(this IEnumerable<TContent> source) where TContent : class, IPublishedElement { var set = source.Select((content, index) => new IndexedArrayItem<TContent>(content, index)).ToArray(); foreach (var setItem in set) setItem.TotalCount = set.Length; return set; } #endregion #region OfTypes // the .OfType<T>() filter is nice when there's only one type // this is to support filtering with multiple types public static IEnumerable<T> OfTypes<T>(this IEnumerable<T> contents, params string[] types) where T : IPublishedElement { types = types.Select(x => x.ToLowerInvariant()).ToArray(); return contents.Where(x => types.Contains(x.ContentType.Alias.ToLowerInvariant())); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 성적처리 { class Program { static void Main(string[] args) { for (int i = 1; i <= 3; i++) { String name; int kor; int eng; int mat; int total; float avg; Console.Write("이름 :"); name = Console.ReadLine(); Console.Write("국어 :"); kor = int.Parse(Console.ReadLine()); Console.Write("영어 :"); eng = int.Parse(Console.ReadLine()); Console.Write("수학 :"); mat = int.Parse(Console.ReadLine()); total = kor + eng + mat; /* 실수는 기본적으로 Double로 받아들여서 Float하고 연산시 경고가 나옵니다. */ avg = total / 3.0f; Console.WriteLine("{0} 님의 총점은 {1} 이고 평균은 {2} 입니다.", name, total, avg); } } } }
using UnityEngine; using UnityEngine.UI; using TMPro; namespace CanYouCount { public class GameOverScreen : BaseScreen { [Header("UI Binding")] [SerializeField] private TMP_Text _timeScoreText = null; [Header("Buttons")] [SerializeField] private Button _menuButton = null; [SerializeField] private Button _retryButton = null; /// <summary> /// Initializes the screen. /// </summary> /// <param name="appManager">App manager.</param> public override void InitializeScreen(ApplicationManager appManager) { base.InitializeScreen(appManager); SetupButtons(); } /// <summary> /// Shows the screen. /// </summary> public override void ShowScreen(bool isInstant = false) { base.ShowScreen(isInstant); _timeScoreText.text = string.Format(GameUIContent.TwoDecimalPoint, _applicationManager.Game.Timer); } private void SetupButtons() { _menuButton.onClick.RemoveAllListeners(); _retryButton.onClick.RemoveAllListeners(); _menuButton.onClick.AddListener(() => { _applicationManager.AudioManager.PlayUIButtonClick(); _applicationManager.ChangeState(AppStates.MainMenu); }); _retryButton.onClick.AddListener(() => { _applicationManager.AudioManager.PlayUIButtonClick(); _applicationManager.StartNewGame(); }); } } }
using Newtonsoft.Json; namespace MonoGame.Extended.Content.Pipeline.TextureAtlases { public class TexturePackerRegion { [JsonProperty("filename")] public string Filename { get; set; } [JsonProperty("frame")] public TexturePackerRectangle Frame { get; set; } [JsonProperty("rotated")] public bool IsRotated { get; set; } [JsonProperty("trimmed")] public bool IsTrimmed { get; set; } [JsonProperty("spriteSourceSize")] public TexturePackerRectangle SourceRectangle { get; set; } [JsonProperty("sourceSize")] public TexturePackerSize SourceSize { get; set; } [JsonProperty("pivot")] public TexturePackerPoint PivotPoint { get; set; } public override string ToString() { return string.Format("{0} {1}", Filename, Frame); } } }
using System; using System.Collections.Generic; using System.Text; namespace ImmedisHCM.Services.Core { public interface IIdentitySeeder : ISeederBase { } }
using Microsoft.EntityFrameworkCore; using Skaitykla.Domains; namespace Skaitykla.EF { public class BookContext : DbContext { public DbSet<Book> Books { get; set; } public DbSet<Author> Authors{ get; set; } public DbSet<LendingBook> Lendings { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server = localhost; Database = coreDB; Trusted_Connection = True;"); } //protected override void OnModelCreating(ModelBuilder modelBuilder) //{ // modelBuilder.Entity<Author>().HasMany(a=>a.WrittenBooks) // . // .OnDelete() //} } }
using Contoso.Forms.Configuration.DataForm; using Contoso.XPlatform.ViewModels.Validatables; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Contoso.XPlatform.Services { public interface IEntityStateUpdater { TModel GetUpdatedModel<TModel>(TModel? existingEntity, Dictionary<string, object?> existingAsDictionary, ObservableCollection<IValidatable> modifiedProperties, List<FormItemSettingsDescriptor> fieldSettings); } }
using System; namespace Reto_Semana_05_02 { class Program { static void Main(string[] args) { //https://youtu.be/2Nzl2WjEgjs double x = 0; Console.WriteLine("Ingrese el valor de x para Sin(x)"); x = int.Parse(Console.ReadLine()); Console.WriteLine("El resultado es: " + Sin(x)); } static double Sin(double x) { int n = 100; double total = 0; for (int i = 0; i < n; i++) { total += ((Math.Pow(-1, i)) / Factorial((2 * i) + 1)) * (Math.Pow(x, (2 * i) + 1)); } return total; } static double Factorial(double valor) { if (valor <= 1) return 1; return valor * Factorial(valor - 1); } } }
using UnityEngine; using System.Collections.Generic; using System; public class TrackRampScript : MonoBehaviour { private bool _moving = false; private Vector3 _localFinalSpot; private Vector3 _globalFinalSpot; private int _zBlocks; public int ZBlocks { set { _zBlocks = value; } } // Use this for initialization void Start() { //resetVisibility(); } // Update is called once per frame void Update() { if (_moving) { Vector3 Distance = this.transform.position - _globalFinalSpot; Vector3 NormalizedDistance = Distance; NormalizedDistance.Normalize(); this.transform.position -= (NormalizedDistance * 2); if (Distance.magnitude < 1) { _moving = false; this.transform.localPosition = _localFinalSpot; } } } //void OnCollisionEnter(Collision other) //{ // if (other.gameObject.name == "Sphere") // { // Renderer[] childsRend = this.gameObject.GetComponentsInChildren<Renderer>(); // foreach (Renderer rend in childsRend) // { // rend.enabled = false; // } // } //} public void OnBecameInvisible() { //if (!_moving) //{ // _moving = true; // // -- actual next position on track // float NextXPositionLocal = this.transform.localPosition.x; // float NextYPositionLocal = this.transform.localPosition.y; // float NextZPositionLocal = this.transform.localPosition.z + (_zBlocks * 0.7f); // //// -- falling 'animation' -- // float NextXPositionGlobal = this.transform.position.x; // float NextYPositionGlobal = this.transform.position.y; // float NextZPositionGlobal = this.transform.position.z + (_zBlocks * 0.7f); // //Final LOCAL position // _localFinalSpot = new Vector3(NextXPositionLocal, NextYPositionLocal, NextZPositionLocal); // //Final GLOBAL position // _globalFinalSpot = new Vector3(NextXPositionGlobal, NextYPositionGlobal, NextZPositionGlobal); // //set next position in the air // this.transform.position = new Vector3(NextXPositionGlobal + UnityEngine.Random.Range(-30, 30), NextYPositionGlobal + UnityEngine.Random.Range(-30, 30), NextZPositionGlobal); // //resetVisibility(); //} this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + (_zBlocks * 0.7f)); } private void resetVisibility() { Renderer[] childsRend = this.gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer rend in childsRend) { rend.enabled = true; } } }
using Kompas6API5; namespace KompasKeyboardPlugin { /// <summary> /// Класс, рисующий линии для эскиза клавиши СИ-БЕМОЛЬ (Bb). /// </summary> public class KeyCreatorBb : KeyCreatorBase { /// <summary> /// Метод, рисующий линии для эскиза клавиши СИ-БЕМОЛЬ (Bb). /// </summary> public override void Build() { Sketch.ksLineSeg(MarginLeft + 0.25, - 5.5, MarginLeft + 0.25, - 15.5, 1); Sketch.ksLineSeg(MarginLeft + 0.25, - 15.5, MarginLeft - 0.85, - 15.5, 1); Sketch.ksLineSeg(MarginLeft - 0.85, - 15.5, MarginLeft - 0.85, - 5.5, 1); Sketch.ksLineSeg(MarginLeft - 0.85, - 5.5, MarginLeft + 0.25, - 5.5, 1); } public KeyCreatorBb(ksDocument2D sketch, double marginLeft) : base(sketch, marginLeft) { } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("AdventureCompleteRewardData")] public class AdventureCompleteRewardData : RewardData { public AdventureCompleteRewardData(IntPtr address) : this(address, "AdventureCompleteRewardData") { } public AdventureCompleteRewardData(IntPtr address, string className) : base(address, className) { } public string GetGameObjectName() { return base.method_13("GetGameObjectName", Array.Empty<object>()); } public string ToString() { return base.method_13("ToString", Array.Empty<object>()); } public string BannerText { get { return base.method_13("get_BannerText", Array.Empty<object>()); } } public bool IsBadlyHurt { get { return base.method_11<bool>("get_IsBadlyHurt", Array.Empty<object>()); } } public string RewardObjectName { get { return base.method_13("get_RewardObjectName", Array.Empty<object>()); } } public static string s_DefaultRewardObject { get { return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "AdventureCompleteRewardData", "s_DefaultRewardObject"); } } } }
using System; using CoreGraphics; using Foundation; using UIKit; using StudyEspanol.Data; using StudyEspanol.Data.Models; using StudyEspanol.iOS; using StudyEspanol.UI.Cells; using StudyEspanol.UI.Screens; namespace StudyEspanol.UI.Views { public partial class TagAspect { #region Const Fields public const int FULL_SIZE = 60; public const int HALF_SIZE = 30; public const int EMPTY = 0; public const int FULL = 30; #endregion #region Fields private UITextField inputTextField; private UIButton addButton; private UICollectionView tagCollection; #endregion #region Initialization public TagAspect(WordScreen parent, CGRect frame) : base(parent, frame) { Initialization(parent); CreateSubViews(frame); } public TagAspect(SearchScreen parent, CGRect frame) : base(parent, frame) { Initialization(parent); CreateSubViews(frame); } private void CreateSubViews(CGRect frame) { inputTextField = new UITextField(new CGRect(0, 0, frame.Width - 50, 30)); inputTextField.Placeholder = Strings.tag; inputTextField.BackgroundColor = UIColor.White; addButton = new UIButton(new CGRect(inputTextField.Frame.Width, 0, 50, 30)); addButton.SetTitle(Strings.add, UIControlState.Normal); addButton.SetTitleColor(UIColor.Red, UIControlState.Normal); addButton.TouchUpInside += OnClick; tagCollection = new UICollectionView(new CGRect(0, addButton.Frame.Height, frame.Width, 0), new UIHorizontalTableViewLayout(50, 30, 1)); tagCollection.RegisterClassForCell(typeof(TagCell), TagCell.REUSE_ID); tagCollection.BackgroundColor = UIColor.White; TagListAdapter adapter = new TagListAdapter(Tags, true); adapter.FlowLayout.ItemClick += (sender, e) => { RemoveTag(e.Index); tagCollection.ReloadData(); CheckForListSize(); }; tagCollection.Source = adapter; tagCollection.Delegate = adapter.FlowLayout; AddSubviews(inputTextField, addButton, tagCollection); Frame = new CGRect(Frame.X, Frame.Y, Frame.Width, HALF_SIZE); parent.ChildDidLoad(); } #endregion #region Methods private void OnClick(object sender, EventArgs e) { if (sender == addButton) { AddTag(inputTextField.Text); } } private void CheckForListSize() { if (Tags.Count == 0 && Frame.Height != HALF_SIZE) { TagCollectionToggle(HALF_SIZE, EMPTY); InvokeFrameResized(); } else if (Tags.Count >= 1 && Frame.Height != FULL_SIZE) { TagCollectionToggle(FULL_SIZE, FULL); InvokeFrameResized(); } } private void TagCollectionToggle(int viewSize, int collectionSize) { Frame = new CGRect(Frame.Location, new CGSize(Frame.Width, viewSize)); tagCollection.Frame = new CGRect(tagCollection.Frame.Location, new CGSize(tagCollection.Frame.Width, collectionSize)); } #endregion #region Partial Methods partial void AddTagView(Tag tag) { CheckForListSize(); inputTextField.Text = ""; tagCollection.ReloadData(); } partial void SetValues(Word word) { inputTextField.Text = ""; foreach (Tag tag in word.Tags) { AddTag(tag); } } partial void Query(Query query) { if (tags.Count >= 1) { foreach (Tag tag in tags) { query.AddOrStatement(Database.TAG_TABLE + "." + StudyEspanol.Data.Models.Tag.TEXT + "='" + tag.Text + "'"); } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var legendariesList = new Dictionary<string, int>() { {"motes", 0 }, {"shards", 0 }, {"fragments", 0 } }; var junkList = new Dictionary<string, int>(); var canContinue = true; while (canContinue) { var input = Console.ReadLine().Split(); for (int i = 0; i < input.Length; i += 2) { var currentResourceQuantity = int.Parse(input[i]); var currentResourceType = input[i + 1].ToLower(); if (legendariesList.ContainsKey(currentResourceType)) { legendariesList[currentResourceType] += currentResourceQuantity; if (legendariesList[currentResourceType] >= 250) { legendariesList[currentResourceType] -= 250; var legendaryItemObtained = string.Empty; switch (currentResourceType) { case "motes": legendaryItemObtained = "Dragonwrath"; break; case "shards": legendaryItemObtained = "Shadowmourne"; break; case "fragments": legendaryItemObtained = "Valanyr"; break; } Console.WriteLine($"{legendaryItemObtained} obtained!"); canContinue = false; break; } } else { if (!junkList.ContainsKey(currentResourceType)) { junkList[currentResourceType] = 0; } junkList[currentResourceType] += currentResourceQuantity; } } } foreach (var legendaryItem in legendariesList.OrderByDescending(x => x.Value).ThenBy(x => x.Key)) { var legendaryItemName = legendaryItem.Key; var legendaryMatsQuantity = legendaryItem.Value; Console.WriteLine($"{legendaryItemName}: {legendaryMatsQuantity}"); } foreach (var junkItem in junkList.OrderBy(x => x.Key)) { var junkItemName = junkItem.Key; var junkMatsQuantity = junkItem.Value; Console.WriteLine($"{junkItemName}: {junkMatsQuantity}"); } } }
using System; using System.Linq; using System.Web.Mvc; using ArteVida.Dominio.Contexto; using ArteVida.Dominio.Repositorio; using ArteVida.Dominio.Entidades; using AutoMapper; using AutoMapper; using AutoMapper.QueryableExtensions; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using ArteVida.GestorWeb.ViewModels; using Microsoft.Owin.Security.DataHandler.Encoder; namespace ArteVida.GestorWeb.Controllers { public class IrmaoController : Controller { private DbContexto _contexto; private RepositorioIrmao _repositorio; private RepositorioAtleta _repositorioAtleta; private int _AtletaId; public IrmaoController() { _contexto = new DbContexto(); _repositorio = new RepositorioIrmao(_contexto); // ViewData["Funcionarios"] = _repositorioFuncionario.ObterTodos().Select(c => new { Id = c.PessoaId, Nome = c.Nome }).OrderBy(x=>x.Nome); } public ActionResult Index() { return View(); } public ActionResult Consulta() { var model = new JanelaViewModel { Titulo = "Cadastro de Irmaos", Relatorio = "ListagemIrmaos.trdx", Tela = "_GridIrmaos" }; return View("_ConsultaBase", model); } public ActionResult LerIrmaoAtleta([DataSourceRequest] DataSourceRequest request, int atletaId) { _AtletaId = atletaId; return Json(PegarIrmaos().ToDataSourceResult(request)); } public ActionResult Ler([DataSourceRequest] DataSourceRequest request, int id) { _AtletaId = id; //_AtletaId = int.Parse(id); return Json(PegarIrmaos().ToDataSourceResult(request)); } private IQueryable<IrmaoViewModel> PegarIrmaos() { var dados = _repositorio.ObterTodos().Where(x => x.Atleta.PessoaId == _AtletaId).ProjectTo<IrmaoViewModel>(); return dados; } //public ActionResult IncluirIrmaoAtleta([DataSourceRequest] DataSourceRequest request, IrmaoViewModel item) //{ // return IncluirIrmaoAtleta(request, item,0); //} [HttpPost] public ActionResult IncluirIrmaoAtleta(DataSourceRequest request, IrmaoViewModel item, int atletaId) { if (ModelState.IsValid) { try { Irmao dados = Mapper.Map<Irmao>(item); dados.Atleta = _contexto.Atletas.Find(atletaId); _repositorio.Inserir(dados); _contexto.SaveChanges(); item.IrmaoId = dados.IrmaoId; } catch (Exception erro) { ModelState.AddModelError("", erro.Message); _contexto.Rollback(); return Json(ModelState.ToDataSourceResult()); } } return Json(new[] {item}.ToDataSourceResult(request, ModelState)); } public ActionResult Atualizar([DataSourceRequest] DataSourceRequest request, IrmaoViewModel item) { if (ModelState.IsValid) { try { Irmao dados = Mapper.Map<Irmao>(item); dados = _repositorio.Atualizar(dados); _contexto.Commit(); item.IrmaoId = dados.IrmaoId; } catch (Exception erro) { ModelState.AddModelError("", erro.Message); _contexto.Rollback(); } } return Json(ModelState.ToDataSourceResult()); } public ActionResult ExcluirIrmaoAtleta([DataSourceRequest] DataSourceRequest request, IrmaoViewModel item) { try { _contexto.Irmoes.Remove(_contexto.Irmoes.Find(item.IrmaoId)); _contexto.SaveChanges(); ModelState.IsValidField("true"); } catch (Exception erro) { ModelState.IsValidField("false"); ModelState.AddModelError("", erro.Message); _contexto.Rollback(); } return Json(ModelState.ToDataSourceResult()); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Ruminate.GUI.Framework; using Ruminate.GUI.Content; using System.IO; using Ruminate.Utils; using System.Globalization; using ParticleStormDLL; using System.Reflection; namespace Sandstorm.GUI { /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class HUD : DrawableGameComponent { public Gui GUI { get; set; } private SpriteFont _Calibri20; private SpriteFont _Calibri16; private Texture2D _ImageMap; private string _Map; private Panel _MainMenu; private ScrollBars _MainContent; private List<Object> _Items; private bool _Visible; public int MenuOffset { get; set; } /// <summary> /// /// </summary> /// <param name="game"></param> public HUD(Game game) : base(game) { MenuOffset = 170; _Items = new List<Object>(); _Calibri20 = Game.Content.Load<SpriteFont>("font\\Calibri20"); _Calibri16 = Game.Content.Load<SpriteFont>("font\\Calibri16"); _ImageMap = Game.Content.Load<Texture2D>("GUI\\StormThemePurple"); _Map = File.OpenText("Content\\GUI\\StormMap.txt").ReadToEnd(); } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { base.Initialize(); } public void InitGui() { _Visible = true; var skin = new Skin(_ImageMap, _Map); var calibri16 = new Text(_Calibri16, Color.White); var calibri20 = new Text(_Calibri20, Color.White); var testSkins = new[] { new Tuple<string, Skin>("Skin", skin) }; var testTexts = new[] { new Tuple<string, Text>("Calibri16", calibri16), new Tuple<string, Text>("Calibri20", calibri20)}; int width = Game.Window.ClientBounds.Width; int height = Game.Window.ClientBounds.Height; GUI = new Gui(base.Game, skin, calibri16, testSkins, testTexts); CreateMainMenu(width, height); Hide(); } private void CreateMainMenu(int width, int height) { _MainMenu = new Panel(width - MenuOffset, 0, 175, height); _MainContent = new ScrollBars(); Label head = new Label(5, 15, "Options") { Text = "Calibri20" }; Panel optionPanel = new Panel(0, 50, 170, height - 50); GUI.AddWidget(_MainMenu); _MainMenu.AddWidget(head); _MainMenu.AddWidget(optionPanel); optionPanel.AddWidget(_MainContent); for (int i = 0; i < _Items.Count; i++) { string label = _Items[i].GetType().Name.Substring(0, _Items[i].GetType().Name.IndexOf("Properties")); Widget subMenu = CreateSubMenu(width, height, _Items[i], label); _MainContent.AddWidget(new Button(0, 30 * i, 170 - 15, label, buttonEvent: delegate(Widget widget) { HideWidget(_MainMenu); ShowWidget(subMenu); })); } } private Widget CreateSubMenu(int width, int height, Object item, string label) { Panel subPanel = new Panel(width - MenuOffset, 0, 175, height); Label head = new Label(5, 15, label) { Text = "Calibri20" }; Panel optionPanel = new Panel(0, 50, 170, height - 50); ScrollBars scrollBars = new ScrollBars(); GUI.AddWidget(subPanel); subPanel.AddWidget(head); subPanel.AddWidget(optionPanel); optionPanel.AddWidget(scrollBars); PropertyInfo[] properties = item.GetType().GetProperties(); for (int i = 0, offset = 0; i < properties.Length; i++) { switch (properties[i].PropertyType.ToString()) { case "System.Int32": IntSlider iS = new IntSlider(scrollBars, item, properties[i].Name, 0, offset, 145, 0, 2000); offset += 40; break; case "System.Single": FloatSlider oS = new FloatSlider(scrollBars, item, properties[i].Name, 0, offset, 145, 0.0f, 100.0f); offset += 40; break; case "Microsoft.Xna.Framework.Vector3": Vector3Slider v3S = new Vector3Slider(scrollBars, item, properties[i].Name, 0, offset, 145, new Vector3(-999, -999, -999), new Vector3(999, 999, 999)); offset += 85; break; case "Microsoft.Xna.Framework.Color": ColorSlider cS = new ColorSlider(scrollBars, item, properties[i].Name, 0, offset, 145, new Color(0, 0, 0, 0), new Color(255, 255, 255, 255)); offset += 100; break; case "System.Boolean": BooleanToggle bt = new BooleanToggle(scrollBars, item, properties[i].Name, 0, offset); offset += 40; break; case "Microsoft.Xna.Framework.Graphics.Texture2D": break; } } return subPanel; } /// <summary> /// /// </summary> /// <param name="value"></param> public void AddSubMenu(Object item) { _Items.Add(item); _Visible = true; InitGui(); } /// <summary> /// /// </summary> public void Show() { if (!_Visible) { ShowWidget(_MainMenu); _Visible = true; } } /// <summary> /// /// </summary> public void Hide() { if (_Visible) { foreach (Widget widget in GUI.Widgets) { HideWidget(widget); } _Visible = false; } } /// <summary> /// /// </summary> /// <param name="widget"></param> private void HideWidget(Widget widget) { foreach (Widget child in widget.Children) { HideWidget(child); child.Visible = false; } widget.Visible = false; } /// <summary> /// /// </summary> /// <param name="widget"></param> private void ShowWidget(Widget widget) { //Widget[] children = widget.Children.ToArray(); foreach (Widget child in widget.Children) { ShowWidget(child); child.Visible = true; } widget.Visible = true; } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { if (GUI != null) GUI.Update(); base.Update(gameTime); } public override void Draw(GameTime gameTime) { if (GUI != null) GUI.Draw(); base.Draw(gameTime); } public void OnResize() { this.InitGui(); GUI.Resize(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformerCharacter : MonoBehaviour { public bool isGrounded; public float moveSpeed = 15f; public float jumpPower = 20f; public Transform cam; public float camOffset = .5f; Rigidbody2D myRigidBody; Transform myTransform; float inputHorizontal; bool isJumping = false; void Start() { myRigidBody = GetComponent<Rigidbody2D>(); myTransform = GetComponent<Transform>(); } void Update() { inputHorizontal = Input.GetAxis("Horizontal"); if (Input.GetButtonDown("Jump") && isGrounded) { isJumping = true; } moveCamera(); } void FixedUpdate() { myRigidBody.velocity = new Vector2 ( inputHorizontal * moveSpeed, myRigidBody.velocity.y); if (isJumping) { myRigidBody.velocity = new Vector2 (myRigidBody.velocity.x, jumpPower); isJumping = false; } } void moveCamera() { cam.position = new Vector3 (0f, myTransform.position.y + camOffset, -10f); if (cam.position.y < .5) { cam.position = new Vector3 (0f, camOffset, -10f); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit.Abstractions; namespace Microsoft.EntityFrameworkCore { public class TPTTableSplittingSqlServerTest : TPTTableSplittingTestBase { public TPTTableSplittingSqlServerTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; public override async Task Can_use_with_redundant_relationships() { await base.Can_use_with_redundant_relationships(); AssertSql( @"SELECT [v].[Name], [v].[SeatingCapacity], [c].[AttachedVehicleName], CASE WHEN [c].[Name] IS NOT NULL THEN N'CompositeVehicle' WHEN [p].[Name] IS NOT NULL THEN N'PoweredVehicle' END AS [Discriminator], [t0].[Name], [t0].[Operator_Name], [t0].[LicenseType], [t0].[Discriminator], [t1].[Name], [t1].[Active], [t1].[Type], [t4].[Name], [t4].[Computed], [t4].[Description], [t4].[Discriminator], [t6].[VehicleName], [t6].[Capacity], [t6].[FuelType], [t6].[GrainGeometry], [t6].[Discriminator] FROM [Vehicles] AS [v] LEFT JOIN [PoweredVehicles] AS [p] ON [v].[Name] = [p].[Name] LEFT JOIN [CompositeVehicles] AS [c] ON [v].[Name] = [c].[Name] LEFT JOIN ( SELECT [v0].[Name], [v0].[Operator_Name], [l].[LicenseType], CASE WHEN [l].[VehicleName] IS NOT NULL THEN N'LicensedOperator' END AS [Discriminator] FROM [Vehicles] AS [v0] LEFT JOIN [LicensedOperators] AS [l] ON [v0].[Name] = [l].[VehicleName] INNER JOIN ( SELECT [v1].[Name] FROM [Vehicles] AS [v1] ) AS [t] ON [v0].[Name] = [t].[Name] ) AS [t0] ON [v].[Name] = [t0].[Name] LEFT JOIN ( SELECT [v2].[Name], [v2].[Active], [v2].[Type] FROM [Vehicles] AS [v2] INNER JOIN ( SELECT [v3].[Name] FROM [Vehicles] AS [v3] INNER JOIN ( SELECT [v4].[Name] FROM [Vehicles] AS [v4] ) AS [t3] ON [v3].[Name] = [t3].[Name] ) AS [t2] ON [v2].[Name] = [t2].[Name] WHERE [v2].[Active] IS NOT NULL ) AS [t1] ON [t0].[Name] = [t1].[Name] LEFT JOIN ( SELECT [p2].[Name], [p2].[Computed], [p2].[Description], CASE WHEN [s].[VehicleName] IS NOT NULL THEN N'SolidRocket' WHEN [i].[VehicleName] IS NOT NULL THEN N'IntermittentCombustionEngine' WHEN [c3].[VehicleName] IS NOT NULL THEN N'ContinuousCombustionEngine' END AS [Discriminator] FROM [PoweredVehicles] AS [p2] LEFT JOIN [ContinuousCombustionEngines] AS [c3] ON [p2].[Name] = [c3].[VehicleName] LEFT JOIN [IntermittentCombustionEngines] AS [i] ON [p2].[Name] = [i].[VehicleName] LEFT JOIN [SolidRockets] AS [s] ON [p2].[Name] = [s].[VehicleName] INNER JOIN ( SELECT [v5].[Name] FROM [Vehicles] AS [v5] INNER JOIN [PoweredVehicles] AS [p3] ON [v5].[Name] = [p3].[Name] ) AS [t5] ON [p2].[Name] = [t5].[Name] WHERE [p2].[Computed] IS NOT NULL ) AS [t4] ON [v].[Name] = [t4].[Name] LEFT JOIN ( SELECT [c5].[VehicleName], [c5].[Capacity], [c5].[FuelType], [s0].[GrainGeometry], CASE WHEN [s0].[VehicleName] IS NOT NULL THEN N'SolidFuelTank' END AS [Discriminator] FROM [CombustionEngines] AS [c5] LEFT JOIN [SolidFuelTanks] AS [s0] ON [c5].[VehicleName] = [s0].[VehicleName] INNER JOIN ( SELECT [p4].[Name] FROM [PoweredVehicles] AS [p4] INNER JOIN [CombustionEngines] AS [c6] ON [p4].[Name] = [c6].[VehicleName] ) AS [t7] ON [c5].[VehicleName] = [t7].[Name] WHERE [c5].[Capacity] IS NOT NULL ) AS [t6] ON [t4].[Name] = [t6].[VehicleName] ORDER BY [v].[Name]"); } public override async Task Can_query_shared() { await base.Can_query_shared(); AssertSql( @"SELECT [v].[Name], [v].[Operator_Name], [l].[LicenseType], CASE WHEN [l].[VehicleName] IS NOT NULL THEN N'LicensedOperator' END AS [Discriminator] FROM [Vehicles] AS [v] LEFT JOIN [LicensedOperators] AS [l] ON [v].[Name] = [l].[VehicleName] INNER JOIN ( SELECT [v0].[Name] FROM [Vehicles] AS [v0] ) AS [t] ON [v].[Name] = [t].[Name]"); } public override async Task Can_query_shared_nonhierarchy() { await base.Can_query_shared_nonhierarchy(); AssertSql( @"SELECT [v].[Name], [v].[Operator_Name] FROM [Vehicles] AS [v] INNER JOIN ( SELECT [v0].[Name] FROM [Vehicles] AS [v0] ) AS [t] ON [v].[Name] = [t].[Name]"); } public override async Task Can_query_shared_nonhierarchy_with_nonshared_dependent() { await base.Can_query_shared_nonhierarchy_with_nonshared_dependent(); AssertSql( @"SELECT [v].[Name], [v].[Operator_Name] FROM [Vehicles] AS [v] INNER JOIN ( SELECT [v0].[Name] FROM [Vehicles] AS [v0] ) AS [t] ON [v].[Name] = [t].[Name]"); } public override async Task Can_query_shared_derived_hierarchy() { await base.Can_query_shared_derived_hierarchy(); AssertSql( @"SELECT [c].[VehicleName], [c].[Capacity], [c].[FuelType], [s].[GrainGeometry], CASE WHEN [s].[VehicleName] IS NOT NULL THEN N'SolidFuelTank' END AS [Discriminator] FROM [CombustionEngines] AS [c] LEFT JOIN [SolidFuelTanks] AS [s] ON [c].[VehicleName] = [s].[VehicleName] INNER JOIN ( SELECT [p].[Name] FROM [PoweredVehicles] AS [p] INNER JOIN [CombustionEngines] AS [c0] ON [p].[Name] = [c0].[VehicleName] ) AS [t] ON [c].[VehicleName] = [t].[Name] WHERE [c].[Capacity] IS NOT NULL"); } public override async Task Can_query_shared_derived_nonhierarchy() { await base.Can_query_shared_derived_nonhierarchy(); AssertSql( @"SELECT [c].[VehicleName], [c].[Capacity], [c].[FuelType] FROM [CombustionEngines] AS [c] INNER JOIN ( SELECT [p].[Name] FROM [PoweredVehicles] AS [p] INNER JOIN [CombustionEngines] AS [c0] ON [p].[Name] = [c0].[VehicleName] ) AS [t] ON [c].[VehicleName] = [t].[Name] WHERE [c].[Capacity] IS NOT NULL"); } public override async Task Can_query_shared_derived_nonhierarchy_all_required() { await base.Can_query_shared_derived_nonhierarchy_all_required(); AssertSql( @"SELECT [c].[VehicleName], [c].[Capacity], [c].[FuelType] FROM [CombustionEngines] AS [c] INNER JOIN ( SELECT [p].[Name] FROM [PoweredVehicles] AS [p] INNER JOIN [CombustionEngines] AS [c0] ON [p].[Name] = [c0].[VehicleName] ) AS [t] ON [c].[VehicleName] = [t].[Name] WHERE [c].[Capacity] IS NOT NULL AND [c].[FuelType] IS NOT NULL"); } public override async Task Can_change_dependent_instance_non_derived() { await base.Can_change_dependent_instance_non_derived(); AssertSql( @"@p1='Trek Pro Fit Madone 6 Series' (Nullable = false) (Size = 450) @p0='repairman' (Size = 4000) SET NOCOUNT ON; UPDATE [Vehicles] SET [Operator_Name] = @p0 WHERE [Name] = @p1; SELECT @@ROWCOUNT;", // @"@p2='Trek Pro Fit Madone 6 Series' (Nullable = false) (Size = 450) @p3='Repair' (Size = 4000) SET NOCOUNT ON; INSERT INTO [LicensedOperators] ([VehicleName], [LicenseType]) VALUES (@p2, @p3);", // @"SELECT TOP(2) [v].[Name], [v].[SeatingCapacity], [c].[AttachedVehicleName], CASE WHEN [c].[Name] IS NOT NULL THEN N'CompositeVehicle' WHEN [p].[Name] IS NOT NULL THEN N'PoweredVehicle' END AS [Discriminator], [t0].[Name], [t0].[Operator_Name], [t0].[LicenseType], [t0].[Discriminator] FROM [Vehicles] AS [v] LEFT JOIN [PoweredVehicles] AS [p] ON [v].[Name] = [p].[Name] LEFT JOIN [CompositeVehicles] AS [c] ON [v].[Name] = [c].[Name] LEFT JOIN ( SELECT [v0].[Name], [v0].[Operator_Name], [l].[LicenseType], CASE WHEN [l].[VehicleName] IS NOT NULL THEN N'LicensedOperator' END AS [Discriminator] FROM [Vehicles] AS [v0] LEFT JOIN [LicensedOperators] AS [l] ON [v0].[Name] = [l].[VehicleName] INNER JOIN ( SELECT [v1].[Name] FROM [Vehicles] AS [v1] ) AS [t] ON [v0].[Name] = [t].[Name] ) AS [t0] ON [v].[Name] = [t0].[Name] WHERE [v].[Name] = N'Trek Pro Fit Madone 6 Series'"); } public override async Task Can_change_principal_instance_non_derived() { await base.Can_change_principal_instance_non_derived(); AssertSql( @"@p1='Trek Pro Fit Madone 6 Series' (Nullable = false) (Size = 450) @p0='2' SET NOCOUNT ON; UPDATE [Vehicles] SET [SeatingCapacity] = @p0 WHERE [Name] = @p1; SELECT @@ROWCOUNT;", // @"SELECT TOP(2) [v].[Name], [v].[SeatingCapacity], [c].[AttachedVehicleName], CASE WHEN [c].[Name] IS NOT NULL THEN N'CompositeVehicle' WHEN [p].[Name] IS NOT NULL THEN N'PoweredVehicle' END AS [Discriminator], [t0].[Name], [t0].[Operator_Name], [t0].[LicenseType], [t0].[Discriminator] FROM [Vehicles] AS [v] LEFT JOIN [PoweredVehicles] AS [p] ON [v].[Name] = [p].[Name] LEFT JOIN [CompositeVehicles] AS [c] ON [v].[Name] = [c].[Name] LEFT JOIN ( SELECT [v0].[Name], [v0].[Operator_Name], [l].[LicenseType], CASE WHEN [l].[VehicleName] IS NOT NULL THEN N'LicensedOperator' END AS [Discriminator] FROM [Vehicles] AS [v0] LEFT JOIN [LicensedOperators] AS [l] ON [v0].[Name] = [l].[VehicleName] INNER JOIN ( SELECT [v1].[Name] FROM [Vehicles] AS [v1] ) AS [t] ON [v0].[Name] = [t].[Name] ) AS [t0] ON [v].[Name] = [t0].[Name] WHERE [v].[Name] = N'Trek Pro Fit Madone 6 Series'"); } public override async Task Optional_dependent_materialized_when_no_properties() { await base.Optional_dependent_materialized_when_no_properties(); AssertSql( @"SELECT TOP(1) [v].[Name], [v].[SeatingCapacity], [c].[AttachedVehicleName], CASE WHEN [c].[Name] IS NOT NULL THEN N'CompositeVehicle' WHEN [p].[Name] IS NOT NULL THEN N'PoweredVehicle' END AS [Discriminator], [t0].[Name], [t0].[Operator_Name], [t0].[LicenseType], [t0].[Discriminator], [t1].[Name], [t1].[Active], [t1].[Type] FROM [Vehicles] AS [v] LEFT JOIN [PoweredVehicles] AS [p] ON [v].[Name] = [p].[Name] LEFT JOIN [CompositeVehicles] AS [c] ON [v].[Name] = [c].[Name] LEFT JOIN ( SELECT [v0].[Name], [v0].[Operator_Name], [l].[LicenseType], CASE WHEN [l].[VehicleName] IS NOT NULL THEN N'LicensedOperator' END AS [Discriminator] FROM [Vehicles] AS [v0] LEFT JOIN [LicensedOperators] AS [l] ON [v0].[Name] = [l].[VehicleName] INNER JOIN ( SELECT [v1].[Name] FROM [Vehicles] AS [v1] ) AS [t] ON [v0].[Name] = [t].[Name] ) AS [t0] ON [v].[Name] = [t0].[Name] LEFT JOIN ( SELECT [v2].[Name], [v2].[Active], [v2].[Type] FROM [Vehicles] AS [v2] INNER JOIN ( SELECT [v3].[Name] FROM [Vehicles] AS [v3] INNER JOIN ( SELECT [v4].[Name] FROM [Vehicles] AS [v4] ) AS [t3] ON [v3].[Name] = [t3].[Name] ) AS [t2] ON [v2].[Name] = [t2].[Name] WHERE [v2].[Active] IS NOT NULL ) AS [t1] ON [t0].[Name] = [t1].[Name] WHERE [v].[Name] = N'AIM-9M Sidewinder' ORDER BY [v].[Name]"); } } }
using System; using MXDbhelper.Common; namespace MXQHLibrary { [TableView("Sys_FunctionLoad")] public class FunctionLoad { /// <summary> /// id /// </summary> [ColumnProperty(Key.True)] public Int64 Id { get; set; } /// <summary> /// 功能编号 /// </summary> public string FunNo { get; set; } /// <summary> /// 依赖文件路径 /// </summary> public string LoadName { get; set; } /// <summary> /// 载入顺序 /// </summary> [ColumnProperty(Sort.ASC, 3)] public int? SortNo { get; set; } } }
namespace Array_Symmetry { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ArraySymmetry { public static void Main(string[] args) { //read the input,split and convert to string array; var input = Console.ReadLine().Split(' ').ToArray(); //bool for check if strings are equal; bool flag = true; for (int i = 0; i < input.Length / 2; i++) { //var for left string var leftString = input[i]; //var for right string; var rightString = input[(input.Length - 1) - i]; if (leftString != rightString) { flag = false; break; } } if (flag) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } } }
using System; using System.Data; using System.Windows.Forms; using Microsoft.Office.Interop.Word; using MySql.Data.MySqlClient; namespace PwMemoGenerator { public partial class frmPWMemoMainMenu : Form { public frmPWMemoMainMenu() { InitializeComponent(); } Microsoft.Office.Interop.Word.Application app; Document doc; object missing = Type.Missing; private void btnGenerateNewPWs_Click(object sender, EventArgs e) { //killprocess("winword"); app = new Microsoft.Office.Interop.Word.Application { Visible = false }; System.Data.DataTable dt = new System.Data.DataTable(); string qry = "SELECT * FROM ibis_pw_userlist WHERE ibis_pw_userlist_active = 1 AND ibis_pw_userlist_id > 1"; //string qry = "SELECT * FROM ibis_pw_userlist WHERE ibis_pw_userlist_active = 1"; Random randnum = new Random(); int _min4 = 0; int _max4 = 9999; int _min6 = 0; int _max6 = 999999; using (MySqlConnection dbh = new MySqlConnection(Properties.Resources.DB_CONNSTR_HES)) { dbh.Open(); using (MySqlDataAdapter da = new MySqlDataAdapter(qry, dbh)) { da.Fill(dt); foreach (DataRow row in dt.Rows) { doc = app.Documents.Add(@"C:\Users\dc1_000\Documents\HoldenEngineering\pw_memo_template.docx"); doc.Activate(); string newpw; if (row["ibis_pw_userlist_un"].ToString().Equals("dholden")) { newpw = String.Format("{0:000000}", randnum.Next(_min6, _max6)); } else { // HERE IS WHERE ONE COULD RANDOMIZE THE PLACEMENT OF // THE ABBREVIATION RELATIVE TO THE FOUR-DIGIT NUMBER newpw = row["ibis_pw_userlist_abbr"].ToString() + String.Format("{0:0000}", randnum.Next(_min4, _max4)); } doc.Bookmarks["bmNameLbl"].Range.Text = row["ibis_pw_userlist_label"].ToString(); doc.Bookmarks["bmGenPW"].Range.Text = newpw; doc.Bookmarks["bmUserName"].Range.Text = row["ibis_pw_userlist_un"].ToString(); doc.Bookmarks["bmOldPW"].Range.Text = row["ibis_pw_userlist_currpw"].ToString(); doc.Bookmarks["bmNewPW"].Range.Text = newpw; doc.Bookmarks["bmNewPW2"].Range.Text = newpw; doc.PrintOut(); ((Microsoft.Office.Interop.Word._Document)doc).Close(false, ref missing, ref missing); try { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = dbh; cmd.CommandText = "UPDATE ibis_pw_userlist SET ibis_pw_userlist_currpw = @npw, ibis_pw_userlist_prevpw = @opw WHERE ibis_pw_userlist_id = @uid"; cmd.Prepare(); cmd.Parameters.AddWithValue("@npw", newpw); cmd.Parameters.AddWithValue("@opw", row["ibis_pw_userlist_currpw"].ToString()); cmd.Parameters.AddWithValue("@uid", row["ibis_pw_userlist_id"].ToString()); cmd.ExecuteNonQuery(); } catch (MySqlException mysqle) { MessageBox.Show("mysql ERROR: " + mysqle.ToString()); return; } catch (Exception m1ex) { MessageBox.Show("M1_ERROR: " + m1ex.ToString()); return; } } } dbh.Close(); } } private void btnCloseAndExit_Click(object sender, EventArgs e) { ((Microsoft.Office.Interop.Word._Application)app).Quit(false, ref missing, ref missing); System.Windows.Forms.Application.Exit(); } private void btnPrintPWMemos_Click(object sender, EventArgs e) { app = new Microsoft.Office.Interop.Word.Application { Visible = false }; System.Data.DataTable dt = new System.Data.DataTable(); string qry = "SELECT * FROM ibis_pw_userlist WHERE ibis_pw_userlist_active = 1"; using (MySqlConnection dbh = new MySqlConnection(Properties.Resources.DB_CONNSTR_HES)) { dbh.Open(); using (MySqlDataAdapter da = new MySqlDataAdapter(qry, dbh)) { da.Fill(dt); foreach (DataRow row in dt.Rows) { doc = app.Documents.Add(@"C:\Users\dc1_000\Documents\HoldenEngineering\pw_memo_template.docx"); doc.Activate(); doc.Bookmarks["bmNameLbl"].Range.Text = row["ibis_pw_userlist_label"].ToString(); doc.Bookmarks["bmGenPW"].Range.Text = row["ibis_pw_userlist_currpw"].ToString(); doc.Bookmarks["bmUserName"].Range.Text = row["ibis_pw_userlist_un"].ToString(); doc.Bookmarks["bmOldPW"].Range.Text = row["ibis_pw_userlist_prevpw"].ToString(); doc.Bookmarks["bmNewPW"].Range.Text = row["ibis_pw_userlist_currpw"].ToString(); doc.Bookmarks["bmNewPW2"].Range.Text = row["ibis_pw_userlist_currpw"].ToString(); doc.PrintOut(); ((Microsoft.Office.Interop.Word._Document)doc).Close(false, ref missing, ref missing); } } dbh.Close(); } } } }
using System; using System.Text; namespace GdNet.Common { /// <summary> /// Generate new random string with difference options /// </summary> public class RandomString { private readonly int _length; private const string LowerChars = "abcdefgijkmnopqrstwxyz"; private const string UpperChars = "ABCDEFGHJKLMNPQRSTWXYZ"; private const string Numbers = "0123456789"; private const string SpecialChars = "!@#$%^&*()+=?/"; private readonly string _allChars; /// <summary> /// Options use to generate new random string /// </summary> [Flags] public enum Options { /// <summary> /// Generate only numbers /// </summary> Numbers = 1, /// <summary> /// Generate only lower characters /// </summary> LowerChars = 2, /// <summary> /// Generate only upper characters /// </summary> UpperChars = 4, /// <summary> /// Generate only special characters /// </summary> SpecialChars = 8, /// <summary> /// Expect any characters /// </summary> Any = Numbers | LowerChars | UpperChars | SpecialChars } /// <summary> /// New instance with default options (Length = 6 and only Numbers) /// </summary> public RandomString() : this(6, Options.Numbers) { } /// <summary> /// New instance with custom options /// </summary> public RandomString(int length, Options options) { if (length < 3) { throw new ArgumentException("Length must not less than 3"); } _length = length; _allChars = BuildAllChars(options); } /// <summary> /// Generate new random string with given options /// </summary> public string NextValue() { var sb = new StringBuilder(); var random = new Random(); while (sb.Length < _length) { var index = random.Next(_allChars.Length); sb.Append(_allChars[index]); } return sb.ToString(); } private string BuildAllChars(Options options) { var allChars = new StringBuilder(); if (options.HasFlag(Options.Numbers)) { allChars.Append(Numbers); } if (options.HasFlag(Options.LowerChars)) { allChars.Append(LowerChars); } if (options.HasFlag(Options.UpperChars)) { allChars.Append(UpperChars); } if (options.HasFlag(Options.SpecialChars)) { allChars.Append(SpecialChars); } return allChars.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace irc_client.connection.requests { public class AddRequest:AbstractRequest, IRequest { public const int LOGIN = 0; public AddRequest(string login) : base("add", 1) { base._requestParams[LOGIN] = login; } public RequestType Type { get { return RequestType.Add; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace EBV { public partial class AdminHome : System.Web.UI.Page { BLL.BLL obj = new BLL.BLL(); protected void Page_Load(object sender, EventArgs e) { LoadCompanies(); LoadGuest(); if (Session["cName"] != null) { txtCompany.Text =Convert.ToString(Session["cName"]); } else if (Session["Guest"] != null) { txtCompany.Text = Convert.ToString(Session["Guest"]); } } private void LoadCompanies() { DataTable tab = obj.getCompany(); if (tab.Rows.Count > 0) { gvCompany.DataSource = tab; gvCompany.DataBind(); } else { gvCompany.Controls.Clear(); lblMsg.Text = "Companies are not yet added"; } } private void LoadGuest() { DataTable tab = obj.getGuestByBit(1); if (tab.Rows.Count > 0) { gvGuest1.DataSource = tab; gvGuest1.DataBind(); } else { gvGuest1.Controls.Clear(); lblMsg.Text = "Guests are not yet added"; } } protected void btnSubmit_Click(object sender, EventArgs e) { if (Session["Guest"] == null) { if (btnSubmit.Text == "Add") { if (obj.Insertcompany(txtCompany.Text, txtmail.Text, txtPass.Text)) { lblMsg.Text = ""; LoadCompanies(); ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Company Added Sucessfully')", true); btnSubmit.Text = "Add"; txtCompany.Text = ""; txtmail.Text = ""; } else { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Operation Failed')", true); } } else { if (obj.updateCompany(txtCompany.Text, txtmail.Text, txtPass.Text, id)) { lblMsg.Text = ""; LoadCompanies(); ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Company Updated Sucessfully')", true); btnSubmit.Text = "Add"; txtCompany.Text = ""; txtmail.Text = ""; } else { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Updation Failed!!')", true); } } } else { if (btnSubmit.Text == "Add") { int bit= 1; if (int.Parse(Session["gid"].ToString()) > 0) id=int.Parse(Session["gid"].ToString()); if (obj.updateGuest(txtmail.Text,txtPass.Text,bit,id)) { lblMsg.Text = ""; LoadCompanies(); LoadGuest(); ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Request Added Sucessfully')", true); btnSubmit.Text = "Add"; txtCompany.Text = ""; txtmail.Text = ""; } else { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Operation Failed')", true); } } else { int bit = 1; if (obj.updateGuest(txtmail.Text, txtPass.Text, bit, id)) { lblMsg.Text = ""; LoadCompanies(); LoadGuest(); ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Request Updated Sucessfully')", true); btnSubmit.Text = "Add"; txtCompany.Text = ""; txtmail.Text = ""; } else { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Updation Failed!!')", true); } } } } static int id = 0; protected void lnkEdit_Click(object sender, EventArgs e) { GridViewRow gvr = (GridViewRow)((LinkButton)sender).Parent.Parent; id = int.Parse(((LinkButton)sender).CommandArgument); txtCompany.Text = gvr.Cells[0].Text; txtmail.Text = gvr.Cells[1].Text; txtPass.Text = gvr.Cells[2].Text; btnSubmit.Text = "UPDATE"; } protected void lbkDelete_Click(object sender, EventArgs e) { GridViewRow gvr = (GridViewRow)((LinkButton)sender).Parent.Parent; id = int.Parse(((LinkButton)sender).CommandArgument); if (obj.deleteGuest(id)) { LoadCompanies(); ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Sucessfully Deleted')", true); } else { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Deletion Failed!!')", true); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Aserradero : Edificacion,IRecolectable<int> { [Header("Atributos de tipo Aserradero")] public int madera = 10; public float waitingTime=0.5f; private float currentTime=0f; /// <summary> /// Generars the recurso. /// </summary> /// <param name="cantidad">Cantidad.</param> public void generarRecurso(int cantidad){ Global.globales.madera += cantidad; Global.globales.textoMadera.text=Global.globales.madera +"/"+Global.globales.maderaMax; } // Update is called once per frame void Update () { currentTime += Time.deltaTime; if (currentTime>waitingTime) { currentTime = 0f; generarRecurso (madera); } Debug.Log (currentTime); } public void activarFuncionalidad(bool activar){ this.enabled = activar; } public override bool canConstruct () { Recurso[] recursos = this.construccion.costoEnRecursos; if (recursos[0].valor<=Global.globales.monedas && recursos[1].valor<= Global.globales.madera && recursos[2].valor<= Global.globales.plata) { return true; } return false; } }
namespace Plus.HabboHotel.Users { public class HabboStats { public int RoomVisits { get; set; } public double OnlineTime { get; set; } public int Respect { get; set; } public int RespectGiven { get; set; } public int GiftsGiven { get; set; } public int GiftsReceived { get; set; } public int DailyRespectPoints { get; set; } public int DailyPetRespectPoints { get; set; } public int AchievementPoints { get; set; } public int QuestId { get; set; } public int QuestProgress { get; set; } public int FavouriteGroupId { get; set; } public string RespectsTimestamp { get; set; } public int ForumPosts { get; set; } public HabboStats(int roomVisits, double onlineTime, int respect, int respectGiven, int giftsGiven, int giftsReceived, int dailyRespectPoints, int dailyPetRespectPoints, int achievementPoints, int questId, int questProgress, int groupId, string respectsTimestamp, int forumPosts) { RoomVisits = roomVisits; OnlineTime = onlineTime; Respect = respect; RespectGiven = respectGiven; GiftsGiven = giftsGiven; GiftsReceived = giftsReceived; DailyRespectPoints = dailyRespectPoints; DailyPetRespectPoints = dailyPetRespectPoints; AchievementPoints = achievementPoints; QuestId = questId; QuestProgress = questProgress; FavouriteGroupId = groupId; RespectsTimestamp = respectsTimestamp; ForumPosts = forumPosts; } } }
using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Malum.Items.Weapons.Azurite { public class AzuriteHammer : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Azurite Hammer"); Tooltip.SetDefault("Isn't this unsafe? Fossils are apparently fragile.."); } public override void SetDefaults() { item.damage = 3; item.melee = true; item.width = 40; item.height = 40; item.useTime = 30; item.useAnimation = 10; item.hammer = 50; item.useStyle = 1; item.knockBack = 20; item.value = 10000; item.rare = 2; item.UseSound = SoundID.Item1; item.autoReuse = true; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "AzuriteBar", 15); recipe.AddTile(16); recipe.SetResult(this); recipe.AddRecipe(); } } }
using System.Collections.Generic; using CloneDeploy_DataModel; using CloneDeploy_Entities; using CloneDeploy_Entities.DTOs; namespace CloneDeploy_Services { public class ImageClassificationServices { private readonly UnitOfWork _uow; public ImageClassificationServices() { _uow = new UnitOfWork(); } public ActionResultDTO AddImageClassification(ImageClassificationEntity imageClassification) { var validationResult = ValidateImageClassification(imageClassification, true); var actionResult = new ActionResultDTO(); if (validationResult.Success) { _uow.ImageClassificationRepository.Insert(imageClassification); _uow.Save(); actionResult.Success = true; actionResult.Id = imageClassification.Id; } else { actionResult.ErrorMessage = validationResult.ErrorMessage; } return actionResult; } public ActionResultDTO DeleteImageClassification(int imageClassificationId) { var imageClassification = GetImageClassification(imageClassificationId); if (imageClassification == null) return new ActionResultDTO {ErrorMessage = "Image Classification Not Found", Id = 0}; _uow.ImageClassificationRepository.Delete(imageClassificationId); _uow.Save(); var images = _uow.ImageRepository.Get(x => x.ClassificationId == imageClassificationId); var imageService = new ImageServices(); foreach (var image in images) { image.ClassificationId = -1; imageService.UpdateImage(image); } var actionResult = new ActionResultDTO(); actionResult.Success = true; actionResult.Id = imageClassification.Id; return actionResult; } public List<ImageClassificationEntity> GetAll() { return _uow.ImageClassificationRepository.Get(); } public ImageClassificationEntity GetImageClassification(int imageClassificationId) { return _uow.ImageClassificationRepository.GetById(imageClassificationId); } public string TotalCount() { return _uow.ImageClassificationRepository.Count(); } public ActionResultDTO UpdateImageClassification(ImageClassificationEntity imageClassification) { var r = GetImageClassification(imageClassification.Id); if (r == null) return new ActionResultDTO {ErrorMessage = "Image Classification Not Found", Id = 0}; var validationResult = ValidateImageClassification(imageClassification, false); var actionResult = new ActionResultDTO(); if (validationResult.Success) { _uow.ImageClassificationRepository.Update(imageClassification, imageClassification.Id); _uow.Save(); actionResult.Success = true; actionResult.Id = imageClassification.Id; } return actionResult; } private ValidationResultDTO ValidateImageClassification(ImageClassificationEntity imageClassification, bool isNewImageClassification) { var validationResult = new ValidationResultDTO {Success = true}; if (string.IsNullOrEmpty(imageClassification.Name)) { validationResult.Success = false; validationResult.ErrorMessage = "Image Classification Name Is Not Valid"; return validationResult; } if (isNewImageClassification) { if (_uow.ImageClassificationRepository.Exists(h => h.Name == imageClassification.Name)) { validationResult.Success = false; validationResult.ErrorMessage = "This Image Classification Already Exists"; return validationResult; } } else { var originalImageClassification = _uow.ImageClassificationRepository.GetById(imageClassification.Id); if (originalImageClassification.Name != imageClassification.Name) { if (_uow.ImageClassificationRepository.Exists(h => h.Name == imageClassification.Name)) { validationResult.Success = false; validationResult.ErrorMessage = "This Image Classification Already Exists"; return validationResult; } } } return validationResult; } } }
using System; namespace Publicon.Core.Entities.Abstract { public abstract class DeleteAble : Entity { public DateTime? DeletedAt { get; protected set; } } }
using System; using Microsoft.Azure.Cosmos.Table; namespace camera_api.Model { public class Vignette : TableEntity { public Vignette() { } public Vignette(string ecv, string order) { PartitionKey = ecv; RowKey = order; } public DateTime ValidFrom {get; set;} public int ValidDays {get; set;} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public GameObject hexagonPrefab; public GameObject target; private float _x, _y; private float offsetX; private float offsetY = -0.25f; Color[] colors = { Color.red, Color.green, Color.blue, Color.yellow,Color.magenta }; public GameObject tapPrefab; public GameObject tapTarget; private float tapOffsetX = -0.1f; private float tapOffsetY = 0; Vector2 tapTargetStartPos; // Start is called before the first frame update void Start() { tapTargetStartPos = tapTarget.transform.position; CreateGrid(); } // Update is called once per frame void Update() { } void CreateGrid() { _x = 0; for (int i = 0; i < 2; i++) { for (int k = 0; k < 9; k++) { for (int j = 0; j < 4; j++) { GameObject insHexagon = Instantiate(hexagonPrefab, new Vector2(target.transform.position.x + offsetX, target.transform.position.y + offsetY), target.transform.rotation); insHexagon.GetComponent<Renderer>().material.color = colors[Random.Range(0, colors.Length)]; offsetX += 1.3f; } offsetX = _x; offsetY -= 0.7f; } offsetX = 0.65f; offsetY = -0.60f; _x = 0.65f; } for (int i = 0; i < 4; i++) { for (int j = 0; j < 16; j++) { GameObject insTap = Instantiate(tapPrefab, new Vector2(tapTarget.transform.position.x + tapOffsetX, tapTarget.transform.position.y - tapOffsetY), target.transform.rotation); tapOffsetY += 0.35f; tapOffsetX *= -1; } tapOffsetY = 0; tapTarget.transform.position = new Vector2(tapTarget.transform.position.x + 1.3f, tapTarget.transform.position.y); } tapTarget.transform.position = tapTargetStartPos; tapTarget.transform.position = new Vector2(tapTarget.transform.position.x + 0.65f, tapTarget.transform.position.y); tapOffsetX = 0.1f; for (int i = 0; i < 3; i++) { for (int j = 0; j < 16; j++) { GameObject insTap = Instantiate(tapPrefab, new Vector2(tapTarget.transform.position.x + tapOffsetX, tapTarget.transform.position.y - tapOffsetY), target.transform.rotation); tapOffsetY += 0.35f; tapOffsetX *= -1; } tapOffsetY = 0; tapTarget.transform.position = new Vector2(tapTarget.transform.position.x + 1.3f, tapTarget.transform.position.y); } } }
using System; namespace ReadyGamerOne.Utility { public static class StringExtension { public static int FindFirstSubstring(this string sour, string substring) { var length = sour.Length; var times = length - substring.Length + 1; if (times == 0) throw new Exception("substring 比 sour 短,怎么找Index?"); for (var i = 0; i < times; i++) { var temp = sour.Substring(i, length - i); if (temp.StartsWith(substring)) return i; } return -1; } public static string GetAfterSubstring(this string sour, string substring) { var index = sour.FindFirstSubstring(substring); index += substring.Length; return sour.Substring(index, sour.Length - index); } public static string GetBeforeSubstring(this string sour, string substring) { var index = sour.FindFirstSubstring(substring); return sour.Substring(0, index); } public static string GetAfterLastChar(this string sour, char c) { var index = sour.LastIndexOf(c); return sour.Substring(index+1,sour.Length-(1+index)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TBD.imdb.DataAccess.Entities; namespace TBD.imdb.Managers.Interfaces { public interface IAutor { IQueryable<Autor> ObtenerTodosActores(); } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MMSdb.dbo.Tables { [Table("tbl_Groups")] public class tbl_Groups { [Key] public long grp_ID { get; set; } public String? grp_Name { get; set; } public DateTime? grp_Created { get; set; } public DateTime? grp_Modified { get; set; } public Boolean? deleted { get; set; } } }
namespace RealEstate.Migrations { using System; using System.Data.Entity.Migrations; public partial class uioptionForMenu_2 : DbMigration { public override void Up() { AddColumn("dbo.PostCategories", "UIOption_DisplayOrder", c => c.Int(nullable: false)); AddColumn("dbo.PostCategories", "UIOption_IsDisplay", c => c.Boolean(nullable: false)); } public override void Down() { DropColumn("dbo.PostCategories", "UIOption_IsDisplay"); DropColumn("dbo.PostCategories", "UIOption_DisplayOrder"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetCode.Connection; using NetCode.Util; namespace NetCode.Payloads { [EnumeratePayload] public class HandshakePayload : Payload { public override bool ImmediateTransmitRequired { get { return true; } } public override bool AcknowledgementRequired { get { return AckRequired; } } public NetworkClient.ConnectionState State { get; private set; } private uint LocalNetTime; private bool AckRequired; private const byte AckRequriedBit = 0x80; public HandshakePayload() { } public static HandshakePayload Generate(NetworkClient.ConnectionState state, bool ackRequired) { HandshakePayload payload = new HandshakePayload() { State = state, LocalNetTime = (uint)NetTime.Now(), AckRequired = ackRequired }; payload.AllocateAndWrite(); return payload; } public override void OnReception(NetworkClient client) { client.RecieveEndpointState(State); long timestamp = NetTime.Now(); client.Connection.Stats.RecordNetTimeOffset(LocalNetTime - timestamp, timestamp); } public override void OnTimeout(NetworkClient client) { } public override int ContentSize() { return sizeof(byte) + sizeof(uint); } public override void ReadContent() { byte header = Buffer.ReadByte(); State = (NetworkClient.ConnectionState)(header & ~AckRequriedBit); AckRequired = (header & AckRequriedBit) != 0; LocalNetTime = Buffer.ReadUInt(); } public override void WriteContent() { byte header = (byte)State; if (AckRequired) { header |= AckRequriedBit; } Buffer.WriteByte(header ); Buffer.WriteUInt(LocalNetTime); } } }
using RateAndShare.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace RateAndShare.Controllers { public class UsersController : Controller { public const string SessionName = "UserId"; public const string SessionIsAdminName = "IsAdmin"; private RateAndShareContext db = new RateAndShareContext(); // GET: Users/Login public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login([Bind(Include = "Username,Password")] User p_user) { if (p_user == null) { return View(); } // check if the given params are correct and there is a user else if (p_user.Username != null && p_user.Password != null && isUserExists(p_user.Username, p_user.Password)) { User currUser = db.Users.First(user => user.Username == p_user.Username); int userId = currUser.UserId; bool isAdmin = currUser.IsAdmin; HttpContext.Session.Add(SessionName, userId); HttpContext.Session.Add(SessionIsAdminName, isAdmin); return RedirectToAction("Index", "Home"); } else { ViewData["ErrMessage"] = "Incorrect user name or password"; } return View(); } // GET: Users/Register public ActionResult Register() { ViewData["countries"] = db.Countries.ToList(); return View(); } // POST: Users/Register [HttpPost] public async Task<ActionResult> Register([Bind(Include = "Username,Password,Email,CountryId")] User p_user) { if (ModelState.IsValid) { // Check if there already User with the same username if (db.Users.Any(user => user.Username == p_user.Username)) { ViewData["ErrMessage"] = "The requeseted username is already taken, sorry.."; return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } db.Users.Add(p_user); await db.SaveChangesAsync(); return RedirectToAction("Login"); } return View(); } // GET: Users/LogOut public ActionResult LogOut() { HttpContext.Session.Clear(); return RedirectToAction("Index", "Home"); } private bool isUserExists(string p_username, string p_password) { return db.Users.Any(user => user.Username == p_username && user.Password == p_password); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { public class FolderMappingViewModel { public int Id { get; set; } public string Name { get; set; } public string FolderTypeName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using WS_PosData_PMKT.Models; using WS_PosData_PMKT.Models.Base; using WS_PosData_PMKT.Models.Object; using WS_PosData_PMKT.Models.Request; using WS_PosData_PMKT.Models.Response; namespace WS_PosData_PMKT { // NOTA: puede usar el comando "Rename" del menú "Refactorizar" para cambiar el nombre de interfaz "IWS_PosData_PMKT" en el código y en el archivo de configuración a la vez. [ServiceContract] public interface IWS_PosData_PMKT { // TODO: agregue aquí sus operaciones de servicio [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "AutenticateUser", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] UserDataResponse AutenticateUser(LoginUserRequest request); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "AvailablePromosUser/{user}", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ListPromosResponse AvailablePromosUser(string user); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "DetailEventsPromo/{IdPromo}", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] DetailEventsPromoResponse DetailEventsPromo(string IdPromo); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "DataRoutePromo/{Email}/{IdPromo}/{IdDay}", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] DataRoutePromoResponse DataRoutePromo(string Email, string IdPromo, string IdDay); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "ObtieneDatosEmcriptados", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] LoginUserRequest ObtieneDatosEmcriptados(); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "RegisterCheckin", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase RegisterCheckin(RegisterCheckinRequest request); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "RegisterCheckout", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase RegisterCheckout(RegisterCheckoutRequest request); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "RegisterSurvey", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase RegisterSurvey(RegisterSurveyRequest request); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "ResetPassword/{Email}", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase ResetPassword(string Email); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "RegisterSale", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase RegisterSale(RegisterSalesRequest request); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "RegisterAudit", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase RegisterAudit(RegisterAuditRequest request); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "RegisterPlacement", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] ResponseBase RegisterPlacement(RegisterPlacementRequest request); } // Utilice un contrato de datos, como se ilustra en el ejemplo siguiente, para agregar tipos compuestos a las operaciones de servicio. [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } }
using System; namespace AquaServiceSPA.DataModel { public class EmailSettingsTable { public Guid ID { get; set; } public byte[] EncryptedBuffer { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetPayroll.Guides.Common; namespace NetPayroll.Guides.Contract.Employ { public static class OperationsEmploy { public const Int32 TIME_MULTIPLY_SIXTY = 60; public static int WorkingSecondsDaily(int workingHours) { Int32 secondsInHour = (TIME_MULTIPLY_SIXTY * TIME_MULTIPLY_SIXTY); return (workingHours * secondsInHour); } public static int WorkingSecondsWeekly(int workingDays, int workingHours) { Int32 secondsDaily = WorkingSecondsDaily(workingHours); return (workingDays * secondsDaily); } public static uint DateFromInPeriod(Period period, DateTime? dateFrom) { uint dayTermFrom = Period.TERM_BEG_FINISHED; DateTime periodDateBeg = new DateTime((int)period.Year(), (int)period.Month(), 1); if (dateFrom != null) { dayTermFrom = (uint)dateFrom.Value.Day; } if (dateFrom == null || dateFrom < periodDateBeg) { dayTermFrom = 1; } return dayTermFrom; } public static uint DateEndsInPeriod(Period period, DateTime? dateEnds) { uint dayTermEnd = Period.TERM_END_FINISHED; uint daysPeriod = (uint)DateTime.DaysInMonth((int)period.Year(), (int)period.Month()); DateTime periodDateEnd = new DateTime((int)period.Year(), (int)period.Month(), (int)daysPeriod); if (dateEnds != null) { dayTermEnd = (uint)dateEnds.Value.Day; } if (dateEnds == null || dateEnds > periodDateEnd) { dayTermEnd = daysPeriod; } return dayTermEnd; } public static Int32[] WeekSchedule(Period period, Int32 secondsWeekly, Int32 workdaysWeekly) { Int32 secondsDaily = (secondsWeekly / Math.Min(workdaysWeekly, 7)); Int32 secRemainder = secondsWeekly - (secondsDaily * workdaysWeekly); Int32[] weekSchedule = Enumerable.Range(1, 7). Select((x) => (WeekDaySeconds(x, workdaysWeekly, secondsDaily, secRemainder))).ToArray(); return weekSchedule; } private static Int32 WeekDaySeconds(int dayOrdinal, int daysOfWork, Int32 secondsDaily, Int32 secRemainder) { if (dayOrdinal < daysOfWork) { return secondsDaily; } else if (dayOrdinal == daysOfWork) { return secondsDaily + secRemainder; } return (0); } public static Int32[] MonthSchedule(Period period, Int32[] weekSchedule) { int daysInMonth = period.DaysInMonth(); int beginDayCwd = period.WeekDayOfMonth(1); Int32[] monthSchedule = Enumerable.Range(1, daysInMonth). Select((x) => (SecondsFromWeekSchedule(period, weekSchedule, x, beginDayCwd))).ToArray(); return monthSchedule; } private static Int32 SecondsFromWeekSchedule(Period period, Int32[] weekSchedule, int dayOrdinal, int beginDayCwd) { int dayOfWeek = DayOfWeekFromOrdinal(dayOrdinal, beginDayCwd); int indexWeek = (dayOfWeek - 1); if (indexWeek < 0 || indexWeek >= weekSchedule.Length) { return 0; } return weekSchedule[indexWeek]; } private static Int32 SecondsFromScheduleSeq(Period period, Int32[] timeTable, int dayOrdinal, uint dayFromOrd, uint dayEndsOrd) { if (dayOrdinal < dayFromOrd || dayOrdinal > dayEndsOrd) { return 0; } int indexTable = (dayOrdinal - (Int32)dayFromOrd); if (indexTable < 0 || indexTable >= timeTable.Length) { return 0; } return timeTable[indexTable]; } private static int DayOfWeekFromOrdinal(int dayOrdinal, int beginDayCwd) { // dayOrdinal 1..31 // beginDayCwd 1..7 // dayOfWeek 1..7 int dayOfWeek = (((dayOrdinal - 1) + (beginDayCwd - 1)) % 7) + 1; return dayOfWeek; } public static Int32[] TimesheetSchedule(Period period, Int32[] monthSchedule, uint dayOrdFrom, uint dayOrdEnds) { Int32[] timeSheet = monthSchedule.Select((x, i) => (HoursFromCalendar(dayOrdFrom, dayOrdEnds, i, x))).ToArray(); return timeSheet; } public static Int32[] TimesheetAbsence(Period period, Int32[] absenceSchedule, uint dayOrdFrom, uint dayOrdEnds) { int daysInMonth = period.DaysInMonth(); Int32[] monthSchedule = Enumerable.Range(1, daysInMonth). Select((x) => (SecondsFromScheduleSeq(period, absenceSchedule, x, dayOrdFrom, dayOrdEnds))).ToArray(); return monthSchedule; } private static int HoursFromCalendar(uint dayOrdFrom, uint dayOrdEnds, int dayIndex, Int32 workSeconds) { int dayOrdinal = dayIndex + 1; int workingDay = workSeconds; if (dayOrdFrom > dayOrdinal) { workingDay = 0; } if (dayOrdEnds < dayOrdinal) { workingDay = 0; } return workingDay; } public static Int32 TotalTimesheetHours(Int32[] monthTimesheet) { if (monthTimesheet == null) { return 0; } Int32 timesheetHours = monthTimesheet.Aggregate(0, (agr, dh) => (agr + dh)); return timesheetHours; } } }
using UnityEngine; using System.Collections; using uAdventure.Core; namespace uAdventure.Editor { public interface ConditionEditor { void draw(Condition c); bool manages(Condition c); string conditionName(); Condition InstanceManagedCondition(); bool Collapsed { get; set; } bool Available { get; } Rect Window { get; set; } } }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet; using System; using System.Management.Automation; namespace NtObjectManager.Cmdlets.Object { /// <summary> /// <para type="synopsis">Set a NT token on a process or thread.</para> /// <para type="description">This cmdlet sets a token on a process or thread.</para> /// </summary> /// <example> /// <code>Set-NtToken -Token $token -Process $process</code> /// <para>Set a process' primary token.</para> /// </example> /// <example> /// <code>Set-NtToken -Token $token -Process $process -Duplicate</code> /// <para>Set a process' primary token, duplicating it before use.</para> /// </example> /// <example> /// <code>Set-NtToken -Token $token -ProcessId 1234</code> /// <para>Set a process' primary token from its PID.</para> /// </example> /// <example> /// <code>Set-NtToken -Token $token -Thread $thread</code> /// <para>Set a thread's impersonation token.</para> /// </example> /// <example> /// <code>Set-NtToken -Token $token -Thread $thread -Duplicate -ImpersonationLevel Identification</code> /// <para>Set a thread's impersonation token, duplicating as an Identification level token first..</para> /// </example> /// <example> /// <code>Set-NtToken -Token $token -ThreadId 1234</code> /// <para>Set a thread's impersonation token from its TID.</para> /// </example> /// <para type="link">about_ManagingNtObjectLifetime</para> [Cmdlet(VerbsCommon.Set, "NtToken", DefaultParameterSetName = "Process")] public class SetNtTokenCmdlet : PSCmdlet { /// <summary> /// <para type="description">Specify the process to set the token on.</para> /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = "Process")] public NtProcess Process { get; set; } /// <summary> /// <para type="description">Specify the process to set the token on.as a PID.</para> /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = "ProcessId"), Alias("pid")] public int ProcessId { get; set; } /// <summary> /// <para type="description">Specify the thread to set the token on.</para> /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = "Thread")] public NtThread Thread { get; set; } /// <summary> /// <para type="description">Specify the thread to set the token on as a TID.</para> /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ThreadId"), Alias("tid")] public int ThreadId { get; set; } /// <summary> /// <para type="description">Duplicate the token before setting it.</para> /// </summary> [Parameter] public SwitchParameter Duplicate { get; set; } /// <summary> /// <para type="description">Specify the token to set.</para> /// </summary> [Parameter(Mandatory = true, Position = 0)] public NtToken Token { get; set; } /// <summary> /// <para type="description">Specify the impersonation level of the token to assign if -Duplicate is specified.</para> /// </summary> [Parameter(ParameterSetName = "Thread"), Parameter(ParameterSetName = "ThreadId")] public SecurityImpersonationLevel ImpersonationLevel { get; set; } /// <summary> /// <para type="description">Specify the integrity level of the token to set if -Duplicate is specified.</para> /// </summary> [Parameter] public TokenIntegrityLevel? IntegrityLevel { get; set; } private bool IsProcess() { switch (ParameterSetName) { case "Process": case "ProcessId": return true; case "Thread": case "ThreadId": return false; default: throw new ArgumentException("Invalid parameter set."); } } private NtToken GetToken() { if (!Duplicate) return Token.Duplicate(); TokenType type = IsProcess() ? TokenType.Primary : TokenType.Impersonation; using (var token = Token.DuplicateToken(type, ImpersonationLevel, TokenAccessRights.MaximumAllowed)) { if (IntegrityLevel.HasValue) { token.IntegrityLevel = IntegrityLevel.Value; } return token.Duplicate(); } } private NtProcess GetProcess() { if (ParameterSetName == "Process") return Process.Duplicate(ProcessAccessRights.SetInformation); return NtProcess.Open(ProcessId, ProcessAccessRights.SetInformation); } private NtThread GetThread() { if (ParameterSetName == "Thread") return Thread.Duplicate(ThreadAccessRights.Impersonate); return NtThread.Open(ThreadId, ThreadAccessRights.Impersonate); } /// <summary> /// Overridden ProcessRecord method. /// </summary> protected override void ProcessRecord() { using (var token = GetToken()) { if (IsProcess()) { using (var proc = GetProcess()) { proc.SetToken(token); } } else { using (var thread = GetThread()) { thread.Impersonate(token); } } } } } }
namespace ns20 { using System; using System.Runtime.CompilerServices; internal class Class180 { [CompilerGenerated] private Enum17 enum17_0; [CompilerGenerated] private Type type_0; public Enum17 Enum17_0 { [CompilerGenerated] get { return this.enum17_0; } [CompilerGenerated] set { this.enum17_0 = value; } } public Type Type_0 { [CompilerGenerated] get { return this.type_0; } [CompilerGenerated] set { this.type_0 = value; } } } }
using MovieLibrary2.Model; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace MovieLibrary2.DataManagement { public static class MovieDataDownloader { public static void DownloadMovieData(Movie movie) { string posterURL = TheMovieDBParser(movie); //string posterURL = OMDBApiParser(Movie); if (File.Exists(movie.ImagePath)) { return; } movie.ImagePath = FileFinder.GetExistingImage(movie.GetImageSavePath()); if (movie.ImagePath != null) { return; } else if (posterURL != null && posterURL != string.Empty && posterURL != "N/A") { new System.Net.WebClient().DownloadFile(posterURL, movie.GetImageSavePath() + GetImageExtension(posterURL)); movie.ImagePath = movie.GetImageSavePath() + GetImageExtension(posterURL); } } public static string GetImageExtension(string url) { return "." + url.Split('.').Last(); } private static string GetAddressString(Movie movie) { return @"https://api.themoviedb.org/3/search/movie?" + $"api_key={MovieLibrary2.Properties.Settings.Default.MovieDBAPIKey}" + $"&query={movie.Title}" + ((movie.Year != -1) ? $"&primary_release_year={movie.Year}" : ""); } public static string TheMovieDBParser(Movie movie) { string posterURL = null; using (var WebClient = new System.Net.WebClient()) { try { string addressString = GetAddressString(movie); var requestResult = WebClient.DownloadString(addressString); JObject json = JObject.Parse(requestResult); if (json.Property("results") == null) return null; List<JToken> tokens = json["results"].Children().ToList(); if (tokens == null || tokens.Count == 0) return null; string movieDBID = tokens[0]["id"].ToString(); string movieQueryString = @"https://api.themoviedb.org/3/movie/" + $"{movieDBID}" + $"?api_key={MovieLibrary2.Properties.Settings.Default.MovieDBAPIKey}"; requestResult = WebClient.DownloadString(movieQueryString); json = JObject.Parse(requestResult); if (tokens != null && tokens.Count > 0) { movie.IMDbID = json["imdb_id"].ToString(); movie.Description = json["overview"].ToString(); movie.UserRating = json["vote_average"].ToString(); movie.Runtime = (int)json["runtime"]; posterURL = @"https://image.tmdb.org/t/p/w500" + json["poster_path"].ToString(); } } catch (NullReferenceException ex) { Console.WriteLine("ERROR: " + ex.Message); } catch (WebException ex) { Console.WriteLine("ERROR: " + ex.Message); } } return posterURL; } public static string OMDBApiParser(Movie movie) { string posterURL = null; using (var WebClient = new System.Net.WebClient()) { try { string addressString = @"http://www.omdbapi.com/?s=" + movie.Title; addressString += (movie.Year != -1) ? "&y=" + movie.Year : ""; var str = WebClient.DownloadString(addressString); JObject json = JObject.Parse(str); if (json.Property("Search") != null) { List<JToken> tokens = json["Search"].Children().ToList(); foreach (JToken t in tokens) { posterURL = (string)t["Poster"]; break; } } } catch (NullReferenceException ex) { Console.WriteLine("ERROR: " + ex.Message); } catch (WebException ex) { Console.WriteLine("ERROR: " + ex.Message); } } return posterURL; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ArenaBase; namespace Arena { public class MapBuilder { public ArenaMap SimpleSquareMap(int width, int height) { ArenaMap map = new ArenaMap(); CreateBorderWalls(width, height, map); // FillWithFloor(width, height, map); return map; } private void CreateBorderWalls(int width, int height, ArenaMap map) { for (int i = 0; i < width; i++) { for(int j=0; j < height; j++) { if (i == 0 || i == width-1 || j == 0 || j == height-1) { map.Map.Add(new ArenaTile() { Icon = '#', Location = Coordinates.NewCoord(i, j), Passable = false, Immovable = false, Name = "Stone wall" }); } else { map.Map.Add(new ArenaTile() { Icon = '.', Location = Coordinates.NewCoord(i, j), Passable = true, Immovable = false, Name = "Floor" }); } } } } private void FillWithFloor(int width, int height, ArenaMap map) { for (int i = 1; i < width-1; i++) { for (int j = 1; j < height-1; j++) { } } } } }
using System; using System.Collections.Generic; using JetBrains.Annotations; using RoR2; using RoR2.Networking; using TridevLoader.Mod.API; using TridevLoader.Mod.API.Item; using UnityEngine.Networking; namespace TridevLoader.Core.Game.Modded { public class ModdedInventory : Inventory { //public readonly List<int> itemCounts; //public readonly Dictionary<ModObjectId, int> moddedItemAcquisitionOrder = new Dictionary<ModObjectId, int>(); // //public ModdedInventory() { // this.itemCounts = new List<int>(ModItemRegistry.Instance.GetItemIds().Count); //} // //private void Start() { // if (!NetworkServer.active || !Run.instance.enabledArtifacts.HasArtifact(ArtifactIndex.Enigma)) // return; // this.SetEquipmentIndex(EquipmentIndex.Enigma); //} // //[Server] //public void GiveModdedItemByName(string itemString) { // var modObjectId = new ModObjectId(itemString); // if (!NetworkServer.active) // return; // if (modObjectId.ModId.Equals(VanillaMod.Id)) { // base.GiveItemString(itemString); // } else { // this.GiveModdedItem(modObjectId); // } //} // //[Server] //public void GiveModdedItem(ModObjectId id, int count = 1) { // if (!NetworkServer.active) // return; // // if (count <= 0) { // if (count >= 0) // return; // this.RemoveModdedItem(id, -count); // } else { // this.SetDirtyBit(1U); // if ((this.itemCounts[(int) itemIndex] += count) == count) { // this.itemAcquisitionOrder.Add(itemIndex); // this.SetDirtyBit(8U); // } // // Action inventoryChanged = this.onInventoryChanged; // if (inventoryChanged != null) // inventoryChanged(); // Action<Inventory, ItemIndex, int> onServerItemGiven = Inventory.onServerItemGiven; // if (onServerItemGiven != null) // onServerItemGiven(this, itemIndex, count); // this.CallRpcItemAdded(itemIndex); // } //} // //public static event Action<Inventory, ItemIndex, int> onServerItemGiven; // //[ClientRpc] //private void RpcItemAdded(ItemIndex itemIndex) { // this.StartCoroutine(this.HighlightNewItem(itemIndex)); //} // //[Server] //public void RemoveModdedItem(ModObjectId id, int count = 0) { // if (!NetworkServer.active) // Debug.LogWarning((object) "[Server] function 'System.Void RoR2.Inventory::RemoveItem(RoR2.ItemIndex,System.Int32)' called on client"); // else if (count <= 0) { // if (count >= 0) // return; // this.GiveModdedItem(id, -count); // } else { // int itemStack = this.itemCounts[(int) itemIndex]; // count = Math.Min(count, itemStack); // if (count == 0) // return; // if ((this.itemCounts[(int) itemIndex] = itemStack - count) == 0) { // this.itemAcquisitionOrder.Remove(itemIndex); // this.SetDirtyBit(8U); // } // // this.SetDirtyBit(1U); // Action inventoryChanged = this.onInventoryChanged; // if (inventoryChanged == null) // return; // inventoryChanged(); // } //} // //[Server] //public void ResetItem(ItemIndex itemIndex) { // if (!NetworkServer.active) { // Debug.LogWarning((object) "[Server] function 'System.Void RoR2.Inventory::ResetItem(RoR2.ItemIndex)' called on client"); // } else { // if (this.itemCounts[(int) itemIndex] <= 0) // return; // this.itemCounts[(int) itemIndex] = 0; // this.SetDirtyBit(1U); // this.SetDirtyBit(8U); // Action inventoryChanged = this.onInventoryChanged; // if (inventoryChanged == null) // return; // inventoryChanged(); // } //} // //[Server] //public void CopyEquipmentFrom(Inventory other) { // if (!NetworkServer.active) { // Debug.LogWarning((object) "[Server] function 'System.Void RoR2.Inventory::CopyEquipmentFrom(RoR2.Inventory)' called on client"); // } else { // for (int index = 0; index < other.equipmentStateSlots.Length; ++index) // this.SetEquipment(new EquipmentState(other.equipmentStateSlots[index].equipmentIndex, Run.FixedTimeStamp.negativeInfinity, 1), (uint) index); // } //} // //[Server] //public void CopyItemsFrom(Inventory other) { // if (!NetworkServer.active) { // Debug.LogWarning((object) "[Server] function 'System.Void RoR2.Inventory::CopyItemsFrom(RoR2.Inventory)' called on client"); // } else { // other.itemStacks.CopyTo((Array) this.itemCounts, 0); // this.itemAcquisitionOrder.Clear(); // this.itemAcquisitionOrder.AddRange(other.itemAcquisitionOrder); // this.SetDirtyBit(1U); // this.SetDirtyBit(8U); // Action inventoryChanged = this.onInventoryChanged; // if (inventoryChanged == null) // return; // inventoryChanged(); // } //} // //[Server] //public void ShrineRestackInventory([NotNull] Xoroshiro128Plus rng) { // if (!NetworkServer.active) { // Debug.LogWarning((object) "[Server] function 'System.Void RoR2.Inventory::ShrineRestackInventory(Xoroshiro128Plus)' called on client"); // } else { // List<ItemIndex> itemIndexList1 = new List<ItemIndex>(); // List<ItemIndex> itemIndexList2 = new List<ItemIndex>(); // List<ItemIndex> itemIndexList3 = new List<ItemIndex>(); // List<ItemIndex> itemIndexList4 = new List<ItemIndex>(); // List<ItemIndex> itemIndexList5 = new List<ItemIndex>(); // List<ItemIndex> itemIndexList6 = new List<ItemIndex>(); // int count1 = 0; // int count2 = 0; // int count3 = 0; // int count4 = 0; // int count5 = 0; // for (int index = 0; index < this.itemCounts.Length; ++index) { // ItemIndex itemIndex = (ItemIndex) index; // if (this.itemCounts[index] > 0) { // switch (ItemCatalog.GetItemDef(itemIndex).tier) { // case ItemTier.Tier1: // count1 += this.itemCounts[index]; // itemIndexList1.Add(itemIndex); // break; // case ItemTier.Tier2: // count2 += this.itemCounts[index]; // itemIndexList2.Add(itemIndex); // break; // case ItemTier.Tier3: // count3 += this.itemCounts[index]; // itemIndexList3.Add(itemIndex); // break; // case ItemTier.Lunar: // count4 += this.itemCounts[index]; // itemIndexList4.Add(itemIndex); // break; // case ItemTier.Boss: // count5 += this.itemCounts[index]; // itemIndexList5.Add(itemIndex); // break; // } // } // // this.ResetItem(itemIndex); // } // // ItemIndex itemIndex1 = itemIndexList1.Count == 0 ? ItemIndex.None : itemIndexList1[rng.RangeInt(0, itemIndexList1.Count)]; // ItemIndex itemIndex2 = itemIndexList2.Count == 0 ? ItemIndex.None : itemIndexList2[rng.RangeInt(0, itemIndexList2.Count)]; // ItemIndex itemIndex3 = itemIndexList3.Count == 0 ? ItemIndex.None : itemIndexList3[rng.RangeInt(0, itemIndexList3.Count)]; // ItemIndex itemIndex4 = itemIndexList4.Count == 0 ? ItemIndex.None : itemIndexList4[rng.RangeInt(0, itemIndexList4.Count)]; // ItemIndex itemIndex5 = itemIndexList5.Count == 0 ? ItemIndex.None : itemIndexList5[rng.RangeInt(0, itemIndexList5.Count)]; // this.itemAcquisitionOrder.Clear(); // this.SetDirtyBit(8U); // this.GiveItem(itemIndex1, count1); // this.GiveItem(itemIndex2, count2); // this.GiveItem(itemIndex3, count3); // this.GiveItem(itemIndex4, count4); // this.GiveItem(itemIndex5, count5); // } //} // //public int GetItemCount(ItemIndex itemIndex) { // return this.itemCounts[(int) itemIndex]; //} // //public bool HasAtLeastXTotalItemsOfTier(ItemTier itemTier, int x) { // int num = 0; // for (ItemIndex itemIndex = ItemIndex.Syringe; itemIndex < ItemIndex.Count; ++itemIndex) { // if (ItemCatalog.GetItemDef(itemIndex).tier == itemTier) { // num += this.GetItemCount(itemIndex); // if (num >= x) // return true; // } // } // // return false; //} // //public int GetTotalItemCountOfTier(ItemTier itemTier) { // int num = 0; // for (ItemIndex itemIndex = ItemIndex.Syringe; itemIndex < ItemIndex.Count; ++itemIndex) { // if (ItemCatalog.GetItemDef(itemIndex).tier == itemTier) // num += this.GetItemCount(itemIndex); // } // // return num; //} // //public void WriteItemStacks(int[] output) { // Array.Copy((Array) this.itemCounts, output, output.Length); //} // //public override int GetNetworkChannel() { // return QosChannelIndex.defaultReliable.intVal; //} // //public override void OnDeserialize(NetworkReader reader, bool initialState) { // int num1 = reader.ReadByte(); // bool flag1 = (uint) (num1 & 1) > 0U; // bool flag2 = (uint) (num1 & 4) > 0U; // bool flag3 = (uint) (num1 & 8) > 0U; // bool flag4 = (uint) (num1 & 16) > 0U; // if (flag1) // reader.ReadItemStacks(this.itemCounts); // if (flag2) // this.infusionBonus = reader.ReadPackedUInt32(); // if (flag3) { // byte num2 = reader.ReadByte(); // this.itemAcquisitionOrder.Clear(); // this.itemAcquisitionOrder.Capacity = num2; // for (byte index = 0; (int) index < (int) num2; ++index) // this.itemAcquisitionOrder.Add((ItemIndex) reader.ReadByte()); // } // // if (flag4) { // uint num2 = reader.ReadByte(); // for (uint slot = 0; slot < num2; ++slot) // this.SetEquipmentInternal(EquipmentState.Deserialize(reader), slot); // this.activeEquipmentSlot = reader.ReadByte(); // } // // if (!(flag1 | flag4 | flag2)) // return; // Action inventoryChanged = this.onInventoryChanged; // if (inventoryChanged == null) // return; // inventoryChanged(); //} // //public override bool OnSerialize(NetworkWriter writer, bool initialState) { // uint num1 = this.syncVarDirtyBits; // if (initialState) // num1 = 17U; // for (int index = 0; index < this.equipmentStateSlots.Length; ++index) { // if (this.equipmentStateSlots[index].dirty) { // num1 |= 16U; // break; // } // } // // int num2 = (num1 & 1U) > 0U ? 1 : 0; // bool flag1 = (num1 & 4U) > 0U; // bool flag2 = (num1 & 8U) > 0U; // bool flag3 = (num1 & 16U) > 0U; // writer.Write((byte) num1); // if (num2 != 0) // writer.WriteItemStacks(this.itemCounts); // if (flag1) // writer.WritePackedUInt32(this.infusionBonus); // if (flag2) { // byte count = (byte) this.itemAcquisitionOrder.Count; // writer.Write(count); // for (byte index = 0; (int) index < (int) count; ++index) // writer.Write((byte) this.itemAcquisitionOrder[index]); // } // // if (flag3) { // writer.Write((byte) this.equipmentStateSlots.Length); // for (int index = 0; index < this.equipmentStateSlots.Length; ++index) // EquipmentState.Serialize(writer, this.equipmentStateSlots[index]); // writer.Write(this.activeEquipmentSlot); // } // // if (!initialState) { // for (int index = 0; index < this.equipmentStateSlots.Length; ++index) // this.equipmentStateSlots[index].dirty = false; // } // // if (!initialState) // return num1 > 0U; // return false; //} // //protected static void InvokeRpcRpcItemAdded(NetworkBehaviour obj, NetworkReader reader) { // if (!NetworkClient.active) // Debug.LogError((object) "RPC RpcItemAdded called on server."); // else // ((Inventory) obj).RpcItemAdded((ItemIndex) reader.ReadInt32()); //} // //public void CallRpcItemAdded(ItemIndex itemIndex) { // if (!NetworkServer.active) { // Debug.LogError((object) "RPC Function RpcItemAdded called on client."); // } else { // NetworkWriter writer = new NetworkWriter(); // writer.Write((short) 0); // writer.Write((short) 2); // writer.WritePackedUInt32((uint) Inventory.kRpcRpcItemAdded); // writer.Write(this.GetComponent<NetworkIdentity>().netId); // writer.Write((int) itemIndex); // this.SendRPCInternal(writer, 0, "RpcItemAdded"); // } //} // //static ModdedInventory() { // RegisterRpcDelegate(typeof(Inventory), Inventory.kRpcRpcItemAdded, new CmdDelegate(Inventory.InvokeRpcRpcItemAdded)); // NetworkCRC.RegisterBehaviour(nameof(Inventory), 0); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using POG.Utils; using POG.Forum; using System.Diagnostics; using System.Windows.Forms; using POG.Werewolf; using System.Text.RegularExpressions; namespace TatianaTiger { class SubInfo { public String Out { get; private set; } public String In { get; private set; } public DateTime Time { get; private set; } public Int32 Post { get; private set; } public SubInfo(String outPlayer, String inPlayer, DateTime time, Int32 post) { Out = outPlayer; In = inPlayer; Time = time; Post = post; } } class GameStarter : StateMachine { #region consts readonly String WOLF = "Wolf"; readonly String VILLAGE = "Village"; readonly String VANILLA = "vanilla"; readonly String SEER = "seer"; #endregion #region fields VBulletinForum _forum; private POG.Werewolf.IPogDb _db; System.Timers.Timer _timer = new System.Timers.Timer(); System.Timers.Timer _timerPM = new System.Timers.Timer(); DateTimeOffset _EarliestPMTime = DateTimeOffset.Now; DateTimeOffset _maxTime = DateTimeOffset.MaxValue; Int32 _lastPMProcessed = 0; PrivateMessage _requestPM; List<String> _requestNames; List<String> _validNames = new List<string>(); List<String> _canPM = new List<string>(); List<String> _PMSent = new List<string>(); List<Player> _playerRoles = new List<Player>(); List<Player> _peeks = new List<Player>(); Dictionary<String, Player> _playerByName = new Dictionary<string,Player>(); List<SubInfo> _subs = new List<SubInfo>(); Player _peek; String _killMessage; DateTime _nextNight; int _d1Duration; int _dDuration; int _n1Duration; int _nDuration; Int32 _threadId = 1204368; String _url = "http://forumserver.twoplustwo.com/59/puzzles-other-games/vote-counter-testing-thread-1204368/"; Boolean _majorityLynch = false; ElectionInfo _count; private POG.Werewolf.AutoComplete _autoComplete; int _pendingLookups = 0; #endregion public GameStarter(VBulletinForum forum, StateMachineHost host, POG.Werewolf.IPogDb db, POG.Werewolf.AutoComplete autoComplete) : base("GameStarter", host) { _forum = forum; _db = db; _autoComplete = autoComplete; _timer.AutoReset = false; _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); _timerPM.AutoReset = false; _timerPM.Elapsed += new System.Timers.ElapsedEventHandler(_timerPM_Elapsed); _EarliestPMTime = _EarliestPMTime.AddMinutes(-1); SetInitialState(StateIdle); } void _timerPM_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { PostEvent(new Event("SendPMTimer")); } #region states State StateTop(Event e) { switch (e.EventName) { case "EventEnter": { _timer.Interval = GetTimerInterval(); _timer.Start(); } break; case "EventExit": { _timer.Stop(); _timerPM.Stop(); } break; case "SendPMTimer": { UnqueuePM(); } break; case "DelayedPost": { Event<String, String, Boolean> evtPost = e as Event<String, String, Boolean>; MakePost(evtPost.Param1, evtPost.Param2, evtPost.Param3); } return null; } return null; } State StateIdle(Event e) { switch (e.EventName) { case "EventMinute": { PollPMs(); } break; case "StrangerPM": { Event<PrivateMessage> pme = e as Event<PrivateMessage>; String msg = pme.Param.Content; List<String> rawList = msg.Split( new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Trim()) .Distinct().OrderBy(p => p.ToUpper()).ToList(); _validNames.Clear(); _requestNames = rawList; _requestPM = pme.Param; CheckNames(); ChangeState(StateStartGameRequested); } break; } return StateTop; } String _threadTitle; State StateStartGameRequested(Event e) { switch (e.EventName) { case "EventEnter": { } break; case "EventExit": { } break; case "NamesChecked": { if (_validNames.Count != 9) { ReplyFailure(_requestPM, _requestNames, _validNames, "In order to start a turbo I need a PM with exactly 9 names; one name on each line."); ChangeState(StateIdle); } else { String title = ""; foreach(string request in _requestNames) { if (request.ToLowerInvariant().Trim().StartsWith("title")) { title = request.Trim().Substring("title".Length).Trim(); } } if (title.Length == 0) { title = String.Format("{0:yy.MM.dd HH:mm}", DateTime.Now.ToUniversalTime()); QueueAnnouncement("Next time give your turbo a title by including 'title MY CUSTOM TITLE' as the first line of your PM."); } title = title.Trim(); if (!title.ToLowerInvariant().StartsWith("turbo: ")) { title = "Turbo: " + title; } if (title.Length > 80) title = title.Substring(0, 80); _threadTitle = title; if (CheckCanReceivePM()) { PostEvent(new Event("Rand")); } else { ReplyFailure(_requestPM, _validNames, _canPM, "Some players can't receive PMs. They need to clear space or join pog messages group."); ChangeState(StateIdle); } } } break; case "PostOP": { ReplyFailure(_requestPM, new List<String>(), _canPM, "So far so good!"); ChangeState(StateIdle); } break; case "Rand": { int i; Player p; for (i = 1; i < 3; i++) { String wolf = Misc.RandomItemFromList(_canPM); p = new Player(i, false, wolf, WOLF, VANILLA); _playerRoles.Add(p); _canPM.Remove(wolf); } String seer = Misc.RandomItemFromList(_canPM); p = new Player(i++, false, seer, VILLAGE, SEER); _playerRoles.Add(p); _canPM.Remove(seer); foreach (String vanilla in _canPM) { p = new Player(i++, false, vanilla, VILLAGE, VANILLA); _playerRoles.Add(p); } _canPM.Clear(); foreach (var pr in _playerRoles) { _playerByName[pr.Name] = pr; } Int32 peek = Misc.RandomItemFromRange(4, 10); _peeks.Clear(); _peeks.Add(LookupPlayer(peek)); PostEvent(new Event("SendPMs")); } break; case "SendPMs": { List<String> seers = (from p in _playerRoles where (p.Role == SEER) select p.Name).ToList(); List<String> vanillas = (from p in _playerRoles where (p.Team == VILLAGE) && (p.Role == VANILLA) select p.Name).ToList(); List<string> wolves = (from p in _playerRoles where p.Team == WOLF select p.Name).ToList(); String seerMsg = MakeSeerPmMessage(); String wolfMsg = MakeWolfPmMessage(); String vanillaMsg = MakeVanillaPmMessage(); PrivateMessage pmSeer = new PrivateMessage(null, seers, "Turbo Role PM", seerMsg); PrivateMessage pmWolf = new PrivateMessage(wolves, null, "Turbo Role PM", wolfMsg); PrivateMessage pmVanilla = new PrivateMessage(null, vanillas, "Turbo Role PM", vanillaMsg); List<PrivateMessage> pms = new List<PrivateMessage>(); pms.Add(pmSeer); pms.Add(pmWolf); pms.Add(pmVanilla); PrivateMessage pm = Misc.RandomItemFromList(pms); pms.Remove(pm); QueuePM(pm); pm = Misc.RandomItemFromList(pms); pms.Remove(pm); QueuePM(pm); pm = Misc.RandomItemFromList(pms); QueuePM(pm); ChangeState(StateNight0); } break; } return StateTop; } String MakePMIntro() { String welcome = "Hello, I am Tatiana Tiger, your automated moderator." + "You are playing a game of werewolf, this is your role PM.\r\n\r\n"; string rc = String.Format("{0} The game thread has the title '{1}'.\r\n\r\n", welcome, _threadTitle); return rc; } String MakeSeerPmMessage() { String peek = _peeks[0].Name; String seerMsg = MakePMIntro() + String.Format("You are the seer. Your random n0 villager peek is {0}\r\n", peek); seerMsg += "\r\nEach night send a PM with the exact name of the player you want to peek.\r\n"; return seerMsg; } String MakeWolfPmMessage() { List<string> wolves = (from p in _playerRoles where p.Team == WOLF select p.Name).ToList(); String wolfMsg = MakePMIntro() + "You are the wolves:\r\n"; foreach (var w in wolves) { wolfMsg += w + "\r\n"; } wolfMsg += "\r\nYou can communicate with each other outside the thread [b]at night only[/b]."; wolfMsg += " During the day the game is played only by posting inside the thread."; wolfMsg += "\r\nEach night send a PM with the exact name of the player you want to kill.\r\n"; wolfMsg += "If the game is hopeless send a PM that only says 'resign'."; return wolfMsg; } String MakeVanillaPmMessage() { String rc = MakePMIntro() + "You are a vanilla villager."; return rc; } Boolean _hyper = false; State StatePlaying(Event e) { switch (e.EventName) { case "EventEnter": { } break; case "EventExit": { _peeks.Clear(); _playerByName.Clear(); _playerRoles.Clear(); _requestNames.Clear(); _subs.Clear(); _peek = null; _killMessage = ""; //_threadId _majorityLynch = false; _count = null; _day = 0; _kill = ""; lock (_pmQueue) { _pmQueue.Clear(); } _EarliestPMTime = TruncateSeconds(DateTime.Now); } break; case "CorrectionPM": { PrivateMessage pm = (e as Event<PrivateMessage>).Param; List<String> rawList = pm.Content.Split( new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Trim()) .Distinct().ToList(); StringBuilder reply = new StringBuilder(); foreach (var line in rawList) { Match m = Regex.Match(pm.Content, "(.*)=(.*)"); if (m.Success) { String l = m.Groups[1].Value.Trim(); String r = m.Groups[2].Value.Trim(); var leftPlayer = LookupPlayer(l); var rightPlayer = LookupPlayer(r); if ((leftPlayer == null) && (rightPlayer == null)) { reply.AppendFormat("failure: neither '{0}' nor '{1}' is a recognized player.\r\n", l, r); continue; } if ((leftPlayer != null) && (rightPlayer != null)) { reply.AppendFormat("failure: both '{0}' and '{1}' are players.\r\n", l, r); continue; } var p = (leftPlayer != null) ? leftPlayer : rightPlayer; String nickname = (leftPlayer == null) ? l : r; if (_count != null) { _count.AddVoteAlias(nickname, p.Name); reply.AppendFormat("success: '{0}' now means {1}.\r\n", nickname, p.Name); continue; } reply.AppendFormat("failure: there is no game right now."); break; } else { reply.AppendFormat("no '=' so ignoring line '{0}'", line); } } if (reply.Length == 0) { reply.AppendLine("Your pm had 'correction' in the title, but no corrections were found."); reply.AppendLine("format: bolded=playername, one correction on each line."); } QueuePM(new String[] { pm.From }, "Vote Correction Results", reply.ToString()); } break; case "StrangerPM": { PrivateMessage pm = (e as Event<PrivateMessage>).Param; QueuePM(new string[] { pm.From }, pm.Title, String.Format("Thank you for your pm. Unfortunately, I am currently busy auto-modding this game:{0}.", _url)); } break; case "SubPM": { PrivateMessage pm = (e as Event<PrivateMessage>).Param; var role = ParseSubPM(pm); if (role == null) { QueuePM(new string[] { pm.From }, pm.Title, String.Format("I couldn't find the player you are asking to sub in for: '{0}'", pm.Content)); break; } Player oldRole = LookupPlayer(pm.From); if (oldRole != null) { if (oldRole != role) { QueuePM(new string[] { pm.From }, pm.Title, String.Format("Sorry, I can't sub you back in.")); break; } } List<String> notify = new List<string>() { role.Name, pm.From }; StringBuilder sb = new StringBuilder(); String subMsg = String.Format("[b]{0}[/b] is subbing in for [b]{1}[/b]\n\n", pm.From, role.Name); var sub = new SubInfo(role.Name, pm.From, DateTime.Now, _count.LastPost); _subs.Add(sub); _count.SubPlayer(role.Name, pm.From); _playerByName[pm.From] = role; role.Name = pm.From; QueueAnnouncement(subMsg); sb.AppendLine(subMsg); sb.AppendLine("Role Info:\n"); if (role.Team == WOLF) { sb.AppendLine(MakeWolfPmMessage()); } else { if (role.Role == SEER) { sb.AppendLine(MakeSeerPmMessage()); sb.AppendLine("\r\n[u]Peeks:[/u]\r\n"); foreach (var peek in _peeks) { sb.AppendFormat("{0} : {1} {2}\r\n", peek.Name, peek.Team, peek.Role); } } else { sb.AppendLine(MakeVanillaPmMessage()); } } sb.AppendLine().AppendFormat("If you do not wish to sub out, sub back in by sending a PM with title sub and body {0}", sub.In); PrivateMessage pmSub = new PrivateMessage(notify, null, "Substitution in Turbo", sb.ToString()); QueuePM(pmSub); } break; case "DeadPM": { PrivateMessage pm = (e as Event<PrivateMessage>).Param; QueuePM(new string[] { pm.From }, pm.Title, "Thank you for your pm. Unfortunately, you are dead in this game so I can't help you."); } break; case "WolfResignPM": { PrivateMessage pm = (e as Event<PrivateMessage>).Param; String msg = String.Format("{0} has resigned for the wolves. The village wins.", pm.From); PostEvent(new Event<String>("GameOver", msg)); } break; case "GameOver": { String msg = (e as Event<String>).Param; var live = from p in _playerRoles where p.Dead == false select p; StringBuilder sb = new StringBuilder(); sb.AppendLine(msg); sb.AppendLine("\r\n\r\n[u]Remaining Players:[/u]\r\n"); foreach (var p in live) { sb.AppendFormat("{0} : {1} {2}\r\n", p.Name, p.Team, p.Role); KillPlayer(p.Name); } sb.AppendLine("\r\n\r\n[u]Peeks:[/u]\r\n"); foreach (var p in _peeks) { sb.AppendFormat("{0} : {1} {2}\r\n", p.Name, p.Team, p.Role); } _forum.LockThread(_threadId, false); MakePost("Mod: Game Over", sb.ToString()); ChangeState(StateIdle); } break; } return StateTop; } State StateNight0(Event e) { switch(e.EventName) { case "EventEnter": { _majorityLynch = false; if (_forum.Username.Equals("Oreos", StringComparison.InvariantCultureIgnoreCase)) { _hyper = true; _d1Duration = 4; _dDuration = 3; _n1Duration = 3; _nDuration = 3; } else { _hyper = false; _d1Duration = 18; _dDuration = 17; _n1Duration = 7; _nDuration = 4; } } break; case "EventExit": { } break; case "EventMinute": { if (_pmQueue.Count == 0) { SetDayDuration(); if (AnnounceDay(0)) { ChangeState(StateDay); } // else try again next minute... } } return null; } return StatePlaying; } State StateResign(Event e) { return StatePlaying; } Int32 _day = 0; Int32 _lastCountPostNumber; DateTime _lastCountTime; List<String> _lastCountLeaders = new List<string>(); Boolean _missingPlayers = false; State StateDay(Event e) { switch (e.EventName) { case "EventEnter": { _lastCountPostNumber = 0; _lastCountTime = DateTime.MinValue; _lastCountLeaders.Clear(); _day++; AnnounceDay(_day); _count.SetDayBoundaries(_day, _count.LastPost + 1, _nextNight); _count.ChangeDay(_day); } break; case "EventExit": { } break; case "EventMinute": { if (_count != null) { Trace.TraceInformation("another minute, need a vote count."); _count.CheckThread(() => { PostEvent(new Event("CountUpdated")); }); } PollPMs(); } return null; case "CountUpdated": { Trace.TraceInformation("Deciding to post another vote count."); String announce = GetAnnouncements(); String postableCount = announce + _count.GetPostableVoteCount(); Int32 count; List<String> leaders = _count.GetVoteLeaders(out count).ToList(); DateTime now = DateTime.Now; now = TruncateSeconds(now); if ((now > _nextNight) || (count >= GetMajorityCount())) { String lynch = Misc.RandomItemFromList(leaders); Player player = KillPlayer(lynch); String teamColor = player.Team == VILLAGE ? "green" : "red"; String roleColor = player.Role == SEER ? "purple" : teamColor; String result = (leaders.Count > 1) ? "The lynch was randed to break a tie.\r\n" : ""; result += String.Format( "[b]{0}[/b] was lynched. Team: [color={1}][b]{2}[/b][/color] Role: [color={3}][b]{4}[/b][/color]\r\n", player.Name, teamColor, player.Team, roleColor, player.Role); String winner = ""; if (WolfCount == 0) { winner = "[color=green][b]Village Wins![/b][/color]\r\n"; } else { if (WolfCount >= (LiveCount - WolfCount - 1)) { winner = "[color=red][b]Wolves Win![/b][/color]\r\n"; } } String post = postableCount + "\r\n\r\n" + result; if (winner == "") { var postcounts = _count.GetPostCounts(); var missing = from p in postcounts where p.Item2 == 0 select p.Item1; if (missing.Any()) { _missingPlayers = true; } else { _missingPlayers = false; } SetNightDuration(); post += "PM your night action or it will be randed.\r\nDeadline: " + MakeGoodBad(_nextDay); post += "\r\n\r\n[b]It is night![/b]"; MakePost("Mod: Lynch result", post, true); ChangeState(StateNightNeedAction); } else { post += winner; PostEvent(new Event<String>("GameOver", post)); } } else { Boolean postCount = false; Int32 lastPost = _count.LastPost; if ((lastPost - _lastCountPostNumber) > 5) { if (((lastPost - 1) / 50) != ((_lastCountPostNumber - 1) / 50)) { // totp! postCount = true; } DateTime realNight = _nextNight.AddMinutes(1); TimeSpan whole = realNight - _lastCountTime; TimeSpan part = now - _lastCountTime; if ((part.TotalSeconds / whole.TotalSeconds) > 0.33) { postCount = true; } } HashSet<String> movers = new HashSet<string>(_lastCountLeaders); movers.SymmetricExceptWith(leaders); if (movers.Any()) { // vote leader changed. postCount = true; } if (announce.Length > 0) { postCount = true; } if (postCount) { _lastCountLeaders = leaders; _lastCountTime = now; _lastCountPostNumber = lastPost + 1; MakePost("Vote Count", postableCount); } if(_day == 4) { var remaining = _nextNight - now; if ((remaining.TotalSeconds < 125) && (remaining.TotalSeconds > 100)) { List<String> lateVoters = new List<string>(); var voters = _count.LivePlayers; foreach (var voter in voters) { switch(voter.Votee.ToLowerInvariant()) { case "": case "unvote": case "error": case "no lynch": case "not voting": { lateVoters.Add(voter.Name); } break; } } if (lateVoters.Count > 0) { PrivateMessage pm = new PrivateMessage(null, lateVoters, "Two Minute Warning", "You have 2 minutes remaining to cast a vote."); SendPM(pm); } } } } } break; } return StatePlaying; } DateTime _nextDay; String _kill; State StateNight(Event e) { switch (e.EventName) { case "EventEnter": { _kill = ""; if (_count != null) { _count.CheckThread(() => // keep reading the thread so we have the right start post. { }); } } break; case "EventExit": { _majorityLynch = true; _count.CheckMajority = true; SetDayDuration(); Int32 villas = SeerCount + VanillaCount; Int32 wolves = WolfCount; if ((wolves + 1) >= villas) { _count.LockedVotes = true; } } break; case "EventMinute": { PollPMs(); if (_count != null) { _count.CheckThread(() => // keep reading the thread so we have the right start post. { //PostEvent(new Event("CountUpdated")); }); } PostEvent(new Event("CheckForTimeout")); } return null; } return StatePlaying; } State StateCallDay(Event e) { switch (e.EventName) { case "EventEnter": { if (_kill == "") { // rand a kill var villagers = (from p in _playerRoles where (p.Dead == false) && (p.Team == VILLAGE) select p); var kill = Misc.RandomItemFromList(villagers); Trace.TraceInformation("*** Randed a wolf kill of '{0}'", kill.Name); _kill = kill.Name; } String seerName = (from p in _playerRoles where p.Role == SEER select p.Name).First(); if (IsSeerAlive() && (_peek == null)) { var possibles = GetPeekCandidates(seerName); if (possibles.Any()) { _peek = Misc.RandomItemFromList(possibles); Trace.TraceInformation("*** Randed a seer peek of '{0}'", _peek.Name); } } var seer = LookupPlayer(seerName); var k = LookupPlayer(_kill); KillPlayer(k.Name); String roleColor = (k.Role == SEER) ? "purple" : "green"; _killMessage = String.Format("The wolves killed [b]{0}[/b]. Role: [color={1}][b]{2}[/b][/color].\r\n", k.Name, roleColor, k.Role); if ((seer.Dead == false) && (_kill.Equals(seerName, StringComparison.InvariantCultureIgnoreCase) == false)) { String msg; if (_peek != null) { _peeks.Add(_peek); msg = String.Format("Peek result for {0}: {1}\r\n", _peek.Name, _peek.Team); } else { msg = "There's nobody left to peek."; } QueuePM(new String[] { seer.Name }, "Night Action Success", msg); } ChangeState(StateDay); } break; case "EventExit": { } break; case "EventMinute": { } break; } return StateNight; } State StateNightNeedAction(Event e) { switch (e.EventName) { case "EventEnter": { _peek = null; } break; case "EventExit": { } break; case "CheckForTimeout": { DateTime now = DateTime.Now; now = TruncateSeconds(now); if (now > _nextDay) { PostEvent(new Event("NightTimeout")); } } return null; case "NightTimeout": { ChangeState(StateCallDay); } return null; case "WolfKillPM": { Event<PrivateMessage> pme = e as Event<PrivateMessage>; PrivateMessage pm = pme.Param; var player = LookupPlayer(pm.From); if (_kill == "") { ParseKillPM(pm); } var kill = LookupPlayer(_kill); if ((_kill != "") && (!IsSeerAlive() || (_peek != null) || (kill.Role == SEER)) && !_missingPlayers) { ChangeState(StateCallDay); return null; } } break; case "SeerPM": { Event<PrivateMessage> pme = e as Event<PrivateMessage>; PrivateMessage pm = pme.Param; if (_peek == null) { _peek = ParsePeekPM(pm); } if ((_kill != "") && (_peek != null) && !_missingPlayers) { ChangeState(StateCallDay); return null; } } break; } return StateNight; } #endregion #region helpers void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { PostEvent(new Event("EventMinute")); _timer.Interval = GetTimerInterval(); _timer.Start(); } private double GetTimerInterval() { int timerPeriod = 30; // seconds int graceMS = 50; // amount local clock can be fast and still not fail. DateTime now = DateTime.Now; double rc = graceMS + ((timerPeriod - now.Second) * 1000) - now.Millisecond; if (rc < 1000) rc += (timerPeriod * 1000); return rc; } void ReplyFailure(PrivateMessage pm, IEnumerable<String> failed, IEnumerable<String> players, String msg) { String reply= "Sorry, this failed. " + msg + "\r\n\r\n"; reply+= String.Format("These {0} were good:\r\n", players.Count()); foreach (var player in players) { reply += player + "\r\n"; } reply += String.Format("\r\nThese {0} failed:\r\n", failed.Count()); foreach(var player in failed) { reply += player + "\r\n"; } PrivateMessage rpm = new PrivateMessage(new String[] { pm.From }, null, pm.Title, reply); _forum.SendPM(rpm); } void PollPMs() { List<PrivateMessage> pms = new List<PrivateMessage>(); List<PrivateMessage> rc = new List<PrivateMessage>(); _forum.CheckPMs(0, 1, null, (folderpage, errMessage, cookie) => { for (int i = 0; i < folderpage.MessagesThisPage; i++) { PMHeader header = folderpage[i]; if ((_EarliestPMTime <= header.Timestamp) && (_maxTime >= header.Timestamp) && (header.Id > _lastPMProcessed)) { _db.AddPosters(new POG.Forum.Poster[] { new POG.Forum.Poster(header.Sender, header.SenderId) }); _forum.ReadPM(header.Id, null, (id, pm, cake) => { pms.Add(pm); }); } } } ); Int32 lastPMId = 0; foreach (var pm in pms) { if (pm.Id <= _lastPMProcessed) { continue; } rc.Add(pm); lastPMId = Math.Max(lastPMId, pm.Id); } if (lastPMId > _lastPMProcessed) { _lastPMProcessed = lastPMId; } rc.Sort((x, y) => x.Id.CompareTo(y.Id)); foreach (var pm in rc) { if (pm.Title.ToLowerInvariant().Trim().StartsWith("correct")) { PostEvent(new Event<PrivateMessage>("CorrectionPM", pm)); continue; } if ((pm.Title.ToLowerInvariant().Trim().StartsWith("sub")) || (pm.Content.ToLowerInvariant().Trim().StartsWith("sub "))) { PostEvent(new Event<PrivateMessage>("SubPM", pm)); continue; } var player = LookupPlayer(pm.From); if (player == null) { PostEvent(new Event<PrivateMessage>("StrangerPM", pm)); continue; } if (player.Dead == true) { PostEvent(new Event<PrivateMessage>("DeadPM", pm)); continue; } if (player.Team == WOLF) { if (pm.Content.StartsWith("resign", StringComparison.InvariantCultureIgnoreCase)) { PostEvent(new Event<PrivateMessage>("WolfResignPM", pm)); ChangeState(StateResign); continue; } PostEvent(new Event<PrivateMessage>("WolfKillPM", pm)); continue; } if (player.Role == SEER) { PostEvent(new Event<PrivateMessage>("SeerPM", pm)); continue; } PostEvent(new Event<PrivateMessage>("VanillaPM", pm)); } } Boolean CheckCanReceivePM() { _canPM.Clear(); Boolean failed = false; for (int i = _validNames.Count - 1; i >= 0; i--) { String name = _validNames[i]; if (_forum.CanUserReceivePM(name)) { _canPM.Add(name); _validNames.RemoveAt(i); } else { failed = true; } } return !failed; } internal void CheckNames() { for(int i = _requestNames.Count - 1; i >= 0; i--) { String name = _requestNames[i]; name = name.Split('\t')[0]; name = name.Trim(); int ix = i; if (_autoComplete.GetPosterId(name, (poster, id) => { if (id > 0) { _validNames.Add(poster); _requestNames.Remove(name); } _pendingLookups--; if (0 == _pendingLookups) { PostEvent(new Event("NamesChecked")); } } ) > 0) { _validNames.Add(name); _requestNames.RemoveAt(ix); } else { _pendingLookups++; } } if (0 == _pendingLookups) { PostEvent(new Event("NamesChecked")); } } DateTime _lastPostTime = DateTime.MinValue; Boolean MakePost(String title, String post, bool lockIt = false) { DateTime now = DateTime.Now; TimeSpan delay = now - _lastPostTime; if (delay < new TimeSpan(0, 0, 26)) { Trace.TraceInformation("Not Delaying post '{0}' due to 25 second rule. Testing mod powers.", title); //Trace.TraceInformation("Delaying post '{0}' due to 25 second rule.", title); //var evt = new Event<String, String, bool>("DelayedPost", title, post, lockIt); //PostEvent(evt); //return true; } var rc = _forum.MakePost(_threadId, title, post, 0, lockIt); _lastPostTime = DateTime.Now; return rc.Item1; } DateTime TruncateSeconds(DateTime dt) { DateTime rc = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0); return rc; } Int32 WolfCount { get { int wolfCount = (from p in _playerRoles where (p.Dead == false) && (p.Team == WOLF) select p).Count(); return wolfCount; } } Int32 SeerCount { get { int seerCount = (from p in _playerRoles where (p.Dead == false) && (p.Team == VILLAGE) && (p.Role == SEER) select p).Count(); return seerCount; } } Int32 VanillaCount { get { int vanillaCount = (from p in _playerRoles where (p.Dead == false) && (p.Team == VILLAGE) && (p.Role == VANILLA) select p).Count(); return vanillaCount; } } Int32 LiveCount { get { var live = from p in _playerRoles where p.Dead == false select p.Name; return live.Count(); } } String MakeGoodBad(DateTime dt) { int minuteGood = dt.Minute; int minuteBad = (minuteGood + 1) % 60; String rc = String.Format("[highlight][color=green]:{0} good[/color] [color=red]:{1} bad[/color][/highlight]", minuteGood.ToString("00"), minuteBad.ToString("00")); return rc; } Boolean AnnounceDay(Int32 day) { Boolean rc = true; var sb = new StringBuilder(); String announce = GetAnnouncements(); if (announce != "") { sb.AppendLine(announce); } if (_killMessage != "") { sb.AppendLine(_killMessage); sb.AppendLine(); } var live = from p in _playerRoles where (p.Dead == false) orderby p.Name.ToUpperInvariant() select p.Name; string wolf = (WolfCount > 1) ? "wolves" : "wolf"; string seer = (SeerCount > 0) ? "1 seer, " : ""; string vanilla = (VanillaCount > 1) ? "villagers" : "villager"; sb.AppendFormat("{0} players: {1} {2}, {3}{4} vanilla {5}", live.Count(), WolfCount, wolf, seer, VanillaCount, vanilla); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[u]Live Players:[/u]"); foreach (string p in live) { sb.AppendLine(p); } sb.AppendLine(); sb.AppendLine(MakeGoodBad(_nextNight)); sb.AppendLine(); if (_majorityLynch) { int majCount = 1 + (live.Count() / 2); sb.AppendFormat("{0} votes is majority.", majCount); } else { sb.AppendLine("No majority lynch today."); } if (day == 0) { sb.Append("\n\n[sub]Note: [b][color=red]Error[/color][/b] vote can be fixed by sending me a PM with title 'correction' and body x=y. "); sb.AppendLine(@"Where x is what the person bolded and y is the player they meant to vote. This is useful at must lynch.[/sub]"); sb.AppendLine("[sub]Note: You can sub by sending me a PM with title 'sub'. Put the player you are replacing in the body.[/sub]\n"); } if ((_count != null) && _count.LockedVotes) { sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[highlight]Caution: Votes are locked in today. Your first vote is final.[/highlight]"); sb.AppendLine(); } sb.AppendLine(); sb.AppendLine("[b]It is day![/b]"); if (day == 0) { if (_hyper == false) { var newThread = _forum.NewThread(59, _threadTitle, sb.ToString(), 15, false); String url = newThread.Item1; _threadId = Misc.TidFromURL(url); _url = url; if (_threadId <= 0) { Trace.TraceError("*** FAILURE CREATING THREAD: {0}", newThread.Item2); rc = false; } } else { _forum.LockThread(_threadId, false); MakePost("Mod: It is day!", sb.ToString()); } ThreadReader t = _forum.Reader(); Action<Action> invoker = a => a(); _count = new ElectionInfo(invoker, t, _db, _forum.ForumURL, _url, _forum.PostsPerPage, false, Language.English, "3.8.7"); _count.Census.Clear(); _count.CheckMajority = false; var players = from p in _playerRoles where p.Dead == false select p.Name; foreach (var p in players) { CensusEntry ce = new CensusEntry(); ce.Name = p; ce.Alive = "Alive"; _count.Census.Add(ce); } _count.CommitRosterChanges(); } else { if (day != 1) { _forum.LockThread(_threadId, false); MakePost("Mod: It is day!", sb.ToString()); } } return rc; } Boolean IsSeerAlive() { var seer = (from p in _playerRoles where (p.Dead == false) && (p.Role == SEER) select p).FirstOrDefault(); if (seer == null) { return false; } return true; } Int32 GetMajorityCount() { if (!_majorityLynch) return Int32.MaxValue; var live = from p in _playerRoles where p.Dead == false select p.Name; int majCount = 1 + (live.Count() / 2); return majCount; } Player KillPlayer(string who) { _count.KillPlayer(who); Player player = LookupPlayer(who); player.Dead = true; var live = from p in _playerRoles where p.Dead == false select p.Name; Trace.TraceInformation("*** Begin Live Player List ***"); foreach (var p in live) { Trace.TraceInformation("live: {0}", p); } Trace.TraceInformation("*** End Live Player List ***"); return player; } Player LookupPlayer(Int32 id) { Player rc = (from p in _playerRoles where p.Id == id select p).FirstOrDefault(); return rc; } Player LookupPlayer(String name) { var player = (from p in _playerByName where p.Key.Equals(name, StringComparison.InvariantCultureIgnoreCase) select p.Value).FirstOrDefault(); return player; } Player LookupLivePlayer(String name) { var player = (from p in _playerRoles where (p.Dead == false) && (p.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) select p).FirstOrDefault(); return player; } private bool ParseKillPM(PrivateMessage pm) { List<String> rawList = pm.Content.Split( new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Trim()) .Distinct().ToList(); foreach (var line in rawList) { var player = LookupPlayer(line); if ((player != null) && (player.Dead == false) && (player.Team != WOLF)) { _kill = player.Name; return true; } } var wolves = from p in _playerRoles where (p.Dead == false) && (p.Team == WOLF) select p.Name; var villagers = from p in _playerRoles where (p.Dead == false) && (p.Team == VILLAGE) orderby p.Name.ToUpperInvariant() select p.Name; var villaNames = from p in _playerByName where (p.Value.Dead == false) && (p.Value.Team == VILLAGE) orderby p.Value.Name.ToLowerInvariant() select p.Key; // look for name without requiring exact. foreach (var line in rawList) { string l = line; if (pm.Content.ToLowerInvariant().Trim().StartsWith("kill ")) { l = l.Substring(5).Trim(); } String k = InexactLookup(l, villaNames); if ((k != null) && (k != "")) { var player = LookupPlayer(k); if ((player != null) && (player.Dead == false) && (player.Team != WOLF)) { _kill = player.Name; return true; } } } String msg = "Submit your kill promptly. It should be a PM that contains only the name of the villager you want to kill.\r\n\r\n live villagers:\r\n"; foreach (var v in villagers) { msg += v + "\r\n"; } QueuePM(wolves, "NIGHT ACTION FAILED", msg); return false; } String InexactLookup(String input, IEnumerable<Player> choices) { var names = from c in choices select c.Name; String rc = InexactLookup(input, names); return rc; } String InexactLookup(String input, IEnumerable<String> choices) { List<ElectionInfo.Alias> choiceList = new List<ElectionInfo.Alias>(); foreach (var c in choices) { choiceList.Add(new ElectionInfo.Alias(c, c)); } String rc = _count.ParseInputToChoice(input, choiceList); return rc; } DateTime _lastPMTime = DateTime.MinValue; Queue<PrivateMessage> _pmQueue = new Queue<PrivateMessage>(); void SendPM(PrivateMessage pm) { _forum.SendPM(pm); _lastPMTime = DateTime.Now; } void SetPMTimer() { if (!_timerPM.Enabled) { DateTime ok = _lastPMTime.AddSeconds(1); TimeSpan ts = ok - DateTime.Now; if (ts.Ticks < 0) { UnqueuePM(); } if (_pmQueue.Count > 0) { _timerPM.Interval = ts.TotalMilliseconds; _timerPM.Start(); } } } void UnqueuePM() { PrivateMessage pm = null; lock (_pmQueue) { if (_pmQueue.Count > 0) { pm = _pmQueue.Dequeue(); } } if(pm != null) { SendPM(pm); SetPMTimer(); } } void QueuePM(PrivateMessage pm) { lock (_pmQueue) { _pmQueue.Enqueue(pm); } SetPMTimer(); } private void QueuePM(IEnumerable<string> bcc, string title, string msg) { PrivateMessage pm = new PrivateMessage(null, bcc, title, msg); QueuePM(pm); } List<String> _annoucementQueue = new List<string>(); void QueueAnnouncement(string msg) { lock (_annoucementQueue) { _annoucementQueue.Add(msg); } } String GetAnnouncements() { StringBuilder rc = new StringBuilder(); lock (_annoucementQueue) { foreach (var msg in _annoucementQueue) { rc.AppendLine(msg); } _annoucementQueue.Clear(); } return rc.ToString(); } private Player ParseSubPM(PrivateMessage pm) { var players = from p in _playerByName orderby p.Key.ToUpperInvariant() select p.Key; List<String> rawList = pm.Content.Split( new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Trim()) .Distinct().ToList(); foreach (var line in rawList) { string l = line; if (pm.Content.ToLowerInvariant().Trim().StartsWith("sub ")) { l = l.Substring(4).Trim(); } var player = LookupLivePlayer(l); if (player != null) { if (player.Dead) return null; return player; } } return null; } private Player ParsePeekPM(PrivateMessage pm) { List<String> rawList = pm.Content.Split( new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Trim()) .Distinct().ToList(); foreach (var line in rawList) { var player = LookupPlayer(line); if ((player != null) && (player.Dead == false)) { return player; } } var peekCandidates = GetPeekCandidatesAllNames(pm.From); List<ElectionInfo.Alias> choiceList = new List<ElectionInfo.Alias>(); foreach (var c in peekCandidates) { choiceList.Add(new ElectionInfo.Alias(c.Key, c.Value.Name)); choiceList.Add(new ElectionInfo.Alias("peek " + c.Key, c.Value.Name)); } // try again, inexact foreach (var line in rawList) { string l = line; String peek = _count.ParseInputToChoice(l, choiceList); var player = LookupPlayer(peek); if ((player != null) && (player.Dead == false)) { return player; } } String msg = "Submit your peek promptly. It should be a PM that contains only the name of the player you want to peek. \r\n\r\nUnpeeked players:\r\n"; var currentCandidates = GetPeekCandidates(pm.From); foreach (var v in currentCandidates) { msg += v.Name + "\r\n"; } QueuePM(new String[] {pm.From}, "NIGHT ACTION FAILED", msg); return null; } IEnumerable<Player> GetPeekCandidates(String seerName) { var players = from p in _playerRoles where (p.Dead == false) orderby p.Name.ToUpperInvariant() select p; var peekCandidates = players.Except(_peeks). Where(p => p.Name.Equals(seerName, StringComparison.InvariantCultureIgnoreCase) == false); return peekCandidates; } IEnumerable<KeyValuePair<String, Player>> GetPeekCandidatesAllNames(String seerName) { var players = from p in _playerByName where (p.Value.Dead == false) && !_peeks.Contains(p.Value) && !p.Value.Name.Equals(seerName, StringComparison.InvariantCultureIgnoreCase) orderby p.Value.Name.ToUpperInvariant() select p; return players; } void SetDayDuration() { Int32 m = (_day < 1) ? _d1Duration : _dDuration; _nextNight = TruncateSeconds(DateTime.Now).AddMinutes(m); } void SetNightDuration() { Int32 m = IsSeerAlive() ? _n1Duration : _nDuration; DateTime now = TruncateSeconds(DateTime.Now); _nextDay = now.AddMinutes(m); _EarliestPMTime = now.AddMinutes(-2); } #endregion } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Text.RegularExpressions; using KaVE.Commons.Utils; using KaVE.JetBrains.Annotations; using KaVE.RS.Commons.Utils; namespace KaVE.VS.FeedbackGenerator.SessionManager.Presentation { public static class JsonSyntaxHighlighter { [NotNull] public static string AddJsonSyntaxHighlightingWithXaml([NotNull] this string json) { var escapedJson = json.EncodeSpecialChars(); return Regex.Replace( escapedJson, @"(""(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\""])*""(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)", match => CreateReplacement(match.Value)); } private static string CreateReplacement(string match) { if (IsStringConstant(match)) { return IsPropertyKey(match) ? FormatPropertyKey(match) : FormatStringConstant(match); } if (IsBooleanConstant(match)) { return FormatBooleanConstant(match); } if (IsNullConstant(match)) { return FormatNullConstant(match); } return FormatNumberConstant(match); } private static string FormatStringConstant(string match) { return match; } private static string FormatPropertyKey(string match) { return XamlFormattingUtil.Bold(match); } private static string FormatBooleanConstant(string match) { return match; } private static string FormatNullConstant(string match) { return match; } private static string FormatNumberConstant(string match) { return match; } private static bool IsStringConstant(string match) { return Regex.IsMatch(match, "^\""); } private static bool IsPropertyKey(string match) { return Regex.IsMatch(match, ":$"); } private static bool IsBooleanConstant(string match) { return Regex.IsMatch(match, "true|false"); } private static bool IsNullConstant(string match) { return Regex.IsMatch(match, "null"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Portal : MonoBehaviour { public GameObject destino; public float tempo; private float tempoAtual; private bool ativo = true; void OnTriggerEnter2D(Collider2D coll){ if (coll.tag == "Player" && ativo) { coll.gameObject.transform.parent.transform.position = destino.transform.position; destino.GetComponent<Portal> ().Desativar (); } } void Update(){ if (tempoAtual > 0) tempoAtual -= Time.deltaTime; if (tempoAtual <= 0) { ativo = true; } } public void Desativar(){ ativo = false; tempoAtual = tempo; } }
using System; using Xamarin.Forms; namespace AnimeViewer.Controls { public class GradientContentView : ContentView { public static readonly BindableProperty StartColorProperty = BindableProperty.Create("StartColorProperty", typeof(Color), typeof(GradientContentView), default(Color)); public static readonly BindableProperty EndColorProperty = BindableProperty.Create("EndColor", typeof(Color), typeof(GradientContentView), default(Color)); public Color EndColor { get { return (Color) GetValue(EndColorProperty); } set { SetValue(EndColorProperty, value); } } public Color StartColor { get { return (Color) GetValue(StartColorProperty); } set { SetValue(StartColorProperty, value); } } } }
using System; using System.Windows.Data; namespace Hsp.Mvvm { public class IsEqualConverter : IValueConverter { public bool Invert { get; set; } public object EqualValue { get; set; } public object NotEqualValue { get; set; } public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var result = false; if (value == null && parameter == null) result = true; else if (value == null) { } else result = value.Equals(parameter); if (Invert) result = !result; return result ? EqualValue : NotEqualValue; } public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } public IsEqualConverter() { EqualValue = true; NotEqualValue = false; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Plus.Database.Interfaces; using Plus.HabboHotel.Rooms; namespace Plus.HabboHotel.Groups { public class Group { public int Id { get; set; } public string Name { get; set; } public int AdminOnlyDeco { get; set; } public string Badge { get; set; } public int CreateTime { get; set; } public int CreatorId { get; set; } public string Description { get; set; } public int RoomId { get; set; } public int Colour1 { get; set; } public int Colour2 { get; set; } public bool ForumEnabled { get; set; } public GroupType Type { get; set; } public bool HasForum; private readonly List<int> _members; private readonly List<int> _requests; private readonly List<int> _administrators; private RoomData _room; public Group(int id, string name, string description, string badge, int roomId, int owner, int time, int type, int colour1, int colour2, int adminOnlyDeco, bool hasForum) { Id = id; Name = name; Description = description; RoomId = roomId; Badge = badge; CreateTime = time; CreatorId = owner; Colour1 = colour1 == 0 ? 1 : colour1; Colour2 = colour2 == 0 ? 1 : colour2; HasForum = hasForum; Type = (GroupType) type; AdminOnlyDeco = adminOnlyDeco; ForumEnabled = ForumEnabled; _members = new List<int>(); _requests = new List<int>(); _administrators = new List<int>(); InitMembers(); } public void InitMembers() { using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("SELECT `user_id`, `rank` FROM `group_memberships` WHERE `group_id` = @id"); dbClient.AddParameter("id", Id); DataTable members = dbClient.GetTable(); if (members != null) { foreach (DataRow row in members.Rows) { int userId = Convert.ToInt32(row["user_id"]); bool isAdmin = Convert.ToInt32(row["rank"]) != 0; if (isAdmin) { if (!_administrators.Contains(userId)) _administrators.Add(userId); } else { if (!_members.Contains(userId)) _members.Add(userId); } } } dbClient.SetQuery("SELECT `user_id` FROM `group_requests` WHERE `group_id` = @id"); dbClient.AddParameter("id", Id); DataTable requests = dbClient.GetTable(); if (requests != null) { foreach (DataRow row in requests.Rows) { int userId = Convert.ToInt32(row["user_id"]); if (_members.Contains(userId) || _administrators.Contains(userId)) { dbClient.RunQuery("DELETE FROM `group_requests` WHERE `group_id` = '" + Id + "' AND `user_id` = '" + userId + "'"); } else if (!_requests.Contains(userId)) { _requests.Add(userId); } } } } } public List<int> GetMembers => _members.ToList(); public List<int> GetRequests => _requests.ToList(); public List<int> GetAdministrators => _administrators.ToList(); public List<int> GetAllMembers { get { List<int> members = new(_administrators.ToList()); members.AddRange(_members.ToList()); return members; } } public int MemberCount => _members.Count + _administrators.Count; public int RequestCount => _requests.Count; public bool IsMember(int id) { return _members.Contains(id) || _administrators.Contains(id); } public bool IsAdmin(int id) { return _administrators.Contains(id); } public bool HasRequest(int id) { return _requests.Contains(id); } public void MakeAdmin(int id) { if (_members.Contains(id)) _members.Remove(id); using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("UPDATE group_memberships SET `rank` = '1' WHERE `user_id` = @uid AND `group_id` = @gid LIMIT 1"); dbClient.AddParameter("gid", Id); dbClient.AddParameter("uid", id); dbClient.RunQuery(); } if (!_administrators.Contains(id)) _administrators.Add(id); } public void TakeAdmin(int userId) { if (!_administrators.Contains(userId)) return; using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("UPDATE group_memberships SET `rank` = '0' WHERE user_id = @uid AND group_id = @gid"); dbClient.AddParameter("gid", Id); dbClient.AddParameter("uid", userId); dbClient.RunQuery(); } _administrators.Remove(userId); _members.Add(userId); } public void AddMember(int id) { if (IsMember(id) || Type == GroupType.Locked && _requests.Contains(id)) return; using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { if (IsAdmin(id)) { dbClient.SetQuery("UPDATE `group_memberships` SET `rank` = '0' WHERE user_id = @uid AND group_id = @gid"); _administrators.Remove(id); _members.Add(id); } else if (Type == GroupType.Locked) { dbClient.SetQuery("INSERT INTO `group_requests` (user_id, group_id) VALUES (@uid, @gid)"); _requests.Add(id); } else { dbClient.SetQuery("INSERT INTO `group_memberships` (user_id, group_id) VALUES (@uid, @gid)"); _members.Add(id); } dbClient.AddParameter("gid", Id); dbClient.AddParameter("uid", id); dbClient.RunQuery(); } } public void DeleteMember(int id) { if (IsMember(id)) { if (_members.Contains(id)) _members.Remove(id); } else if (IsAdmin(id)) { if (_administrators.Contains(id)) _administrators.Remove(id); } else return; using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("DELETE FROM group_memberships WHERE user_id=@uid AND group_id=@gid LIMIT 1"); dbClient.AddParameter("gid", Id); dbClient.AddParameter("uid", id); dbClient.RunQuery(); } } public void HandleRequest(int id, bool accepted) { using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { if (accepted) { dbClient.SetQuery("INSERT INTO group_memberships (user_id, group_id) VALUES (@uid, @gid)"); dbClient.AddParameter("gid", Id); dbClient.AddParameter("uid", id); dbClient.RunQuery(); _members.Add(id); } dbClient.SetQuery("DELETE FROM group_requests WHERE user_id=@uid AND group_id=@gid LIMIT 1"); dbClient.AddParameter("gid", Id); dbClient.AddParameter("uid", id); dbClient.RunQuery(); } if (_requests.Contains(id)) _requests.Remove(id); } public RoomData GetRoom() { if (_room == null) { if (!RoomFactory.TryGetData(RoomId, out RoomData data)) return null; _room = data; return data; } return _room; } public void ClearRequests() { _requests.Clear(); } public void Dispose() { _requests.Clear(); _members.Clear(); _administrators.Clear(); } } }
using FileManager.Common.Layer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.DataAccess.Data { public interface IFile { Student Create(Student student); Student Update(Student student); Boolean Delete(Student student); List<Student> All(); } }
using System; using UnityEngine; using UnityEngine.UI; using Grpc.Core; using Helloworld; public class Example : MonoBehaviour { public Text Response; public void Send() { try { var channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel); var reply = client.SayHello(new HelloRequest { Name = "Unity" }); Response.text = reply.Message; channel.ShutdownAsync().Wait(); } catch (Exception e) { Response.text = "exception: " + e.Message; } } }
using System; namespace QAToolKit.Auth { /// <summary> /// Default auth options object /// </summary> public abstract class DefaultOptions { /// <summary> /// Keycloak token endpoint you want to call /// </summary> public Uri TokenEndpoint { get; private set; } /// <summary> /// Keycloak client ID /// </summary> public string ClientId { get; private set; } /// <summary> /// Keycloak client secret /// </summary> public string Secret { get; private set; } /// <summary> /// Scopes that client has access to /// </summary> public string[] Scopes { get; private set; } = null; /// <summary> /// Username for ROPC flow /// </summary> public string UserName { get; private set; } /// <summary> /// User password for ROPC flow /// </summary> public string Password { get; private set; } /// <summary> /// Oauth2 flow type /// </summary> public FlowType FlowType { get; private set; } /// <summary> /// Add client credential flow parameters /// </summary> /// <param name="tokenEndpoint">Keycloak token endpoint</param> /// <param name="clientId">Keycloak client ID</param> /// <param name="clientSecret">Keycloak client secret</param> /// <param name="scopes">Scopes that client has access to</param> /// <returns></returns> public virtual DefaultOptions AddClientCredentialFlowParameters(Uri tokenEndpoint, string clientId, string clientSecret, string[] scopes = null) { if (tokenEndpoint == null) throw new ArgumentNullException($"{nameof(tokenEndpoint)} is null."); if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException($"{nameof(clientId)} is null."); if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException($"{nameof(clientSecret)} is null."); TokenEndpoint = tokenEndpoint; ClientId = clientId; Secret = clientSecret; Scopes = scopes; UserName = null; Password = null; FlowType = FlowType.ClientCredentialFlow; return this; } /// <summary> /// Add resource owner password credential flow parameters /// </summary> /// <param name="tokenEndpoint">Keycloak token endpoint</param> /// <param name="clientId">Keycloak client ID</param> /// <param name="clientSecret">Keycloak client secret</param> /// <param name="userName">Username</param> /// <param name="password">Password</param> /// <param name="scopes">Scopes that client has access to</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public virtual DefaultOptions AddResourceOwnerPasswordCredentialFlowParameters(Uri tokenEndpoint, string clientId, string clientSecret, string userName, string password, string[] scopes = null) { if (tokenEndpoint == null) throw new ArgumentNullException($"{nameof(tokenEndpoint)} is null."); if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException($"{nameof(clientId)} is null."); if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException($"{nameof(clientSecret)} is null."); if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException($"{nameof(userName)} is null."); if (string.IsNullOrEmpty(password)) throw new ArgumentNullException($"{nameof(password)} is null."); TokenEndpoint = tokenEndpoint; ClientId = clientId; Secret = clientSecret; Scopes = scopes; UserName = userName; Password = password; FlowType = FlowType.ResourceOwnerPasswordCredentialFlow; return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; ////////////////////// // Gavin Macleod // ////////////////////// // S1715408 // // Honours Project // // BSc Computing // ////////////////////// namespace Prototype1 { public class Player { public int Id { get; set; } public string Username { get; set; } public string RankName { get; set; } public int TotalScore { get; set; } public int TalkativeScore { get; set; } public int ShoutScore { get; set; } public int QuietScore { get; set; } public int SwearCount { get; set; } public int MannersCount { get; set; } } }
using System.Linq; using Angband.Core; namespace Angband.Console { public static class Program { public static void Main(string[] args) { switch (args.FirstOrDefault() ?? string.Empty) { case "SUM": var somme = new Somme(args.Skip(1).Select(int.Parse)); System.Console.WriteLine(somme.Resultat); break; case "ADD": var addition = new Addition(int.Parse(args[1]), int.Parse(args[2])); System.Console.WriteLine(addition.Resultat); break; default: System.Console.WriteLine("Commande invalide"); break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using API.DTOs; using API.Services; using Domain; using Infrastructure.Email; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.WebUtilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; namespace API.Controllers { [ApiController] [Route("api/[controller]")] public class AccountController : ControllerBase { private readonly UserManager<AppUser> _userManager; private readonly SignInManager<AppUser> _signInManager; private readonly TokenService _tokenService; private readonly IConfiguration _configuration; private readonly HttpClient _httpClient; private readonly EmailSender _emailSender; public AccountController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager, TokenService tokenService, IConfiguration configuration, EmailSender emailSender) { this._userManager = userManager; this._signInManager = signInManager; this._tokenService = tokenService; this._configuration = configuration; this._httpClient = new HttpClient { BaseAddress = new System.Uri("https://graph.facebook.com") }; this._emailSender = emailSender; } [AllowAnonymous] [HttpPost("login")] public async Task<ActionResult<UserDto>> Login(LoginDto loginDto) { var user = await this._userManager.Users .Include(appUser => appUser.Photos) .FirstOrDefaultAsync(appUser => appUser.Email == loginDto.Email); if (user == null) return Unauthorized("Invalid Email"); // if (user.UserName == "bob") user.EmailConfirmed = true; if (!user.EmailConfirmed) return Unauthorized("Email Not Confimed"); var result = await this._signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false); if (result.Succeeded) { await this.SetRefreshToken(user); return this.CreateUser(user); } else { return Unauthorized("Invalid Password"); } } [AllowAnonymous] [HttpPost("register")] public async Task<ActionResult<UserDto>> Register(RegisterDto registerDto) { if (await this._userManager.Users.AnyAsync(user => user.Email == registerDto.Email)) { ModelState.AddModelError("email", "Email already taken"); return ValidationProblem(); } if (await this._userManager.Users.AnyAsync(user => user.UserName == registerDto.Username)) { ModelState.AddModelError("username", "Username already registered"); return ValidationProblem(); } var user = new AppUser { DisplayName = registerDto.DisplayName, Email = registerDto.Email, UserName = registerDto.Username }; var result = await this._userManager.CreateAsync(user, registerDto.Password); if (result.Succeeded) { var origin = Request.Headers["origin"]; var emailVerificationToken = await this._userManager.GenerateEmailConfirmationTokenAsync(user); emailVerificationToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(emailVerificationToken)); var verifyUrl = $"{origin}/account/verifyEmail?emailVerificationToken={emailVerificationToken}&email={user.Email}"; var message = $"<p>Please click the below link to verify your email address:</p><p><a href='{verifyUrl}'>Click to verify email</a></p>"; await this._emailSender.SendEmailAsync(user.Email, "Please verify email", message); return Ok("Registration success! Please, verify your email"); } else { return BadRequest("Error registering user"); } } [AllowAnonymous] [HttpPost("verifyEmail")] public async Task<ActionResult<UserDto>> VerifyEmail(string emailVerificationToken, string email) { var user = await this._userManager.FindByEmailAsync(email); if (user == null) return Unauthorized(); var decodedTokenBytes = WebEncoders.Base64UrlDecode(emailVerificationToken); var decodedToken = Encoding.UTF8.GetString(decodedTokenBytes); var result = await this._userManager.ConfirmEmailAsync(user, decodedToken); if (result.Succeeded) { return Ok("Email Confirmed! You can now login"); } else { return BadRequest("Error verifying email"); } } [AllowAnonymous] [HttpGet("resendEmailConfirmationLink")] public async Task<IActionResult> ResendEmailConfirmationLink(string email) { var user = await this._userManager.FindByEmailAsync(email); if (user == null) return Unauthorized(); var origin = Request.Headers["origin"]; var token = await this._userManager.GenerateEmailConfirmationTokenAsync(user); token = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token)); var verifyUrl = $"{origin}/account/verifyEmail?emailVerificationToken={token}&email={user.Email}"; var message = $"<p>Please click the below link to verify your email address:</p><p><a href='{verifyUrl}'>Click to verify email</a></p>"; await _emailSender.SendEmailAsync(user.Email, "Please verify email", message); return Ok("Email verification link resent"); } [Authorize] [HttpGet] public async Task<ActionResult<UserDto>> GetCurrentUser() { var user = await this._userManager.Users .Include(appUser => appUser.Photos) .FirstOrDefaultAsync(appUser => appUser.Email == User.FindFirstValue(ClaimTypes.Email)); await this.SetRefreshToken(user); return this.CreateUser(user); } [AllowAnonymous] [HttpPost("fbLogin")] public async Task<ActionResult<UserDto>> FacebookLogin(string accessToken) { var facebookKeys = this._configuration["Facebook:AppId"] + "|" + this._configuration["Facebook:AppSecret"]; var verifyToken = await this._httpClient.GetAsync($"debug_token?input_token={accessToken}&access_token={facebookKeys}"); if (!verifyToken.IsSuccessStatusCode) return Unauthorized(); var facebookUrl = $"me?access_token={accessToken}&fields=name,email,picture.width(100).height(100)"; var response = await this._httpClient.GetAsync(facebookUrl); if (!response.IsSuccessStatusCode) return Unauthorized(); var facebookData = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync()); var username = (string)facebookData.id; var user = await this._userManager.Users.Include(p => p.Photos) .FirstOrDefaultAsync(AppUser => AppUser.UserName == username); if (user != null) return this.CreateUser(user); user = new AppUser { DisplayName = (string)facebookData.name, Email = (string)facebookData.email, UserName = (string)facebookData.id, Photos = new List<Photo> { new Photo { Id = "fb_" + (string)facebookData.id, Url = (string)facebookData.picture.data.url, IsMain = true } } }; user.EmailConfirmed = true; var result = await this._userManager.CreateAsync(user); if (!result.Succeeded) return BadRequest("Error creating user account with facebook"); await this.SetRefreshToken(user); return this.CreateUser(user); } [Authorize] [HttpPost("refreshToken")] public async Task<ActionResult<UserDto>> RefreshToken() { var refreshToken = Request.Cookies["refreshToken"]; var user = await this._userManager.Users .Include(appUser => appUser.RefreshTokens) .Include(appUser => appUser.Photos) .FirstOrDefaultAsync(appUser => appUser.UserName == User.FindFirstValue(ClaimTypes.Name)); var oldToken = user.RefreshTokens.SingleOrDefault(x => x.Token == refreshToken); if (oldToken != null && !oldToken.IsActive) return Unauthorized(); return this.CreateUser(user); } private async Task SetRefreshToken(AppUser appUser) { var refreshToken = this._tokenService.GenerateRefreshToken(); appUser.RefreshTokens.Add(refreshToken); await this._userManager.UpdateAsync(appUser); var cookieOptions = new CookieOptions { HttpOnly = true, Expires = DateTime.UtcNow.AddDays(7) }; Response.Cookies.Append("refreshToken", refreshToken.Token, cookieOptions); } private UserDto CreateUser(AppUser user) { return new UserDto { Username = user.UserName, DisplayName = user.DisplayName, Image = user.Photos?.FirstOrDefault(photo => photo.IsMain)?.Url, Token = this._tokenService.CreateToken(user) }; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace biaolei { public class Fenshu { private long fenshu_id; private string user_name; private float fenshu_guankaname; private float fenshu_defen; //private Date fenshu_date; public float getFenshu_guankaname() { return fenshu_guankaname; } public void setFenshu_guankaname(float fenshu_guankaname) { this.fenshu_guankaname = fenshu_guankaname; } public long getFenshu_id() { return fenshu_id; } public void setFenshu_id(long fenshu_id) { this.fenshu_id = fenshu_id; } public string getUser_name() { return user_name; } public void setUser_name(string user_name) { this.user_name = user_name; } public float getFenshu_defen() { return fenshu_defen; } public void setFenshu_defen(float fenshu_defen) { this.fenshu_defen = fenshu_defen; } /* public Date getFenshu_date() { return fenshu_date; } public void setFenshu_date(Date fenshu_date) { this.fenshu_date = fenshu_date; }*/ } }
using System; using System.Collections.Generic; namespace HotFix_Project { public class InstanceClass { private int id; public InstanceClass() { UnityEngine.Debug.Log("!!! InstanceClass::InstanceClass()"); this.id = 0; } public InstanceClass(int id) { UnityEngine.Debug.Log("!!! InstanceClass::InstanceClass() id = " + id); this.id = id; } public int ID { get { return id; } } // static method public static void StaticFunTest() { UnityEngine.Debug.Log("!!! InstanceClass.StaticFunTest()"); } public static void StaticFunTest2(int a) { UnityEngine.Debug.Log("!!! InstanceClass.StaticFunTest2(), a=" + a); } public static void GenericMethod<T>(T a) { UnityEngine.Debug.Log("!!! InstanceClass.GenericMethod(), a=" + a); } public void RefOutMethod(int addition, out List<int> lst, ref int val) { val = val + addition + id; lst = new List<int>(); lst.Add(id); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IReader<T> { T GetTileTypeAtIndex(int index); int GetTileTypesCount(); float GetTileWeight(T tile); bool CheckForPossibleTile(T currentTile, Direction dir, T tileToFind); }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class B_PlayerCollisionHandler : MonoBehaviour { public PlayerController cont; private GameObject player; private bool playerDisabled; private float startTime; private RigidbodyConstraints fullConstrain = RigidbodyConstraints.FreezeAll; // Start is called before the first frame update void Start() { player = cont.gameObject; } // Update is called once per frame void Update() { if (playerDisabled) { if (Time.time - startTime < 5) { Debug.Log("Yeah boi we can't move"); } else { Debug.Log("Times Up"); cont.enabled = true; //Fully constrain all rotations and zero out all velocity and rotations cont.GetComponent<Rigidbody>().constraints = fullConstrain; resetPlayerVelocity(); resetPlayerRotations(); //Reset to normal player constraints cont.GetComponent<Rigidbody>().constraints = cont.currConstr; playerDisabled = false; } } if (Input.GetKeyDown(KeyCode.P)) { resetPlayerRotations(); resetPlayerVelocity(); } } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "Ground") { if (cont.hover) { cont.toggleHover(); } Debug.Log("Dayum son you hit the ground"); cont.toggleFlight(); } if (collision.gameObject.tag == "Wall" && !playerDisabled) { if (cont.hover) { cont.toggleHover(); } Debug.Log("Oh shit thats a wall"); cont.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None; cont.GetComponent<Rigidbody>().velocity = transform.forward * -50; cont.enabled = false; playerDisabled = true; startTime = Time.time; } } private void resetPlayerRotations() { player.transform.rotation = Quaternion.identity; } private void resetPlayerVelocity() { cont.GetComponent<Rigidbody>().velocity = Vector3.zero; } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using DotNetNuke.Common; using DotNetNuke.Entities.Portals; #endregion namespace DotNetNuke.UI.WebControls { public abstract class WebControlBase : WebControl { #region "Private Members" private string _styleSheetUrl = ""; private string _theme = ""; #endregion #region "Public Properties" public string Theme { get { return _theme; } set { _theme = value; } } public string ResourcesFolderUrl { get { return Globals.ResolveUrl("~/Resources/"); } } public string StyleSheetUrl { get { if ((_styleSheetUrl.StartsWith("~"))) { return Globals.ResolveUrl(_styleSheetUrl); } else { return _styleSheetUrl; } } set { _styleSheetUrl = value; } } public bool IsHostMenu { get { return Globals.IsHostTab(PortalSettings.ActiveTab.TabID); } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { get { return PortalController.Instance.GetCurrentPortalSettings(); } } #endregion public abstract string HtmlOutput { get; } [Obsolete("There is no longer the concept of an Admin Page. All pages are controlled by Permissions. Scheduled removal in v11.0.0.", true)] public bool IsAdminMenu { get { bool _IsAdmin = false; return _IsAdmin; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(HtmlOutput); } } }
using DataLayer.RequestFeatures; using DataTransfer.DTO.Reports; using System.Collections.Generic; using System.Threading.Tasks; namespace Services.Report { public interface IReportManager { Task<IEnumerable<ReportDto>> GetMaximumPurchase(string userId, PurchaseParameters purchaseParameters); Task<IEnumerable<ReportDto>> GetPurchasesByCategory(string userId, PurchaseParameters purchaseParameters); Task<IEnumerable<ReportDto>> GetMinimumPurchase(string userId, PurchaseParameters purchaseParameters); } }
using ProConstructionsManagment.Desktop.Views.Base; using System.Windows.Controls; namespace ProConstructionsManagment.Desktop.Views.Clients { public partial class Clients : UserControl { public Clients() { InitializeComponent(); var viewModel = ViewModelLocator.Get<ClientsViewModel>(); DataContext = viewModel; Loaded += async (sender, args) => await viewModel.Initialize(); Unloaded += (sender, args) => viewModel.Cleanup(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace D_API.Lib.Internal { internal class D_APINoRequestQueue : IRequestQueue { public Task<T> NewRequest<T>(Func<Task<T>> func, Endpoint _) => func(); public Task<T> NewRequest<T>(Func<T> func, Endpoint _) => Task.Run(func); public Task NewRequest(Func<Task> func, Endpoint _) => func(); public Task NewRequest(Action func, Endpoint _) => Task.Run(func); } }
using System; using System.Collections; using System.Data; using OutSystems.HubEdition.RuntimePlatform; using OutSystems.RuntimePublic.Db; using Newtonsoft.Json.Linq; using System.Text; namespace OutSystems.Nssjwt { public class Cssjwt: Issjwt { /// <summary> /// /// </summary> /// <param name="ssPaymentId"></param> /// <param name="ssOrderId"></param> /// <param name="ssSecret"></param> /// <param name="ssSignedToken"></param> public void MssCreateToken(string ssPaymentId, string ssOrderId, string ssSecret, out string ssSignedToken) { ssSignedToken = ""; // TODO: Write implementation for action } // MssCreateToken /// <summary> /// /// </summary> /// <param name="ssJWT_Token"></param> /// <param name="ssPaymentId"></param> /// <param name="ssOrderId"></param> public void MssReadToken(string ssJWT_Token, out string ssPaymentId, out string ssOrderId) { // TODO: Write implementation for action var data = ssJWT_Token.Substring(ssJWT_Token.IndexOf(".") + 1); var Maindata = data.Substring(0, data.IndexOf(".")) + "="; byte[] base64EncodedBytes = Convert.FromBase64String(Maindata); var jsonData = Encoding.UTF8.GetString(base64EncodedBytes); var details = JObject.Parse(jsonData); var paymentId = details["paymentId"]; var orderDetails = details["orderDetails"]; var orderId = orderDetails["orderId"]; ssPaymentId = paymentId.ToString(); ssOrderId = orderId.ToString(); } // MssReadToken } // Cssjwt } // OutSystems.Nssjwt
using UnityEngine; using System.Collections; using System.Collections.Generic; //somewhere in here there is something that can lower the amount of nodes checked public class AStarScript : MonoBehaviour { public bool check = true; public GridScript gridScript; public HueristicScript hueristic; protected int gridWidth; protected int gridHeight; GameObject[,] pos; //A Star stuff protected Vector3 start; protected Vector3 goal; public Path path; protected PriorityQueue<Vector3> frontier; protected Dictionary<Vector3, Vector3> cameFrom = new Dictionary<Vector3, Vector3>(); protected Dictionary<Vector3, float> costSoFar = new Dictionary<Vector3, float>(); protected Vector3 current; List<Vector3> visited = new List<Vector3>(); // Use this for initialization void Awake(){ gridScript = GameObject.Find("Grid").GetComponent<GridScript>(); hueristic = GetComponentInChildren<HueristicScript>(); } protected virtual void Start () { InitAstar(); } protected virtual void InitAstar(){ InitAstar(new Path(hueristic.gameObject.name, gridScript)); } protected virtual void InitAstar(Path path){ this.path = path; start = gridScript.start; goal = gridScript.goal; gridWidth = gridScript.gridWidth; gridHeight = gridScript.gridHeight; pos = gridScript.GetGrid(); frontier = new PriorityQueue<Vector3>(); frontier.Enqueue(start, 0); cameFrom.Add(start, start); costSoFar.Add(start, 0); int exploredNodes = 0; while(frontier.Count != 0){ exploredNodes++; current = frontier.Dequeue(); if (!visited.Contains(current)) { if (current.Equals(goal)) { Debug.Log("GOOOAL!"); break; } visited.Add(current); #region funny diaganol code //if (!visited.Contains(current)) //{ // visited.Add(current); //} //pos[(int)visited[visited.Count - 1].x, (int)visited[visited.Count - 1].y].transform.localScale = // Vector3.Scale(pos[(int)visited[visited.Count - 1].x, (int)visited[visited.Count - 1].y].transform.localScale, new Vector3(.8f, .8f, .8f)); //for (int x = -1; x < 2; x += 2) //{ // AddNodesToFrontier((int)visited[visited.Count - 1].x + x, (int)visited[visited.Count - 1].y); //} //for (int y = -1; y < 2; y += 2) //{ // AddNodesToFrontier((int)visited[visited.Count - 1].x, (int)visited[visited.Count - 1].y + y); //} #endregion // pos[(int)current.x, (int)current.y].transform.localScale = // Vector3.Scale(pos[(int)current.x, (int)current.y].transform.localScale, new Vector3(.8f, .8f, .8f)); for (int x = -1; x < 2; x += 2) { AddNodesToFrontier((int)current.x + x, (int)current.y); } for (int y = -1; y < 2; y += 2) { AddNodesToFrontier((int)current.x, (int)current.y + y); } } else Debug.Log("Tried to add the same node twice"); } current = goal; LineRenderer line = GetComponent<LineRenderer>(); int i = 0; float score = 0; while(!current.Equals(start)){ line.positionCount++; GameObject go = pos[(int)current.x, (int)current.y]; path.Insert(0, go, new Vector3((int)current.x, (int)current.y)); current = cameFrom[current]; Vector3 vec = Util.clone(go.transform.position); vec.z = -1; line.SetPosition(i, vec); score += gridScript.GetMovementCost(go); i++; } path.Insert(0, pos[(int)current.x, (int)current.y]); path.nodeInspected = exploredNodes; Debug.Log(path.pathName + " Terrian Score: " + score); Debug.Log(path.pathName + " Nodes Checked: " + exploredNodes); Debug.Log(path.pathName + " Total Score: " + (score + exploredNodes)); } void AddNodesToFrontier(int x, int y){ if(x >=0 && x < gridWidth && y >=0 && y < gridHeight) { Vector3 next = new Vector3(x, y); float new_cost = costSoFar[current] + gridScript.GetMovementCost(pos[x, y]); if(!costSoFar.ContainsKey(next) || new_cost < costSoFar[next]) { costSoFar[next] = new_cost; float priority = new_cost + hueristic.Hueristic(x, y, start, goal, gridScript); frontier.Enqueue(next, priority); cameFrom[next] = current; } } } // Update is called once per frame void Update () { } }
using CarSelector.Contracts; using CarSelector.Model; namespace CarSelector.Services { public class CarEvaluatorService : ICarEvaluatorService { public virtual CarRaceTrackEvaluation Evaluate(RaceTrack raceTrack, CarConfiguration carConfiguration) { CarRaceTrackEvaluation carRaceTrackEvaluation = new CarRaceTrackEvaluation(raceTrack, carConfiguration); // Determine total pitstops and round down by casting to int int totalPitstopsRequired = (int)(raceTrack.NoOfLapsToComplete / (carConfiguration.FuelCapacity / carConfiguration.AverageFuelConsumptionPerLap)); carRaceTrackEvaluation.CompletionTime = carConfiguration.TimeToCompleteLap * raceTrack.NoOfLapsToComplete + totalPitstopsRequired * raceTrack.PitstopTimespan; return carRaceTrackEvaluation; } public virtual CarRaceTrackEvaluation[] EvaluateAndSort( RaceTrack raceTrack, CarConfiguration[] carConfigurations) { CarRaceTrackEvaluation[] carRaceTrackEvaluations = new CarRaceTrackEvaluation[carConfigurations.Length]; for (int i = 0; i < carConfigurations.Length; i++) { carRaceTrackEvaluations[i] = this.Evaluate(raceTrack, carConfigurations[i]); } QuickSort<CarRaceTrackEvaluation> evaluationSorter = new QuickSort<CarRaceTrackEvaluation>(carRaceTrackEvaluations); evaluationSorter.Sort(); return evaluationSorter.Output; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("MaterialContainer")] public class MaterialContainer : MonoBehaviour { public MaterialContainer(IntPtr address) : this(address, "MaterialContainer") { } public MaterialContainer(IntPtr address, string className) : base(address, className) { } public Material m_material { get { return base.method_3<Material>("m_material"); } } } }
using Entities.Concrete; using FluentValidation; using System; using System.Collections.Generic; using System.Text; namespace Business.DependencyResolvers.ValidationRules.FluentValidator { public class CarValidator:AbstractValidator<Car> { public CarValidator() { RuleFor(p => p.Description).MinimumLength(2); RuleFor(p => p.Description).NotEmpty(); RuleFor(p => p.CarId).NotEmpty(); RuleFor(p => p.DailyPrice).GreaterThan(0).When(p => p.ModelYear <= 2010); RuleFor(p => p.Description).Must(StartWithA).WithMessage("Araba ismi A ile başlamalı"); } private bool StartWithA(string arg) { return arg.StartsWith("A"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Item { public string name; public int hp; public int at; public int cost; public Sprite icon; public Item(Item d) { name = d.name; hp = d.hp; at = d.at; cost = d.cost; icon = d.icon; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace settings.forms.set_uc { public partial class add_uc : UserControl { public add_uc() { InitializeComponent(); } private void bunifuCustomLabel2_Click(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Newtonsoft.Json.Linq; using Music_Game.Models; using System.Collections.ObjectModel; using System.ComponentModel; namespace Music_Game { public partial class FacebookPage : PhoneApplicationPage, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } public FacebookPage() { InitializeComponent(); this.DataContext = this; list_Challenge = new ObservableCollection<ChallengeDAO>(); } private void Btn_LogInFacebook_SessionStateChanged(object sender, Facebook.Client.Controls.SessionStateChangedEventArgs e) { try { if (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened) { Storyboard_MoveOut.Begin(); } else if (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Closed) { Storyboard_MoveIn.Begin(); } } catch { } } private void ApplicationBarIconButton_Click(object sender, EventArgs e) { NavigationService.GoBack(); } private void LoginComplete() { ApplicationBar.IsVisible = true; Global.AccessToken = Btn_LogInFacebook.CurrentSession.AccessToken; image.Visibility = System.Windows.Visibility.Visible; SB_Rotation.Begin(); } protected override void OnNavigatedTo(NavigationEventArgs e) { if(Global.IsBGMusic == false) BG_Player.Volume = 0; else BG_Player.Volume = 1; } void CreateNewUser() { if (Btn_LogInFacebook.CurrentUser != null) { Global.CurrentUser = new UserMusicDAO(); Global.CurrentUser.Name = Btn_LogInFacebook.CurrentUser.Name; Global.CurrentUser.IdFacebook = Btn_LogInFacebook.CurrentUser.Id; Global.CurrentUser.LinkFacebook = Btn_LogInFacebook.CurrentUser.Link; Global.CurrentUser.UserImage = Btn_LogInFacebook.CurrentUser.ProfilePictureUrl.OriginalString; Global.AccessToken = Btn_LogInFacebook.CurrentSession.AccessToken; ConnectServiceHelper.CreateUser(Btn_LogInFacebook.CurrentUser.Id, Btn_LogInFacebook.CurrentUser.Link, Btn_LogInFacebook.CurrentUser.Name, Global.AccessToken); LoadListChallenge(); } } ObservableCollection<ChallengeDAO> list_Challenge; public ObservableCollection<ChallengeDAO> List_Challenge { get { return list_Challenge; } set { list_Challenge = value; image.Visibility = System.Windows.Visibility.Collapsed; SB_Rotation.Stop(); if(list_Challenge.Count == 0) Text_Info.Visibility = System.Windows.Visibility.Visible; else Text_Info.Visibility = System.Windows.Visibility.Collapsed; } } private async void LoadListChallenge() { try { image.Visibility = System.Windows.Visibility.Visible; SB_Rotation.Begin(); List_Challenge = await ConnectServiceHelper.GetChallenges(Global.AccessToken); ListChallenge.DataContext = List_Challenge; } catch { } } private void ListChallenge_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { if (ListChallenge.SelectedIndex >= 0) { Global.CurrentChallenge = List_Challenge[ListChallenge.SelectedIndex]; if (MessageBox.Show("You will play Challenge of " + Global.CurrentChallenge.NameSend + " !\r\nAre you ready?", "Challenge", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) return; Global.TypeGenre = "challenge"; NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative)); } ListChallenge.SelectedIndex = -1; } catch { } } private void MenuItem_Click(object sender, RoutedEventArgs e) { try { if (MessageBox.Show("You will play this Challenge!\r\nAre you ready?", "Challenge", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) return; int selectedIndex = ListChallenge.Items.IndexOf((sender as MenuItem).DataContext); if(selectedIndex >= 0) { Global.CurrentChallenge = List_Challenge[selectedIndex]; if (MessageBox.Show("You will play Challenge of " + Global.CurrentChallenge.NameSend + " !\r\nAre you ready?", "Challenge", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) return; Global.TypeGenre = "challenge"; NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative)); } } catch { } } private void MenuItem_Click_1(object sender, RoutedEventArgs e) { try { int selectedIndex = ListChallenge.Items.IndexOf((sender as MenuItem).DataContext); } catch { } } private void SB_Rotation_Completed(object sender, EventArgs e) { image.Visibility = System.Windows.Visibility.Visible; SB_Rotation.Begin(); } private void Button_Click(object sender, RoutedEventArgs e) { try { Text_Info.Visibility = System.Windows.Visibility.Collapsed; LoadListChallenge(); } catch { } } private void ApplicationBarIconButton_Click_1(object sender, EventArgs e) { MessageBox.Show("Log In by Facebook Account!\r\nIf Game cant load Your Challenge, let out User Profile and open it again!","User Profile", MessageBoxButton.OK); } private void BG_Player_MediaEnded(object sender, RoutedEventArgs e) { BG_Player.Play(); } private void Storyboard_MoveOut_Completed(object sender, EventArgs e) { LoginComplete(); } private async void Storyboard_MoveIn_Completed(object sender, EventArgs e) { Global.AccessToken = null; await new WebBrowser().ClearCookiesAsync(); } private void Btn_LogInFacebook_UserInfoChanged(object sender, Facebook.Client.Controls.UserInfoChangedEventArgs e) { CreateNewUser(); } } }
using UnityEngine; using System.Collections; public class Actor : GameObject { void Start () { } void Update () { } public void Landed() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using Microsoft.Data.Entity; using SoSmartTv.VideoService.Dto; namespace SoSmartTv.VideoService.Store { public class LocalDatabaseStore : IVideoItemsStoreReader, IVideoItemsStoreWriter { private readonly VideoDbContext _context; public LocalDatabaseStore(VideoDbContext context) { _context = context; } public IObservable<VideoItem> GetVideoItem(string title) { return _context.VideoItems .FirstOrDefaultAsync(x => x.Title == title) .ToObservable(); } public IObservable<IList<VideoItem>> GetVideoItems(IEnumerable<string> titles) { return _context.VideoItems .Where(x => titles.Any(title => title == x.Title)) .ToListAsync() .ToObservable(); } private VideoItem VideoItemOrDefault(VideoItem videoItem, string title) { if (videoItem == null) return new VideoItem() { Title = title }; return videoItem; } public IObservable<VideoDetailsItem> GetVideoDetailsItem(int id) { return _context.VideoDetailsItems .FirstOrDefaultAsync(x => x.Id == id) .ToObservable(); } public IObservable<Unit> PersistVideoItems(IList<VideoItem> items) { _context.VideoItems.AddRange(items); return _context.SaveChangesAsync().ToObservable().Select(_ => Unit.Default); } public IObservable<Unit> PersistVideoDetailsItem(VideoDetailsItem item) { if(item.Id == 0) _context.VideoDetailsItems.Add(item); else _context.VideoDetailsItems.Update(item); return _context.SaveChangesAsync().ToObservable().Select(_ => Unit.Default); } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace InfiniteMeals { public partial class SocialLoginPage : ContentPage { public SocialLoginPage() { InitializeComponent(); this.BindingContext = new SocialLoginPageViewModel(); } void Button_Clicked(System.Object sender, System.EventArgs e) { } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using TNBase.Objects; namespace TNBase.DataStorage.Test.Services { [TestClass] public class ScanServiceTests { [TestMethod] public void AddScans_ShouldAddScansToDatabase() { var scans = new List<Scan> { new Scan { Wallet = 1 }, new Scan { Wallet = 1 } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test", Surname = "Tester", InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); service.AddScans(scans); Assert.AreEqual(2, context.Scans.Count()); } [TestMethod] public void AddScans_ShouldMapValuesCorrectly() { var scans = new List<Scan> { new Scan { Wallet = 1, ScanType = ScanTypes.IN, WalletType = WalletTypes.News }, new Scan { Wallet = 2, ScanType = ScanTypes.OUT, WalletType = WalletTypes.Magazine } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test1", Surname = "Tester", InOutRecords = new InOutRecords() }); context.Listeners.Add(new Listener { Forename = "Test2", Surname = "Tester", InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); service.AddScans(scans); var storedScans = context.Scans.OrderBy(x => x.Wallet).ToList(); Assert.AreEqual(1, storedScans.ElementAt(0).Wallet); Assert.AreEqual(ScanTypes.IN, storedScans.ElementAt(0).ScanType); Assert.AreEqual(WalletTypes.News, storedScans.ElementAt(0).WalletType); Assert.AreEqual(2, storedScans.ElementAt(1).Wallet); Assert.AreEqual(ScanTypes.OUT, storedScans.ElementAt(1).ScanType); Assert.AreEqual(WalletTypes.Magazine, storedScans.ElementAt(1).WalletType); } [TestMethod] public void AddScans_ShouldSetCurrentDate() { var scans = new List<Scan> { new Scan { Wallet = 1 } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test", Surname = "Tester", Stock = 1, MagazineStock = 2, InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); var before = DateTime.UtcNow; service.AddScans(scans); var after = DateTime.UtcNow; var storedScan = context.Scans.First(); Assert.IsTrue(before <= storedScan.Recorded, "Date is greater or equal to before"); Assert.IsTrue(after >= storedScan.Recorded, "Date is less or equal to after"); } [TestMethod] public void AddScans_ShouldIncrementNewsStock_WhenNewsScanInAdded() { var scans = new List<Scan> { new Scan { Wallet = 1, ScanType = ScanTypes.IN, WalletType = WalletTypes.News } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test", Surname = "Tester", Stock = 1, MagazineStock = 2, InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); service.AddScans(scans); var listener = context.Listeners.FirstOrDefault(); Assert.AreEqual(2, listener.Stock); Assert.AreEqual(2, listener.MagazineStock); } [TestMethod] public void AddScans_ShouldIncrementMagazineStock_WhenMagazineScanInAdded() { var scans = new List<Scan> { new Scan { Wallet = 1, ScanType = ScanTypes.IN, WalletType = WalletTypes.Magazine } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test", Surname = "Tester", Stock = 1, MagazineStock = 2, InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); service.AddScans(scans); var listener = context.Listeners.FirstOrDefault(); Assert.AreEqual(1, listener.Stock); Assert.AreEqual(3, listener.MagazineStock); } [TestMethod] public void AddScans_ShouldDecrementNewsStock_WhenNewsScanOutAdded() { var scans = new List<Scan> { new Scan { Wallet = 1, ScanType = ScanTypes.OUT, WalletType = WalletTypes.News } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test", Surname = "Tester", Stock = 1, MagazineStock = 2, InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); service.AddScans(scans); var listener = context.Listeners.FirstOrDefault(); Assert.AreEqual(0, listener.Stock); Assert.AreEqual(2, listener.MagazineStock); } [TestMethod] public void AddScans_ShouldDecrementMagazineStock_WhenMagazineScanOutAdded() { var scans = new List<Scan> { new Scan { Wallet = 1, ScanType = ScanTypes.OUT, WalletType = WalletTypes.Magazine } }; using var context = new Repository.TNBaseContext("Data Source=:memory:"); context.UpdateDatabase(); context.Listeners.Add(new Listener { Forename = "Test", Surname = "Tester", Stock = 1, MagazineStock = 2, InOutRecords = new InOutRecords() }); context.SaveChanges(); var service = new ScanService(context); service.AddScans(scans); var listener = context.Listeners.FirstOrDefault(); Assert.AreEqual(1, listener.Stock); Assert.AreEqual(1, listener.MagazineStock); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Data; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities; using DotNetNuke.Entities.Modules; #endregion namespace DotNetNuke.Services.Authentication { /// <summary> /// DNN-4016 /// The UserAuthenticationInfo class provides the Entity Layer for the /// user information in the Authentication Systems. /// </summary> [Serializable] public class UserAuthenticationInfo : BaseEntityInfo, IHydratable { #region Private Members public UserAuthenticationInfo() { AuthenticationToken = Null.NullString; AuthenticationType = Null.NullString; UserAuthenticationID = Null.NullInteger; } #endregion #region Public Properties /// ----------------------------------------------------------------------------- /// <summary> /// Gets and Sets the ID of the User Record in the Authentication System /// </summary> /// ----------------------------------------------------------------------------- public int UserAuthenticationID { get; set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets and Sets the PackageID for the Authentication System /// </summary> /// ----------------------------------------------------------------------------- public int UserID { get; set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets and Sets the type (name) of the Authentication System (eg DNN, OpenID, LiveID) /// </summary> /// ----------------------------------------------------------------------------- public string AuthenticationType { get; set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets and Sets the url for the Logoff Control /// </summary> /// ----------------------------------------------------------------------------- public string AuthenticationToken { get; set; } #endregion #region IHydratable Members /// ----------------------------------------------------------------------------- /// <summary> /// Fills a UserAuthenticationInfo from a Data Reader /// </summary> /// <param name="dr">The Data Reader to use</param> /// ----------------------------------------------------------------------------- public virtual void Fill(IDataReader dr) { UserAuthenticationID = Null.SetNullInteger(dr["UserAuthenticationID"]); UserID = Null.SetNullInteger(dr["UserID"]); AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); AuthenticationToken = Null.SetNullString(dr["AuthenticationToken"]); //Fill base class fields FillInternal(dr); } /// ----------------------------------------------------------------------------- /// <summary> /// Gets and sets the Key ID /// </summary> /// <returns>An Integer</returns> /// ----------------------------------------------------------------------------- public virtual int KeyID { get { return UserAuthenticationID; } set { UserAuthenticationID = value; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace E_Commerce.Models.Helper { public class UserPassword { public int UserID { get; set; } [StringLength(maximumLength: 1000, ErrorMessage = "Şifre 3 karakterden az olamaz", MinimumLength = 3), DataType(DataType.Password), Display(Name = "Eski Şifrenizi giriniz"), Required(ErrorMessage = "Lütfen Eski Şifrenizi Giriniz") ] public string OldPassword { get; set; } [StringLength(maximumLength: 1000, ErrorMessage = "Şifre 3 karakterden az olamaz", MinimumLength = 3), DataType(DataType.Password), Display(Name = "Yeni Şifrenizi giriniz"), Required(ErrorMessage = "Lütfen Yeni Şifrenizi Giriniz") ] public string NewPassword { get; set; } [StringLength(maximumLength: 1000, ErrorMessage = "Şifre 3 karakterden az olamaz", MinimumLength = 3), DataType(DataType.Password), Display(Name = "Yeni Şifrenizi Tekrar giriniz"), Required(ErrorMessage = "Lütfen Yeni Şifrenizi Tekrar Giriniz") ] public string NewPasswordAgain { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; using System.Net.Sockets; public class TCPSocketClient : MonoBehaviour { public String host = "localhost"; public Int32 port = 50000; internal Boolean socket_ready = false; internal String input_buffer = ""; TcpClient tcp_socket; NetworkStream net_stream; StreamWriter socket_writer; StreamReader socket_reader; void Update() { if (!socket_ready) return; string received_data = readSocket(); if (received_data != "") { // Do something with the received data, // print it in the log for now Debug.Log(received_data); string[] words = received_data.ToString().TrimEnd('\r','\n').Split(' '); /*foreach (string w in words) { Debug.Log(w); }*/ if (words[0] == "earth" && words[1] == "reset") { Debug.Log("RESET RECEIVED!"); GetComponent<MainController>().SendMessage("reset_scene"); } else if (words[0] == "earth") { // get the other params int bases = Convert.ToInt32(words[1]); int munitions = Convert.ToInt32(words[2]); int cadence = Convert.ToInt32(words[3]); GetComponent<MainController>().SendMessage("update_earth_bases", bases); GetComponent<MainController>().SendMessage("update_earth_munitions", munitions); GetComponent<MainController>().SendMessage("update_earth_cadence", cadence); } else if (words[0] == "alien1") { // get the other param int cadence = Convert.ToInt32(words[1]); GetComponent<MainController>().SendMessage("update_alien1", cadence); } else if (words[0] == "alien2") { // get the other param int cadence = Convert.ToInt32(words[1]); GetComponent<MainController>().SendMessage("update_alien2", cadence); } else if (words[0] == "alien3") { // get the other param int cadence = Convert.ToInt32(words[1]); GetComponent<MainController>().SendMessage("update_alien3", cadence); } // then answer writeSocket("999\r"); } /* string key_stroke = Input.inputString; // Collects keystrokes into a buffer if (key_stroke != "") { input_buffer += key_stroke; Debug.Log("detected: " + key_stroke); if (key_stroke == "\r") { // Send the buffer, clean it Debug.Log("Sending: " + input_buffer); writeSocket(input_buffer); input_buffer = ""; } } */ } void Awake() { setupSocket(); } void OnApplicationQuit() { closeSocket(); } public void setupSocket() { try { tcp_socket = new TcpClient(host, port); net_stream = tcp_socket.GetStream(); socket_writer = new StreamWriter(net_stream); socket_reader = new StreamReader(net_stream); socket_ready = true; Debug.Log("Client TCP connecté! :)"); } catch (Exception e) { // Something went wrong Debug.Log("Socket error: " + e); } } public void writeSocket(string line) { if (!socket_ready) return; line = line + "\r\n"; socket_writer.Write(line); socket_writer.Flush(); } public String readSocket() { if (!socket_ready) return ""; if (net_stream.DataAvailable) return socket_reader.ReadLine(); return ""; } public void closeSocket() { if (!socket_ready) return; socket_writer.Close(); socket_reader.Close(); tcp_socket.Close(); socket_ready = false; } }