text
stringlengths
13
6.01M
using UnityEngine; public class FollowAnimPlayer : MonoBehaviour { [SerializeField] GameObject animPlayer; void FixedUpdate() { transform.position = new Vector3(animPlayer.transform.position.x, transform.position.y, animPlayer.transform.position.z); } }
using System; using System.Collections.Generic; using System.Linq; using ILogging; using ServiceDeskSVC.DataAccess.Models; namespace ServiceDeskSVC.DataAccess.Repositories { public class HelpDeskTicketDocumentRepository : IHelpDeskTicketDocumentRepository { private readonly ServiceDeskContext _context; private readonly ILogger _logger; public HelpDeskTicketDocumentRepository(ServiceDeskContext context, ILogger logger) { _context = context; _logger = logger; } public List<HelpDesk_TicketDocuments> GetAllDocumentsForTicket(int ticketId) { List<HelpDesk_TicketDocuments> allDocuments = _context.HelpDesk_TicketDocuments.Where(x => x.TicketID == ticketId).ToList(); return allDocuments; } public HelpDesk_TicketDocuments GetSingleDocument(int documentId) { HelpDesk_TicketDocuments singleDoc = _context.HelpDesk_TicketDocuments.FirstOrDefault(x => x.Id == documentId); return singleDoc; } public int SaveDocument(HelpDesk_TicketDocuments document) { _context.HelpDesk_TicketDocuments.Add(document); _context.SaveChanges(); return document.Id; } public bool DeleteDocument(int documentID) { try { HelpDesk_TicketDocuments doc = _context.HelpDesk_TicketDocuments.FirstOrDefault(x => x.Id == documentID); _context.HelpDesk_TicketDocuments.Remove(doc); _context.SaveChanges(); _logger.Debug("Ticket documetn with id " + documentID + " was deleted."); return true; } catch (Exception ex) { _logger.Error(ex); return false; } } } }
using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201312101120)] public class VersionPersonFinalDecision : Migration { public override void Down() { Delete.Column("Version").FromTable("SCR_ScreeningRequestPersonFinalDecision"); } public override void Up() { Alter.Table("SCR_ScreeningRequestPersonFinalDecision").AddColumn("Version").AsInt32().NotNullable().WithDefaultValue(0); } } }
namespace Assets.src.contexts { public interface IInputService : IService { } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; public class GameOverController : MonoBehaviour { public AudioSource playAgainAudio; /// <summary> /// Volta para o jogo novamente /// </summary> public void PlayAgain(){ playAgainAudio.Play (); UnityAdControle.ShowAdReward(); SceneManager.LoadScene (1); } /// <summary> /// Retorna para o menu inicial /// </summary> public void QuitGame(){ SceneManager.LoadScene(0); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using LauncherLib.Utilities; using Newtonsoft.Json.Linq; namespace LauncherLib.Configs { using WindowSize = OrderedPair; using Memory = OrderedPair; public class Config:IJsonConfig { const string DefaultJVMArgs = "-XX:+UseG1GC "+ "-XX:MaxGCPauseMillis=30 "+ "-XX:-UseAdaptiveSizePolicy "+ "-XX:-OmitStackTraceInFastThrow "; const string DefaultMCArgs = "-Dfml.ignoreInvalidMinecraftCertificates=true "+ "-Dfml.ignorePatchDiscrepancies=true "; const int DefaultMinMem = 1024; const int DefaultMaxMem = 1024; const int DefaultWinWid = 854; const int DefaultWinHgt = 480; const string DefaultGamePath = @".\.minecraft"; public PlayerInfo player; /// <summary> /// x for MinMemory; /// y for MaxMemory /// </summary> public Memory memory; public string JavaPath; public string GamePath; /// <summary> /// x for width; /// y for height /// </summary> public WindowSize windowSize; public string JVMArguments; public string MCArguments; public string Server; public bool EnterServer; JObject ConfigJson; public Config(JObject jObject) { ConfigJson = jObject; memory.x = ConfigJson != null ? ConfigJson["MinMem"] != null ? Convert.ToInt32(ConfigJson["MinMem"].ToString()) : DefaultMinMem : DefaultMinMem; memory.y = ConfigJson != null ? ConfigJson["MaxMem"] != null ? Convert.ToInt32(ConfigJson["MaxMem"].ToString()) : DefaultMaxMem : DefaultMaxMem; JavaPath = ConfigJson != null ? ConfigJson["JavaPath"] != null ? ConfigJson["JavaPath"].ToString() : PathTools.GetJavaPath() : PathTools.GetJavaPath(); GamePath = ConfigJson != null ? ConfigJson["GamePath"] != null ? ConfigJson["GamePath"].ToString() : DefaultGamePath : DefaultGamePath; JVMArguments = ConfigJson != null ? ConfigJson["JVMArguments"] != null ? ConfigJson["JVMArguments"].ToString() : DefaultJVMArgs : DefaultJVMArgs; MCArguments = ConfigJson != null ? ConfigJson["MCArguments"] != null ? ConfigJson["MCArguments"].ToString() : DefaultMCArgs : DefaultMCArgs; windowSize.x = ConfigJson != null ? ConfigJson["WindowWidth"] != null ? Convert.ToInt32(ConfigJson["WindowWidth"].ToString()) : DefaultWinWid : DefaultWinWid; windowSize.y = ConfigJson != null ? ConfigJson["WindowHeight"] != null ? Convert.ToInt32(ConfigJson["WindowHeight"].ToString()) : DefaultWinHgt : DefaultWinHgt; Server = ConfigJson != null ? ConfigJson["Server"] != null ? ConfigJson["Server"].ToString() : null : null; EnterServer = ConfigJson != null ? ConfigJson["EnterServer"] != null ? Convert.ToInt32(ConfigJson["EnterServer"].ToString()) != 0 ? true : false : false : false; player = ConfigJson != null ? ConfigJson["Player"] != null ? ConfigJson["Player"]["Name"] != null && ConfigJson["Player"]["UUID"] != null ? new PlayerInfo(ConfigJson["Player"]["Name"].ToString(), ConfigJson["Player"]["UUID"].ToString()) : new PlayerInfo("SetName") : new PlayerInfo("SetName") : new PlayerInfo("SetName"); } public JObject JsonNewConfig() { JObject jObject = new JObject ( new JProperty("GamePath", GamePath), new JProperty("JavaPath",JavaPath), new JProperty("MinMem",memory.x), new JProperty("MaxMem",memory.y), new JProperty("JVMArguments",JVMArguments), new JProperty("MCArguments", MCArguments), new JProperty("WindowWidth", windowSize.x), new JProperty("WindowHeight",windowSize.y), new JProperty("Server",Server), new JProperty("EnterServer",EnterServer == true?1:0), new JProperty ( "Player", new JObject ( new JProperty("Name",player.Name), new JProperty("UUID",player.UUID) ) ) ); return jObject; } public JObject UpdateJsonObj() { return ConfigJson; } public bool WriteJsonObj() { throw new NotImplementedException(); } public override string ToString() { return "MinMem:\t\t\t" +memory.x.ToString()+"\n"+ "MaxMem:\t\t\t" + memory.y.ToString()+"\n" + "JavaPath:\t\t"+JavaPath+"\n" + "GamePath:\t\t"+GamePath+"\n" + "JVMArgs:\t\t"+JVMArguments+"\n" + "MCArgs:\t\t\t" + MCArguments+"\n" + "PlayerName:\t\t"+player.Name+"\n" + "PlayerUUID:\t\t"+player.UUID+"\n" + "WindowWidth:\t"+windowSize.x+"\n" + "WindowHeight:\t"+windowSize.y+"\n" + "Server:\t\t\t" + Server+"\n" + "EnterServer:\t" +EnterServer.ToString()+ "\n"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LookieLooks.Api.Model { public class ClosedGame { public int ProductId { get; set; } public IDictionary<string, string> ClosedAttributes { get; set; } public bool isClosed { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using LogModule.Loggers.TraceLogger.Writers; using LogModule.LogTypes; namespace LogModule.Loggers.TraceLogger { public class TraceLogger : AbstractLogger { private readonly ErrorLogType errorLog; private readonly DebugLogType debugLog; private readonly InfoLogType infoLog; private readonly Dictionary<LogType, AbstractLogType> logTypeTable; public TraceLogger() { ConsoleTraceListener consoleTraceListener = new ConsoleTraceListener(); Trace.Listeners.Add(consoleTraceListener); errorLog = new ErrorLogType(new ErrorTraceWriter()); debugLog = new DebugLogType(new DebugTraceWriter()); infoLog = new InfoLogType(new InfoTraceWriter()); logTypeTable = new Dictionary<LogType, AbstractLogType> { {LogType.Error, errorLog}, {LogType.Debug, debugLog}, {LogType.Info, infoLog} }; } public override void Error(object message) { Log(errorLog, message); } public override void Debug(object message) { Log(debugLog, message); } public override void Info(object message) { Log(infoLog, message); } public override void AddActionBefore(LogType logType, Action handler) { foreach (var typePair in logTypeTable) { if ((logType & typePair.Key) == typePair.Key) { typePair.Value.BeginExecute += handler; } } } public override void RemoveActionBefore(LogType logType, Action handler) { foreach (var typePair in logTypeTable) { if ((logType & typePair.Key) == typePair.Key) { typePair.Value.BeginExecute -= handler; } } } public override void AddActionAfter(LogType logType, Action handler) { foreach (var typePair in logTypeTable) { if ((logType & typePair.Key) == typePair.Key) { typePair.Value.EndExecute += handler; } } } public override void RemoveActionAfter(LogType logType, Action handler) { foreach (var typePair in logTypeTable) { if ((logType & typePair.Key) == typePair.Key) { typePair.Value.EndExecute -= handler; } } } public override void ClearAllActions(LogType logType) { foreach (var typePair in logTypeTable) { if ((logType & typePair.Key) == typePair.Key) { typePair.Value.BeginExecute = null; typePair.Value.EndExecute = null; } } } private void Log(AbstractLogType logType, object message) { logType.Execute($"{GetCallerMethodName()} => {message}"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; // IV added for reading Data Base using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace VARP { public partial class RollingMill : Form { public RollingMill() { InitializeComponent(); } private void RollingMill_Load(object sender, EventArgs e) { comboProductStatus.SelectedIndex = 1; LoadData(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private bool IfProductExist(SqlConnection con, string productCode) { SqlDataAdapter sda = new SqlDataAdapter("Select * From [VARP].[dbo].[Products] WHERE [ProductCode] = '" + productCode +"' ", con); DataTable dt = new DataTable(); sda.Fill(dt); return Convert.ToBoolean (dt.Rows.Count); } private void addProduct_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=VARP;Integrated Security=True"); //IV Insert Logic con.Open(); bool status = !Convert.ToBoolean( comboProductStatus.SelectedIndex); // 1 = Active; 0-Deactive var sqlQuery = ""; if (IfProductExist(con, txtProcuctCode.Text)) { sqlQuery = @"UPDATE [Products] SET [ProductName] = '" + txtProductName.Text + "', [ProductStatus] ='" + status + "' WHERE [ProductCode] = '" + txtProcuctCode.Text + "'"; } else { sqlQuery = @"INSERT INTO [VARP].[dbo].[Products]([ProductCode],[ProductName],[ProductStatus]) VALUES ('" + txtProcuctCode.Text + "', '" + txtProductName.Text + "','" + status + "')"; } SqlCommand cmd = new SqlCommand(sqlQuery, con); cmd.ExecuteNonQuery(); con.Close(); //IV Reading Data SQL LoadData(); } private void productDelete_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=VARP;Integrated Security=True"); var sqlQuery = ""; if (IfProductExist(con, txtProcuctCode.Text)) { con.Open(); sqlQuery = @"DELETE FROM [Products] WHERE [ProductCode] = '" + txtProcuctCode.Text + "'"; SqlCommand cmd = new SqlCommand(sqlQuery, con); cmd.ExecuteNonQuery(); con.Close(); txtProcuctCode.Text = ""; txtProductName.Text = ""; comboProductStatus.SelectedIndex = 1; } else { MessageBox.Show("Record Not Exist..."); } LoadData(); } private void LoadData() { SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=VARP;Integrated Security=True"); SqlDataAdapter sda = new SqlDataAdapter("Select * From [VARP].[dbo].[Products]", con); DataTable dt = new DataTable(); dataGridView1.Rows.Clear(); sda.Fill(dt); foreach (DataRow item in dt.Rows) { int n = dataGridView1.Rows.Add(); dataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString(); dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString(); if ((bool)item["ProductStatus"]) { dataGridView1.Rows[n].Cells[2].Value = "Active"; } else { dataGridView1.Rows[n].Cells[2].Value = "Deactive"; } } } private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e) { txtProcuctCode.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); txtProductName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); if (dataGridView1.SelectedRows[0].Cells[2].Value.ToString() == "Active") { comboProductStatus.SelectedIndex = 0; } else { comboProductStatus.SelectedIndex = 1; } } } }
using Pe.Stracon.Politicas.Aplicacion.Core.Base; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using System.Collections.Generic; namespace Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract { /// <summary> /// Definición del servicio de aplicación UnidadOperativaService /// </summary> /// <remarks> /// Creación: GMD 22150326 <br /> /// Modificación: <br /> /// </remarks> public interface IParametroSeccionService : IGenericService { /// <summary> /// Realiza la busqueda de Parametro Valor /// </summary> /// <param name="filtro">Filtro de Parametro Valor</param> /// <returns>Listado de unidad operativas encontrados</returns> ProcessResult<List<ParametroSeccionResponse>> BuscarParametroSeccion(ParametroSeccionRequest filtro); /// <summary> /// Realiza el registro de un Parámetro Sección /// </summary> /// <param name="filtro">Parámetro Sección a Registrar</param> /// <returns>Indicador de Error</returns> ProcessResult<string> RegistrarParametroSeccion(ParametroSeccionRequest filtro); /// <summary> /// Realiza la eliminación de una sección de parámetro /// </summary> /// <param name="filtro">Sección a Eliminar</param> /// <returns>Indicador de Error</returns> ProcessResult<string> EliminarParametroSeccion(ParametroSeccionRequest filtro, bool autoGuardado = true); /// <summary> /// Realiza la eliminación masiva de secciones de parámetro /// </summary> /// <param name="filtro">Lista de secciones a Eliminar</param> /// <returns>Indicador de Error</returns> ProcessResult<string> EliminarMasivoParametroSeccion(List<ParametroSeccionRequest> filtro); } }
using System.ComponentModel.DataAnnotations; namespace GIFU.Models { public class Account { public int? UserId { get; set; } [Required(ErrorMessage = "此欄位必填")] public string Email { get; set; } [Required(ErrorMessage = "此欄位必填")] public string Passwd { get; set; } [Required(ErrorMessage = "此欄位必填")] public string Name { get; set; } public string Sex { get; set; } public string Birthday { get; set; } public string Phone { get; set; } public string Address { get; set; } public int ProvideCount { get; set; } public string PhotoType { get; set; } public string IsValid { get; set; } public string UserType { get; set; } public string UpdateDate { get; set; } public string Token { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using DelftTools.Functions; using DelftTools.Functions.Filters; using DelftTools.Functions.Generic; using DelftTools.Utils.Aop; using DelftTools.Utils.Collections; using DelftTools.Utils.Collections.Generic; using DelftTools.Utils.Data; using DelftTools.Utils.IO; using DelftTools.Utils.Reflection; using GeoAPI.Extensions.Coverages; using GeoAPI.Geometries; using GisSharpBlog.NetTopologySuite.Geometries; using log4net; using NetTopologySuite.Extensions.Coverages; using OSGeo.GDAL; using SharpMap.Utilities; using io = System.IO; namespace SharpMap.Extensions.Data.Providers { /// <summary> /// Store which always contains functions in a fixed order: /// x /// y /// values /// time (optional) /// </summary> [ParameterValidationAspect] public class GdalFunctionStore : Unique<long>, IFunctionStore, IFileBased { private static readonly ILog log = LogManager.GetLogger(typeof(GdalFunctionStore)); private Dataset gdalDataset; private string path; private IEventedList<IFunction> functions; private IMultiDimensionalArray xValues; private IMultiDimensionalArray yValues; private static IRegularGridCoverage emptyGrid = new RegularGridCoverage(); private static IEventedList<IFunction> emptyGridFunctions = new EventedList<IFunction>(); private GdalState state; enum GdalState { Closed, DefineMode, Initializing, Defined } static GdalFunctionStore() { emptyGridFunctions.Add(emptyGrid); emptyGridFunctions.Add(emptyGrid.X); emptyGridFunctions.Add(emptyGrid.Y); emptyGridFunctions.AddRange(emptyGrid.Components.Cast<IFunction>()); } public GdalFunctionStore() { state = GdalState.Closed; TypeConverters = new List<ITypeConverter>(); Functions = new EventedList<IFunction>(); } ~GdalFunctionStore() { Close(); } private void Functions_CollectionChanging(object sender, NotifyCollectionChangingEventArgs e) { if(!AutoOpen()) { return; } if ((e.Action == NotifyCollectionChangeAction.Add || e.Action == NotifyCollectionChangeAction.Replace) && e.Item is IRegularGridCoverage) { var grid = (IRegularGridCoverage)e.Item; var driverName = GdalHelper.GetDriverName(path); RegisterGdal(); using (var gdalDriver = Gdal.GetDriverByName(driverName)) { var gdalType = GdalHelper.GetGdalDataType(gdalDriver, grid.Components[0].ValueType); var gdalvariableValue = GdalHelper.GetVariableForDataType(gdalType);// TODO: strange logic, use supported GDAL types here (as .NET types) instead var type = gdalvariableValue.ValueType; if (type != grid.Components[0].ValueType) { throw new InvalidOperationException(string.Format("Value type {0} is not supported by GDAL driver", grid.Components[0].ValueType)); } } } } private static bool gdalInitialized; private static void RegisterGdal() { if (!gdalInitialized) { Gdal.AllRegister(); //register gdal drivers var maxGdalCacheSize = Gdal.GetCacheMax(); log.DebugFormat("Adding max GDAL cache size to GC memory pressure: {0}", maxGdalCacheSize); GC.AddMemoryPressure(maxGdalCacheSize); gdalInitialized = true; } } private void Functions_CollectionChanged(object sender, NotifyCollectionChangingEventArgs e) { if(!AutoOpen()) { return; } if (state == GdalState.Initializing) return; var function = (IFunction)e.Item; switch (e.Action) { case NotifyCollectionChangeAction.Add: AddFunction(function); function.Store = this; break; case NotifyCollectionChangeAction.Remove: break; case NotifyCollectionChangeAction.Replace: throw new NotSupportedException(); } } #region IFileBased Members public virtual string Path { get { return path; } set { path = value; } } public void CreateNew(string path) { if (IsOpen) { Close(); } if (File.Exists(path)) { File.Delete(path); } this.path = path; //Functions.Clear(); // clear grid functions.Clear(); // clear grid IsOpen = true; } public void Close() { if (gdalDataset != null) { gdalDataset.Dispose(); // dont forget to call dispose for preventing memory leaks} gdalDataset = null; } // Prevent calling GC.Collect() at all costs. It is very slow; closing project with many gdal stores //// make sure all references to gdal objects are freed to avoid lock on files //// GC.Collect(); IsOpen = false; } private bool isOpening; public void Open(string path) { if (isOpening) return; isOpening = true; try { this.path = path; if (!File.Exists(path)) { throw new FileNotFoundException(String.Format("The following file does not exist: {0}", path)); } log.DebugFormat("Opening grid using GDAL: {0}", path); state = GdalState.Initializing; OpenGdalDataset(path); //if (Functions.Count == 0) if (functions.Count == 0) { CreateSchemaFromDataset(); } state = GdalState.Defined; IsOpen = true; } finally // makes sure flag is reset { isOpening = false; } } public bool IsOpen { get; private set; } public void SwitchTo(string newPath) { Close(); Open(newPath); } public void CopyTo(string newPath) { var sourceDir = io.Path.GetDirectoryName(path); var targetDir = io.Path.GetDirectoryName(newPath); var extension = io.Path.GetExtension(path).ToLower(); File.Copy(path, newPath); var oldFileName = io.Path.GetFileNameWithoutExtension(path); var newFileName = io.Path.GetFileNameWithoutExtension(newPath); switch (extension) { case ".bil": var hdrFileName = io.Path.Combine(sourceDir, oldFileName + ".hdr"); File.Copy(hdrFileName, io.Path.Combine(targetDir, newFileName + ".hdr")); break; } } public void Delete() { if(IsOpen) { Close(); } File.Delete(path); log.WarnFormat("TODO: delete all sattelite GDAL files (projection, headers, etc.)"); } #endregion private void CreateSchemaFromDataset() { var grid = CreateRegularGridCoverage(gdalDataset); grid.Store = this; // add grid, grid components and arguments to the list of functions managed by the current store functions.Add(grid); functions.Add(grid.X); functions.Add(grid.Y); functions.AddRange(grid.Components.Cast<IFunction>()); } private static IRegularGridCoverage CreateRegularGridCoverage(Dataset dataset) { var gridName = System.IO.Path.GetFileNameWithoutExtension(dataset.GetFileList()[0]); IRegularGridCoverage grid = new RegularGridCoverage { Name = gridName }; grid.X.FixedSize = dataset.RasterXSize; grid.Y.FixedSize = dataset.RasterYSize; //set Grid geometry var geometryFactory = new GeometryFactory(); // TODO: add CRS! var extents = GdalHelper.GetExtents(dataset); grid.Geometry = geometryFactory.ToGeometry(extents); // replace grid components by the components found in GDAL dataset grid.Components.Clear(); var gridComponents = GetDataSetComponentVariables(dataset); grid.Components.AddRange(gridComponents); return grid; } static Envelope emptyEnvelope = new Envelope(); public virtual IEnvelope GetExtents() { if(!AutoOpen()) { return emptyEnvelope; } return GdalHelper.GetExtents(gdalDataset); } #region IFunctionStore Members // INotifyCollectionChange public virtual event NotifyCollectionChangedEventHandler CollectionChanged; public virtual event NotifyCollectionChangingEventHandler CollectionChanging; // ICloneable public object Clone() { var clone = new GdalFunctionStore { FireEvents = FireEvents }; try { clone.Open(Path); // replace all function names in the cloned store by the current function names (GDAL store may not remember them) for (var i = 0; i < Functions.Count; i++) { clone.Functions[i].Name = Functions[i].Name; } } catch(Exception e) { // swallow exception because we can be seen as IFeatureProvider log.Error("Can't open file: " + Path, e); } return clone; } public IEventedList<IFunction> Functions { get { AutoOpen(); return functions; } set { if (functions != null) { functions.CollectionChanged -= Functions_CollectionChanged; functions.CollectionChanging -= Functions_CollectionChanging; } functions = value; if (functions != null) { functions.CollectionChanging += Functions_CollectionChanging; functions.CollectionChanged += Functions_CollectionChanged; } } } /// <summary> /// Updates the component values for a regular grid. /// </summary> /// <param name="variable"></param> /// <param name="values"></param> /// <param name="filters"></param> public void SetVariableValues<T>(IVariable variable, IEnumerable<T> values, params IVariableFilter[] filters) { if(!AutoOpen()) { return; // nothing to do } if ((!Grid.Components.Contains(variable))) { throw new ArgumentOutOfRangeException("unsupported function in SetValues call arguments: " + variable); } int componentIndex = Grid.Components.IndexOf(variable); SetGdalValues(componentIndex, values.ToArray(), filters); } /// <summary> /// Use netcdf driver to create datastore with the right dimensions /// </summary> public IMultiDimensionalArray GetVariableValues(IVariable variable, params IVariableFilter[] filters) { if(!AutoOpen()) { return emptyGrid.Components[0].GetValues(); } log.DebugFormat("Getting values for variable {0}", variable.Name); //Non Gdal Values if (variable.Name.Equals("x")) { //return xValues ?? new MultiDimensionalArray<double>(); var geoTrans = new double[6]; gdalDataset.GetGeoTransform(geoTrans); var transform = new RegularGridGeoTransform(geoTrans); var sizeX = gdalDataset.RasterXSize; var sizeY = gdalDataset.RasterYSize; var deltaX = transform.HorizontalPixelResolution; var deltaY = transform.VerticalPixelResolution; var origin = new Coordinate(transform.Left, transform.Top - deltaY * sizeY); return GetValuesArray(deltaX, sizeX, origin.X); } if (variable.Name.Equals("y")) { //return yValues ?? new MultiDimensionalArray<double>(); var geoTrans = new double[6]; gdalDataset.GetGeoTransform(geoTrans); var transform = new RegularGridGeoTransform(geoTrans); var sizeY = gdalDataset.RasterYSize; var deltaY = transform.VerticalPixelResolution; var origin = new Coordinate(transform.Left, transform.Top - deltaY * sizeY); return GetValuesArray(deltaY, sizeY, origin.Y); } if (!Grid.Components.Contains(variable)) { throw new NotSupportedException("Variable not part of grid:" + variable.Name); } //TODO: switch GetVariableValues and GetVariableValues<T> so that the non-generic calls the generic version. switch (variable.ValueType.ToString()) { case "System.Byte": return GetGdalValues<byte>(Grid.Components.IndexOf(variable), filters); case "System.Integer": case "System.Int32": return GetGdalValues<int>(Grid.Components.IndexOf(variable), filters); case "System.Int16": return GetGdalValues<Int16>(Grid.Components.IndexOf(variable), filters); case "System.UInt32": return GetGdalValues<UInt32>(Grid.Components.IndexOf(variable), filters); case "System.UInt16": return GetGdalValues<UInt16>(Grid.Components.IndexOf(variable), filters); case "System.Float": case "System.Single": return GetGdalValues<float>(Grid.Components.IndexOf(variable), filters); default: return GetGdalValues<double>(Grid.Components.IndexOf(variable), filters); } } public IMultiDimensionalArray<T> GetVariableValues<T>(IVariable function, params IVariableFilter[] filters) { if(!AutoOpen()) { return emptyGrid.GetValues<T>(); } if (filters.Length == 0 && Grid.Components.Contains(function)) { return new LazyMultiDimensionalArray<T>( () => (IMultiDimensionalArray<T>)GetVariableValues(function), () => GetGridComponentValuesCount(function)); } return (IMultiDimensionalArray<T>)GetVariableValues(function, filters); } /// <summary> /// Gets the count of the component specified using a 'special' Gdal call. /// </summary> /// <param name="function"></param> /// <returns></returns> private int GetGridComponentValuesCount(IVariable function) { if(!AutoOpen()) { return 0; } //does this cut it for timedepend stuff?...do we have this in Gdal? var count = gdalDataset.RasterXSize*gdalDataset.RasterYSize; return count; /*using (var band = gdalDataset.GetRasterBand(1)) { gdalDataset.get }*/ } public void RemoveFunctionValues(IFunction function, params IVariableValueFilter[] filters) { throw new NotImplementedException("Write (band, x, y) values directly to file (if supported)"); } public virtual event EventHandler<FunctionValuesChangingEventArgs> BeforeFunctionValuesChanged; public virtual event EventHandler<FunctionValuesChangingEventArgs> FunctionValuesChanged; public virtual event EventHandler<FunctionValuesChangingEventArgs> FunctionValuesChanging; public virtual IList<ITypeConverter> TypeConverters { get; set; } public virtual bool FireEvents { get; set; } public void UpdateVariableSize(IVariable variable) { //throw new NotImplementedException(); } public T GetMaxValue<T>(IVariable variable) { if(!AutoOpen()) { return default(T); } using (var band = gdalDataset.GetRasterBand(1)) { double maximum; int hasValue; band.GetMaximum(out maximum, out hasValue); if (hasValue == 0) { double[] values = new double[2]; band.ComputeRasterMinMax(values, 0); maximum = values[1]; } return (T)Convert.ChangeType(maximum, typeof(T)); } } public T GetMinValue<T>(IVariable variable) { if (!AutoOpen()) { return default(T); } using (var band = gdalDataset.GetRasterBand(1)) { double minimum; int hasValue; band.GetMinimum(out minimum, out hasValue); if (hasValue == 0) { double[] values = new double[2]; band.ComputeRasterMinMax(values, 0); minimum = values[0]; } return (T)Convert.ChangeType(minimum, typeof(T)); } } public virtual void CacheVariable(IVariable variable) { //throw new NotImplementedException(); } public virtual bool DisableCaching { get; set; } #endregion private bool AutoOpen() { try { if (!IsOpen && !string.IsNullOrEmpty(Path)) { Open(Path); } } catch (Exception e) { log.Error("Can't open raster file (GDAL): " + Path, e); return false; } return true; } private IRegularGridCoverage grid; public IRegularGridCoverage Grid { get { if(!AutoOpen()) { return emptyGrid; } if (Functions.Count == 0) { return grid ?? (grid = new RegularGridCoverage()); } return (IRegularGridCoverage)Functions[0]; } } struct RasterBoundaries { public int StartX; public int StartY; public int WidthX; public int WidthY; } public Dataset GdalDataset { get { return gdalDataset; } } public virtual void AddIndependendVariableValues<T>(IVariable variable, IEnumerable<T> values) { //GDAL is not intereset in x and y. //SetVariableValues(variable,values); } private void OpenGdalDataset(string path) { if (IsOpen) { Close(); } RegisterGdal(); CheckAndFixHeaders(path); gdalDataset = Gdal.Open(path.ToLower(), Access.GA_Update); SetDriver(path); /* var geoTrans = new double[6]; gdalDataset.GetGeoTransform(geoTrans); var transform = new RegularGridGeoTransform(geoTrans); int sizeX = gdalDataset.RasterXSize; int sizeY = gdalDataset.RasterYSize; // double deltaX = sizeX/gdalDataset.RasterCount; double deltaX = transform.HorizontalPixelResolution; double deltaY = transform.VerticalPixelResolution; var origin = new Coordinate(transform.Left, transform.Top - deltaY * sizeY); /yValues = GetValuesArray(deltaY, sizeY, origin.Y); /xValues = GetValuesArray(deltaX, sizeX, origin.X); */ } private void SetDriver(string path) { using (var driver = gdalDataset.GetDriver()) { if (!GdalHelper.IsCreateSupported(driver)) { log.WarnFormat("Datasource is readonly: {0}", path); return; } //cannot directly create dataset. check if dataset can be created by copying from another set if (GdalHelper.IsCreateCopySupported(driver)) { //TODO: fix this criteria if (GetDatasetSize() < 1000000) { log.Debug("Using in-memory driver to facilitate writing to datasource"); //log.WarnFormat("Using in memory-driver with large dataset can yield unexpected results."); using (var gdalDriver = Gdal.GetDriverByName("MEM")) { var oldGdalDataSet = gdalDataset; gdalDataset = gdalDriver.CreateCopy(path, gdalDataset, 0, new string[] { }, null, null); oldGdalDataSet.Dispose(); } } } } } public int GetDatasetSize() { //TODO: fix this so it works OK..so a 4 bytes per cell per band assumption is here return (gdalDataset.RasterCount * gdalDataset.RasterXSize * gdalDataset.RasterYSize * 4); } private static IEnumerable<IVariable> GetDataSetComponentVariables(Dataset gdalDataset) { IList<IVariable> components = new List<IVariable>(); for (var i = 1; i <= gdalDataset.RasterCount; i++) { using (var band = gdalDataset.GetRasterBand(i)) { var dataType = band.DataType; var componentVariableName = "Raster" + i; var componentVariable = GdalHelper.GetVariableForDataType(dataType); componentVariable.Name = componentVariableName; int hasNoDataValue; double noDataValue; band.GetNoDataValue(out noDataValue, out hasNoDataValue); //ToDo check this logic versus specs of hdr definition for bil files. if (noDataValue < 0 && (dataType == DataType.GDT_UInt32 || dataType == DataType.GDT_UInt16)) { noDataValue = Math.Abs(noDataValue); log.DebugFormat("Nodata value changed from a negative to a positive value"); } if (hasNoDataValue > 0) { componentVariable.NoDataValues = new[] { noDataValue }; } componentVariable.FixedSize = gdalDataset.RasterXSize * gdalDataset.RasterYSize; components.Add(componentVariable); } } return components; } private IMultiDimensionalArray<T> GetGdalValues<T>(int componentIndex, params IVariableFilter[] variableFilters) { bool scale = false; int startX = 0, startY = 0, widthX = Grid.SizeX, widthY = Grid.SizeY; int rasterBandIndex = componentIndex + 1; //1 based index var sizeX = Grid.SizeX; var sizeY = Grid.SizeY; if (variableFilters.Length > 0) { foreach (IVariableFilter filter in variableFilters) { if (filter is VariableAggregationFilter) { var sampleFilter = filter as VariableAggregationFilter; if (sampleFilter.Variable == Grid.X) { startX = sampleFilter.MinIndex; widthX = sampleFilter.Count; sizeX = sampleFilter.MaxIndex - sampleFilter.MinIndex + 1; } if (sampleFilter.Variable == Grid.Y) { startY = Grid.SizeY - sampleFilter.MaxIndex - 1; widthY = sampleFilter.Count; sizeY = sampleFilter.MaxIndex - sampleFilter.MinIndex + 1; } scale = true; continue; } if (filter is IVariableValueFilter) { var variableValueFilter = filter as IVariableValueFilter; if (variableValueFilter.Values.Count > 1) { throw new NotSupportedException( "Multiple values for VariableValueFilter not supported by GDalFunctionStore"); } if (filter.Variable == Grid.X) { startX = Grid.X.Values.IndexOf(variableValueFilter.Values[0]); widthX = 1; } if (filter.Variable == Grid.Y) { //origin of our system is lower left corner, origin of gdal is upper left corner. startY = Grid.SizeY - Grid.Y.Values.IndexOf(variableValueFilter.Values[0]) - 1; widthY = 1; } continue; } if (filter is VariableIndexRangesFilter) { var rangesFilter = ((VariableIndexRangesFilter)filter); if (filter.Variable == Grid.X) { startX = rangesFilter.IndexRanges[0].First; widthX = rangesFilter.IndexRanges[0].Second - startX + 1; } if (filter.Variable == Grid.Y) { // rangesFilter.IndexRanges[0].First; startY = Grid.SizeY - rangesFilter.IndexRanges[0].Second - 1; widthY = Grid.SizeY - startY - rangesFilter.IndexRanges[0].First; } } if (filter is VariableIndexRangeFilter) { var variableIndexRangeFilter = filter as VariableIndexRangeFilter; if (filter.Variable == Grid.X) { startX = variableIndexRangeFilter.MinIndex; widthX = 1 + variableIndexRangeFilter.MaxIndex - variableIndexRangeFilter.MinIndex; } if (filter.Variable == Grid.Y) { startY = Grid.SizeY - variableIndexRangeFilter.MaxIndex - 1; widthY = Grid.SizeY - startY - variableIndexRangeFilter.MinIndex; } continue; } } } //create a generic MDA of [xSize,ySize] with values of dataset. T[] values; if (scale) { values = GdalHelper.GetValuesForBand<T>(gdalDataset, rasterBandIndex, startX, startY, sizeX, sizeY, widthX, widthY); } else { values = GdalHelper.GetValuesForBand<T>(gdalDataset, rasterBandIndex, startX, startY, widthX, widthY); } IMultiDimensionalArray<T> array = (MultiDimensionalArray<T>)TypeUtils.CreateGeneric( typeof(MultiDimensionalArray<>), typeof(T), true, true, Grid.Components[componentIndex]. DefaultValue, values, new[] { widthX, widthY } ); //((MultiDimensionalArray<T>)array).Owner = Grid.Components[componentIndex]; return array; } private void SetGdalValues<T>(int componentIndex, T[] values, params IVariableFilter[] variableFilters) { var rasterBoundaries = GetRasterBoundaries(variableFilters); var rasterBandIndex = componentIndex + 1; //1 based index GdalHelper.SetValuesForBand(gdalDataset, rasterBandIndex, rasterBoundaries.StartX, rasterBoundaries.StartY, rasterBoundaries.WidthX, rasterBoundaries.WidthY, values); gdalDataset.FlushCache(); //update dataset on filesystem by copying in-memory dataset var inMemoryDriver = gdalDataset.GetDriver(); if (!GdalHelper.IsInMemoryDriver(inMemoryDriver)) { return; } Driver targetDatasetDriver = GetTargetDatasetDriver(path); Dataset outputDataset = GetOutputDataset(gdalDataset, inMemoryDriver, targetDatasetDriver, Functions.OfType<IRegularGridCoverage>().FirstOrDefault(), rasterBandIndex, rasterBoundaries, values); WriteGdalDatasetToFile(path, outputDataset); } private static void WriteGdalDatasetToFile(string path, Dataset gdalDataset) { log.Debug("Recreating file and copying data from in-memory datasource."); Driver targetDatasetDriver = GetTargetDatasetDriver(path); using (targetDatasetDriver) { if (GdalHelper.IsCreateCopySupported(targetDatasetDriver)) { targetDatasetDriver.CreateCopy(path, gdalDataset, 0, new string[] { }, null, null) .Dispose(); } } //GC.Collect(); } private static Dataset GetOutputDataset<T>(Dataset gdalDataset, Driver gdalDriver, Driver targetDatasetDriver, IRegularGridCoverage gridCoverage, int rasterBandIndex, RasterBoundaries rasterBoundaries, T[] values) { Dataset outputDataset = gdalDataset; if (targetDatasetDriver.ShortName == "PCRaster") { // Convert the in mem dataset to a pc rasterBoundaries compatible one... Type valueType = gridCoverage.Components[0].ValueType; DataType dataType = GdalHelper.GetGdalDataType(targetDatasetDriver, valueType); outputDataset = gdalDriver.Create(gridCoverage.Name, gdalDataset.RasterXSize, gdalDataset.RasterYSize, gridCoverage.Components.Count, dataType, new string[] { }); GdalHelper.SetValuesForBand(outputDataset, rasterBandIndex, rasterBoundaries.StartX, rasterBoundaries.StartY, rasterBoundaries.WidthX, rasterBoundaries.WidthY, values); } return outputDataset; } private static Driver GetTargetDatasetDriver(string path) { var driverName = GdalHelper.GetDriverName(path); RegisterGdal(); return Gdal.GetDriverByName(driverName); } private RasterBoundaries GetRasterBoundaries(IEnumerable<IVariableFilter> variableFilters) { RasterBoundaries rasterBoundaries = new RasterBoundaries { WidthX = Grid.SizeX, WidthY = Grid.SizeY }; foreach (var filter in variableFilters) { var variableValueFilter = filter as IVariableValueFilter; if (variableValueFilter != null) { if (filter.Variable == Grid.X) { rasterBoundaries.StartX = Grid.X.Values.IndexOf(variableValueFilter.Values[0]); rasterBoundaries.WidthX = 1; } if (filter.Variable == Grid.Y) { rasterBoundaries.StartY = Grid.Y.Values.IndexOf(variableValueFilter.Values[0]); rasterBoundaries.WidthY = 1; } } var variableIndexRangeFilter = filter as VariableIndexRangeFilter; if (variableIndexRangeFilter != null) { if (filter.Variable == Grid.X) { rasterBoundaries.StartX = variableIndexRangeFilter.MinIndex; rasterBoundaries.WidthX = 1 + variableIndexRangeFilter.MaxIndex - variableIndexRangeFilter.MinIndex; } if (filter.Variable == Grid.Y) { rasterBoundaries.StartY = variableIndexRangeFilter.MinIndex; rasterBoundaries.WidthY = 1 + variableIndexRangeFilter.MaxIndex - variableIndexRangeFilter.MinIndex; } } } return rasterBoundaries; } /// <summary> /// Use store to copy values from function to datasource and connect store to function. /// </summary> /// <param name="function"></param> private void AddFunction(IFunction function) { if (!AutoOpen()) { return; } if (!(function is IRegularGridCoverage)) return; if (state == GdalState.Initializing) { return; } var addedCoverage = (IRegularGridCoverage)function; //xValues = addedCoverage.X.Values; //yValues = addedCoverage.Y.Values; //Close(); //clean up resources used by current dataset if any. var driverName = GdalHelper.GetDriverName(path); RegisterGdal(); using (Driver gdalDriver = Gdal.GetDriverByName(driverName)) { VerifyDriverIsValid(gdalDriver); if (addedCoverage.Store is GdalFunctionStore) { //CopyCurrentDatasetFromAddedCoverage((GdalFunctionStore)addedCoverage.Store, gdalDriver); var store = (GdalFunctionStore)addedCoverage.Store; CopyCurrentDatasetFromAddedCoverage(store, gdalDriver); return; } //verify if all components are of the same type VerifyComponentTypesAreSame(addedCoverage); //substitute driver by in-memory driver in case driver is read-only SubstituteDriverByInMemIfReadonly(addedCoverage, gdalDriver); if (gdalDataset == null) { throw new IOException(String.Format("Cannot open file: {0}", path)); } { var transform = new RegularGridGeoTransform(addedCoverage.Origin.X, addedCoverage.Origin.Y + addedCoverage.DeltaY * addedCoverage.SizeY, addedCoverage.DeltaX, addedCoverage.DeltaY); //todo check: lowerleft corner or upperleft corner. (currently using upperleft corner as reference point) gdalDataset.SetGeoTransform(transform.TransForm); // add agruments functions.Add(addedCoverage.X); functions.Add(addedCoverage.Y); if(addedCoverage.X.Parent != null) { // reset parent, since function will have this store as a parent addedCoverage.X.Parent = null; addedCoverage.Y.Parent = null; } //copy components to this store for (int i = 0; i < addedCoverage.Components.Count; i++) { IMultiDimensionalArray componentValues = addedCoverage.Components[i].Values; // reset parent, since function will have this store as a parent if(addedCoverage.Components[i].Parent != null) { addedCoverage.Components[i].Parent = null; } functions.Add(addedCoverage.Components[i]); addedCoverage.Components[i].SetValues(componentValues); } gdalDataset.FlushCache(); } if (gdalDataset == null) { log.ErrorFormat("No GdalDataset available to write/read {0}.", path); } } } private void SubstituteDriverByInMemIfReadonly(IRegularGridCoverage addedCoverage, Driver gdalDriver) { var canCreate = gdalDriver.GetMetadataItem("DCAP_CREATE", null) == "YES"; //cannot create use mem driver. if (!canCreate) { using (var inMemoryDriver = Gdal.GetDriverByName("MEM")) { DataType dataType = GdalHelper.GetGdalDataType(inMemoryDriver, addedCoverage.Components[0].ValueType); if (dataType.Equals(DataType.GDT_Unknown)) { throw new NotSupportedException( String.Format("The datatype {0} cannot be saved to this kind of file: {1}", addedCoverage.Components[0].ValueType, System.IO.Path.GetExtension(path))); } gdalDataset = inMemoryDriver.Create(path, addedCoverage.SizeX, addedCoverage.SizeY, addedCoverage.Components.Count, dataType, new string[] { }); } } else { DataType dataType = GdalHelper.GetGdalDataType(gdalDriver, addedCoverage.Components[0].ValueType); if (dataType.Equals(DataType.GDT_Unknown)) { throw new NotSupportedException( String.Format("The datatype {0} cannot be saved to this kind of file: {1}", addedCoverage.Components[0].ValueType, System.IO.Path.GetExtension(path))); } gdalDataset = gdalDriver.Create(path, addedCoverage.SizeX, addedCoverage.SizeY, addedCoverage.Components.Count, dataType, new string[] { }); } } private void CopyCurrentDatasetFromAddedCoverage(GdalFunctionStore gdalFunctionStore, Driver gdalDriver) { gdalDataset = gdalDriver.CreateCopy(path, gdalFunctionStore.gdalDataset, 0, new string[] { }, null, "Copy"); //substitute driver by in-memory driver in case driver is read-only if (!GdalHelper.IsCreateSupported(gdalDriver)) { using (var inMemoryDriver = Gdal.GetDriverByName("MEM")) { var oldGdalDataSet = gdalDataset; //create in-memory dataset with a copy of the original data. gdalDataset = inMemoryDriver.CreateCopy(path, gdalFunctionStore.gdalDataset, 0, new string[] { }, null, null); oldGdalDataSet.Dispose(); } } } private void VerifyDriverIsValid(Driver gdalDriver) { if (gdalDriver == null) { throw new IOException(String.Format("Cannot find suitable driver to write to this kind of output file: '{0}'", path)); } if (String.Compare(gdalDriver.GetMetadataItem("DCAP_CREATE", null), "YES") != 0) { //verify if driver supports creation by copying from another dataset. if (String.Compare("YES", gdalDriver.GetMetadataItem("DCAP_CREATECOPY", null)) != 0) { //driver does not support writing nor create copy methods to write to this file throw new IOException(String.Format("Cannot find suitable driver to write to this kind of output file: '{0}'", path)); } } } private static IMultiDimensionalArray GetValuesArray(double delta, int size, double offset) { IMultiDimensionalArray result = new MultiDimensionalArray<double>(size); for (var j = 0; j < size; j++) { result[j] = j * delta + offset; } return result; } private static void CheckAndFixHeaders(string path) { if (path.EndsWith(".bil", StringComparison.OrdinalIgnoreCase)) { GdalHelper.CheckBilHdrFileForPixelTypeField(path); } if (path.EndsWith(".asc", StringComparison.OrdinalIgnoreCase)) { GdalHelper.CheckAndFixAscHeader(path); } } private static void VerifyComponentTypesAreSame(IFunction sourceGridCoverage) { var distinctValueTypes = sourceGridCoverage.Components .Select(c => c.ValueType).Distinct(); if (distinctValueTypes.Count() != 1) { throw new NotImplementedException( "All of the components in the dataset should be of the same type"); } } } }
// <copyright file="IAssetService.cs" company="Morten Larsen"> // Copyright (c) Morten Larsen. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> using System.Threading.Tasks; using Microsoft.AspNetCore.Html; namespace AspNetWebpack.AssetHelpers { /// <summary> /// Service for including Webpack assets in UI projects. /// </summary> public interface IAssetService { /// <summary> /// Gets full directory path for assets. /// </summary> string AssetsDirectoryPath { get; } /// <summary> /// Gets web path for UI assets. /// </summary> string AssetsWebPath { get; } /// <summary> /// Gets the full file path. /// </summary> /// <param name="bundle">The bundle filename.</param> /// <param name="fileType">The bundle file type, will append extension to bundle if specified.</param> /// <returns>The full file path.</returns> Task<string?> GetBundlePathAsync(string bundle, FileType? fileType = null); /// <summary> /// Gets a html script tag for the specified asset. /// </summary> /// <param name="bundle">The name of the Webpack bundle.</param> /// <param name="load">Enum for modifying script load behavior.</param> /// <returns>An HtmlString containing the html script tag.</returns> Task<HtmlString> GetScriptTagAsync(string bundle, ScriptLoad load = ScriptLoad.Normal); /// <summary> /// Gets a html script tag for the specified asset. /// </summary> /// <param name="bundle">The name of the Webpack bundle.</param> /// <param name="fallbackBundle">The name of the bundle to fallback to if main bundle does not exist.</param> /// <param name="load">Enum for modifying script load behavior.</param> /// <returns>An HtmlString containing the html script tag.</returns> Task<HtmlString> GetScriptTagAsync(string bundle, string? fallbackBundle, ScriptLoad load = ScriptLoad.Normal); /// <summary> /// Gets a html link tag for the specified asset. /// </summary> /// <param name="bundle">The name of the Webpack bundle.</param> /// <param name="fallbackBundle">The name of the bundle to fallback to if main bundle does not exist.</param> /// <returns>An HtmlString containing the html link tag.</returns> Task<HtmlString> GetLinkTagAsync(string bundle, string? fallbackBundle = null); /// <summary> /// Gets a html style tag for the specified asset. /// </summary> /// <param name="bundle">The name of the Webpack bundle.</param> /// <param name="fallbackBundle">The name of the bundle to fallback to if main bundle does not exist.</param> /// <returns>An HtmlString containing the html style tag.</returns> Task<HtmlString> GetStyleTagAsync(string bundle, string? fallbackBundle = null); } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SerializationDemo { public class GenericObjectConverter : JsonConverter { public GenericObjectConverter(Parameter[] parameters ) { Parameters = parameters; } public Parameter[] Parameters { get; set; } public override bool CanConvert(Type objectType) { return typeof(GenericObject) == objectType; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { GenericObject obj = new GenericObject(); var json = JObject.ReadFrom(reader) as JObject; foreach( var param in Parameters ) { var property = json.Property(param.Name); var valueReader = property.Value.CreateReader(); var value = serializer.Deserialize(valueReader, param.Type); obj[param.ParameterName] = value; } return obj; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } }
namespace Teste_CRUD_CiaTecnica.Infra.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class CodeFirst : DbMigration { public override void Up() { CreateTable( "SYSTEM.Pessoa", c => new { PessoaId = c.Decimal(nullable: false, precision: 10, scale: 0, identity: true), Nome = c.String(nullable: false, maxLength: 100, unicode: false), Logradouro = c.String(nullable: false, maxLength: 100, unicode: false), Numero = c.Decimal(nullable: false, precision: 10, scale: 0), Complemento = c.String(maxLength: 50, unicode: false), Bairro = c.String(nullable: false, maxLength: 100, unicode: false), Cidade = c.String(nullable: false, maxLength: 100, unicode: false), CEP = c.String(nullable: false, maxLength: 8, unicode: false), UF = c.String(nullable: false, maxLength: 2, unicode: false), TipoPessoa = c.String(nullable: false, maxLength: 8, unicode: false), }) .PrimaryKey(t => t.PessoaId); CreateTable( "SYSTEM.PessoaFisica", c => new { PessoaId = c.Decimal(nullable: false, precision: 10, scale: 0), CPF = c.String(nullable: false, maxLength: 14, unicode: false), DataNascimento = c.DateTime(nullable: false), Sobrenome = c.String(nullable: false, maxLength: 15, unicode: false), }) .PrimaryKey(t => t.PessoaId) .ForeignKey("SYSTEM.Pessoa", t => t.PessoaId) .Index(t => t.PessoaId) .Index(t => t.CPF, unique: true, name: "UN_PessoaFisica_CPF"); CreateTable( "SYSTEM.PessoaJuridica", c => new { PessoaId = c.Decimal(nullable: false, precision: 10, scale: 0), CNPJ = c.String(nullable: false, maxLength: 18, unicode: false), NomeFantasia = c.String(nullable: false, maxLength: 100, unicode: false), }) .PrimaryKey(t => t.PessoaId) .ForeignKey("SYSTEM.Pessoa", t => t.PessoaId) .Index(t => t.PessoaId) .Index(t => t.CNPJ, unique: true, name: "UN_PessoaJuridica_CNPJ"); } public override void Down() { DropForeignKey("SYSTEM.PessoaJuridica", "PessoaId", "SYSTEM.Pessoa"); DropForeignKey("SYSTEM.PessoaFisica", "PessoaId", "SYSTEM.Pessoa"); DropIndex("SYSTEM.PessoaJuridica", "UN_PessoaJuridica_CNPJ"); DropIndex("SYSTEM.PessoaJuridica", new[] { "PessoaId" }); DropIndex("SYSTEM.PessoaFisica", "UN_PessoaFisica_CPF"); DropIndex("SYSTEM.PessoaFisica", new[] { "PessoaId" }); DropTable("SYSTEM.PessoaJuridica"); DropTable("SYSTEM.PessoaFisica"); DropTable("SYSTEM.Pessoa"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class FireProjectile : NetworkBehaviour { public GameObject projectilePrefab; GameObject instantiatedProjectile; public Transform projectileLaunchPoint; void Start () { } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.F) && (isLocalPlayer)){ CmdFire(); } } [Command] void CmdFire() { instantiatedProjectile = Instantiate(projectilePrefab, projectileLaunchPoint.position, transform.rotation); if (NetworkServer.active) { NetworkServer.Spawn(instantiatedProjectile); } } }
using gView.Framework.Geometry; using System.Windows.Forms; namespace gView.Plugins.Editor.Dialogs { public partial class FormChooseGeometry : Form { public FormChooseGeometry() : this(GeometryType.Point) { } public FormChooseGeometry(GeometryType type) { InitializeComponent(); this.GeometryType = type; } public GeometryType GeometryType { get { if (chkPoint.Checked) { return GeometryType.Point; } if (chkLine.Checked) { return GeometryType.Polyline; } if (chkPolygon.Checked) { return GeometryType.Polygon; } return GeometryType.Unknown; } set { switch (value) { case GeometryType.Point: case GeometryType.Multipoint: chkPoint.Checked = true; break; case GeometryType.Polyline: chkLine.Checked = true; break; case GeometryType.Polygon: chkPolygon.Checked = true; break; } } } } }
namespace Uintra.Features.Navigation.Configuration { public class NavigationItemTypeSettings { public string Alias { get; set; } public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using TinhLuong.Models; using TinhLuongBLL; using TinhLuongINFO; namespace TinhLuong.Controllers { public class ChamCongController : BaseController { // GET: ChamCong SaveLog sv = new SaveLog(); string nhansuid = "0"; int thang = 1; int nam = 2018; [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public ActionResult Index() { if (Session[SessionCommon.DonViID].ToString() == "VTT") drpDonViCha(); else drpDonViCha(Session[SessionCommon.DonViID].ToString()); drpNam(); drpThang(); return View(); } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public ActionResult IndexDetail(int thang, int nam, string DonViID) { //sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Bang luong don vi->thang-" + thang + "-nam" + nam); drpNam(nam.ToString()); drpThang(thang.ToString()); if (Session[SessionCommon.DonViID].ToString() != "VTT") { drpDonViCha(Session[SessionCommon.DonViID].ToString()); var chamcong = new ChamCongBLL().GetChamCongDonVi(thang.ToString(), nam.ToString(), Session[SessionCommon.DonViID].ToString(), "", Session[SessionCommon.Username].ToString()); return View(chamcong); } else { drpDonViCha(DonViID.Replace("_", "-")); var chamcong = new ChamCongBLL().GetChamCongDonVi(thang.ToString(), nam.ToString(), DonViID.Replace("_", "-"), "", Session[SessionCommon.Username].ToString()); return View(chamcong); } } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public ActionResult ChiTietChamCong(string NhanSuID, int Thang, int Nam) { nhansuid = NhanSuID; thang = Thang; nam = Nam; // sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Bang luong don vi->Detail->NhanSuID-" + NhanSuID + "-thang-" + Thang + "-nam-" + Nam); //var ChamCong = new ChamCongBLL().GetChamCongDonViByNhanSu(NhanSuID, Thang.ToString(), Nam.ToString(), 0); var ChamCong = new ChamCongBLL().GetInfoByNhanSuID(NhanSuID, Thang, Nam); LoadLoaiNgayChamCong(""); return View(ChamCong); } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public ActionResult ChiTietTrucDem(string NhanSuID, int Thang, int Nam) { nhansuid = NhanSuID; thang = Thang; nam = Nam; // sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Bang luong don vi->Detail->NhanSuID-" + NhanSuID + "-thang-" + Thang + "-nam-" + Nam); //var ChamCong = new ChamCongBLL().GetChamCongDonViByNhanSu(NhanSuID, Thang.ToString(), Nam.ToString(), 0); var ChamCong = new ChamCongBLL().GetInfoByNhanSuID(NhanSuID, Thang, Nam); LoadLoaiNgayChamCong(""); return View(ChamCong); } public void drpThang(string selected = null) { List<SelectListItem> listItems = new List<SelectListItem>(); listItems.Add(new SelectListItem { Text = "1", Value = "1" }); listItems.Add(new SelectListItem { Text = "2", Value = "2", }); listItems.Add(new SelectListItem { Text = "3", Value = "3" }); listItems.Add(new SelectListItem { Text = "4", Value = "4" }); listItems.Add(new SelectListItem { Text = "5", Value = "5" }); listItems.Add(new SelectListItem { Text = "6", Value = "6" }); listItems.Add(new SelectListItem { Text = "7", Value = "7" }); listItems.Add(new SelectListItem { Text = "8", Value = "8" }); listItems.Add(new SelectListItem { Text = "9", Value = "9" }); listItems.Add(new SelectListItem { Text = "10", Value = "10" }); listItems.Add(new SelectListItem { Text = "11", Value = "11" }); listItems.Add(new SelectListItem { Text = "12", Value = "12" }); ViewBag.drpThang = new SelectList(listItems, "Value", "Text", selected); } public void drpNam(string selected = null) { List<SelectListItem> listItems = new List<SelectListItem>(); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year - 2).ToString(), Value = (DateTime.Now.Year - 2).ToString() }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year - 1).ToString(), Value = (DateTime.Now.Year - 1).ToString(), }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year).ToString(), Value = (DateTime.Now.Year).ToString() }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year + 1).ToString(), Value = (DateTime.Now.Year + 1).ToString() }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year + 2).ToString(), Value = (DateTime.Now.Year + 2).ToString() }); ViewBag.drpNam = new SelectList(listItems, "Value", "Text", selected); } public void drpDonViCha(string selected = null) { var dmtram = new BaoCaoChungBLL().Get_ListTenDonVi(Session[SessionCommon.DonViID].ToString()); List<DM_DonVi> listItems = new List<DM_DonVi>(); if (selected != null) selected = selected.Replace("-", "_"); foreach (var item in dmtram) { if (item.DonViID != "TNN-NCM" && item.DonViID != "TNN-TKD") listItems.Add(new DM_DonVi { TenDonVi = item.TenDonVi, DonViID = item.DonViID.Replace("-", "_"), }); } ViewBag.DonViID = new SelectList(listItems, "DonViID", "TenDonVi", selected); } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public void LoadLoaiNgayChamCong(string selected = null) { var rs = new ChamCongBLL().SelectByMaChamCong(""); ViewBag.MaChamCong = new SelectList(rs, "MaChamCong", "TenChamCong", selected); } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public bool UpdateChamCong(int NhanVienID, string NgayCong, string MaChamCong, string Note, int TrucDem, string thang) { int Thang, Nam, Ngay; Nam = int.Parse(NgayCong.Substring(0, 4)); Thang = int.Parse(NgayCong.Substring(5, 2)); Ngay = int.Parse(NgayCong.Substring(8, 2)); if (int.Parse(thang) != Thang) return false; else return new ChamCongBLL().UpdateChamCongByNhanVien(NhanVienID, Nam, Thang, Ngay, MaChamCong, Note, TrucDem, Session[SessionCommon.Username].ToString()); } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public void ChotChamCong(string thang, string nam) { string str = ""; if (new ImportExcelBLL().GetChotSo(int.Parse(thang), int.Parse(nam), Session[SessionCommon.DonViID].ToString(), "BangLuong") == false) { setAlert("Dữ liệu đã chốt, không tiếp tục cập nhật được!", "error"); } else { str = new ChamCongBLL().ChotChamCong(thang, nam); var CapNhatLuongTrucDem = new ChamCongBLL().UpdateLuongTrucDem(thang, nam, Session[SessionCommon.Username].ToString()); setAlert(str, "success"); } } public JsonResult GetEvents(string NhanVienID, int thang, int nam, int TrucDem) { string Thang = thang.ToString(); if (Thang.Length < 2) Thang = "0" + Thang; List<Event> events = new List<Event>(); DataTable dt = new ChamCongBLL().GetChamCongDonViByNhanSu(NhanVienID, Thang, nam.ToString(), TrucDem); for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["MaChamCong"].ToString() != "") { Event _Event = new Event(); if (dt.Rows[i]["MaChamCong"].ToString() == "1/2X") { _Event.color = "blue"; } else if (dt.Rows[i]["MaChamCong"].ToString() == "H") { _Event.color = "green"; } else if (dt.Rows[i]["MaChamCong"].ToString() == "BH") { _Event.color = "yellow"; } else if (dt.Rows[i]["MaChamCong"].ToString() == "NL" || dt.Rows[i]["MaChamCong"].ToString() == "NB" || dt.Rows[i]["MaChamCong"].ToString() == "P") { _Event.color = "green"; } else if (dt.Rows[i]["MaChamCong"].ToString() == "N") { _Event.color = "black"; } else if (dt.Rows[i]["MaChamCong"].ToString() == "Ô") { _Event.color = "red"; } string ngay = dt.Rows[i]["Ngay"].ToString(); if (ngay.Length < 2) ngay = "0" + ngay; _Event.id = i; _Event.title = dt.Rows[i]["TenChamCong"].ToString(); _Event.someKey = i; _Event.note = dt.Rows[i]["GhiChu"].ToString(); _Event.start = nam.ToString() + "-" + Thang + "-" + ngay + "T07:00:00"; _Event.end = nam.ToString() + "-" + Thang + "-" + ngay + "T17:00:00"; _Event.allDay = true; _Event.MaChamCong = dt.Rows[i]["MaChamCong"].ToString(); events.Add(_Event); } } var rows = events.ToArray(); return Json(rows, JsonRequestBehavior.AllowGet); } public class Event { public int id; public string title; public int someKey; public string start; public string end; public string textColor; public string color; public string className; public bool allDay; public string note; public string MaChamCong; } [CheckCredential(RoleID = "CHAM_CONG_DONVI")] public ActionResult BaoCaoChamCong(string thang, string nam, int trucdem, string dv, string tram) { Session.Add(SessionCommon.Thang, thang); Session.Add(SessionCommon.nam, nam); Session.Add("TrucDem", trucdem); string content = ""; if (dv == "") Session.Add("DonVi_BaoCao", Session[SessionCommon.DonViID].ToString()); else Session.Add("DonVi_BaoCao", dv.Replace("_", "-")); content = "~/Reports/BaoCaoChung/ChamCongDonVi.aspx"; return Redirect(content); } } }
using System; using System.Collections; namespace Strings { /* * Given an arbitrary string, write code that can figure out if * a string has only unique characters. * * What if no additional space can be used? */ public class DoesTheStringHaveAllUniqueCharacters { /** * @ CheckExhaustively(string => bool) * * Easiest way to do this imo is to do a brute force search * * (+) No additional space * (-) O(n^2) worst-case */ public bool CheckExhaustively(string input) { int length = input.Length; for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i != j && input[i] == input[j]) { return false; } } } return true; } /** * @ CheckUsingHashTable(string => bool) * * Could simply use a HashTable to lookup already seen characters in the string. * * (+) Efficient, hashtables have a constant lookup time * (-) SPACE complexity of O(n) */ public bool CheckUsingHashTable(string input) { var length = input.Length; var lookupTable = new Hashtable(); for (int i = 0; i < length; i++) { if (!lookupTable.ContainsKey(input[i])) { lookupTable.Add(input[i], 0); } else { return false; } } return true; } /** * @ CheckUsingBitVector(string => bool) * * Uses a bit vector which requires 8x|16x less space than hash table. * * (+) More space efficient compared to Hashtable * (-) Still requires extra space */ public bool CheckUsingBitVector(string input) { var bitArray = new BitArray(char.MaxValue); for (int i = 0; i < input.Length; i++) { if (bitArray[input[i]]) { return false; } bitArray[input[i]] = true; } return true; } /** * @ CheckUsingSortedStringAdjacencySearch(string => bool) * * This is O(n) with no extra space requirment. Sort the string and look for * adjacent characters that are the same. *"throwing" -> "hrowingt" * (+) Very fast * (-) Assumes sorting algorithm has constant SPACE complexity */ public bool CheckingUsingSortedAdjacencySearch(string input) { var sorted = input.ToCharArray(); Array.Sort(sorted); for (int i = 0; i < input.Length - 1; i++) { if (sorted[i] == sorted[i + 1]) return false; } return true; } } }
using System; using System.Collections.Generic; using System.Linq; namespace NetEscapades.AspNetCore.SecurityHeaders.Headers; /// <summary> /// Used to build a Reporting-Endpoints header. /// </summary> public class ReportingEndpointsHeaderBuilder { private const string Separator = ", "; private const string DefaultName = "default"; private readonly List<KeyValuePair<string, string>> _endpoints = new(); /// <summary> /// Adds a reporting endpoint with the name <c>default</c> and url <paramref name="url"/>. /// The name of the endpoint is used to identify the endpoint in other security headers, /// such as the <c>Content-Security-Policy</c> <c>report-to</c> directive. The <c>default</c> /// endpoint must be defined to receive some reports such as deprecation and intervention reports. /// </summary> /// <param name="url">The url for the endpoint. Must be a valid, absolute, path</param> /// <returns>The <see cref="ReportingEndpointsHeaderBuilder"/> for method chaining</returns> public ReportingEndpointsHeaderBuilder AddDefaultEndpoint(string url) => AddEndpoint(DefaultName, url); /// <summary> /// Adds a reporting endpoint with the name <c>default</c> and url <paramref name="url"/>. /// The name of the endpoint is used to identify the endpoint in other security headers, /// such as the <c>Content-Security-Policy</c> <c>report-to</c> directive. The <c>default</c> /// endpoint must be defined to receive some reports such as deprecation and intervention reports. /// </summary> /// <param name="url">The url for the endpoint. Must be a valid, absolute, path</param> /// <returns>The <see cref="ReportingEndpointsHeaderBuilder"/> for method chaining</returns> public ReportingEndpointsHeaderBuilder AddDefaultEndpoint(Uri url) => AddEndpoint(DefaultName, url); /// <summary> /// Adds a reporting endpoint with the defined <paramref name="name"/> and <paramref name="url"/> /// </summary> /// <param name="name">The name of the endpoint. This value is used to identify the endpoint /// in other security headers, such as the <c>Content-Security-Policy</c> <c>report-to</c> directive</param> /// <param name="url">The url for the endpoint. Must be a valid, absolute, path</param> /// <returns>The <see cref="ReportingEndpointsHeaderBuilder"/> for method chaining</returns> public ReportingEndpointsHeaderBuilder AddEndpoint(string name, string url) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(nameof(url)); } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || !IsValid(uri)) { throw new ArgumentException($"The provided url {url} was not a valid absolute URL", nameof(url)); } if (string.Equals(uri.PathAndQuery, "/", StringComparison.Ordinal) && !url.EndsWith("/", StringComparison.Ordinal)) { // endpoints must have a path that starts with / url += "/"; } AddToList(name, url); return this; } /// <summary> /// Adds a reporting endpoint with the defined <paramref name="name"/> and <paramref name="url"/> /// </summary> /// <param name="name">The name of the endpoint. This value is used to identify the endpoint /// in other security headers, such as the <c>Content-Security-Policy</c> <c>report-to</c> directive</param> /// <param name="url">The url for the endpoint. Must be a valid, absolute, path</param> /// <returns>The <see cref="ReportingEndpointsHeaderBuilder"/> for method chaining</returns> public ReportingEndpointsHeaderBuilder AddEndpoint(string name, Uri url) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (url is null) { throw new ArgumentNullException(nameof(url)); } if (!IsValid(url)) { throw new ArgumentException($"The provided url '{url}' was not a valid absolute URL", nameof(url)); } AddToList(name, url.ToString()); return this; } private void AddToList(string name, string uri) { foreach (var endpoint in _endpoints) { if (string.Equals(endpoint.Key, name, StringComparison.Ordinal)) { throw new InvalidOperationException($"Can't add endpoint '{name}' with url '{uri}', as endpoint is already defined as '{endpoint.Value}'"); } } _endpoints.Add(new KeyValuePair<string, string>(name, uri)); } /// <summary> /// Build the Reporting-Endpoints header value /// </summary> /// <returns>The <see cref="ReportingEndpointsHeader"/> value</returns> internal string Build() { return string.Join(Separator, _endpoints.Select(x => $"{x.Key}=\"{x.Value}\"")); } private static bool IsValid(Uri uri) => uri.IsAbsoluteUri && !string.IsNullOrEmpty(uri.Host) && !string.IsNullOrEmpty(uri.Scheme); }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Domains.Enums { /// <summary> /// 状态 /// </summary> [ClassProperty(Name = "状态")] public enum Status { /// <summary> /// 正常 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "正常")] [Field(Icon = "la la-check-circle-o")] Normal = 1, /// <summary> /// 冻结 /// </summary> [LabelCssClass(BadgeColorCalss.Metal)] [Display(Name = "冻结")] [Field(Icon = "la la-lock")] Freeze = 2, /// <summary> /// 软删除,不是真正的删除,只是在数据库标记 /// </summary> [LabelCssClass(BadgeColorCalss.Danger)] [Display(Name = "删除")] [Field(Icon = "fa fa-trash-o")] Deleted = 3 } }
using System; using UnityEngine; namespace StateMachines { public class PauseHandler: StateHandler { private GameObject pausePanel; private void Awake() { pausePanel = GameObject.Find("PausePanel"); pausePanel.SetActive(false); DontDestroyOnLoad(pausePanel); } // Update is called once per frame void Update() { Debug.Log(GameObject.Find("PausePanel")); if (Input.GetKeyDown(KeyCode.Escape)) { if (!pausePanel.activeInHierarchy) { ContinueGame(); } else { PauseGame(); } } } //Note to myself: if scripts still work while timescale is 0, disable and enable them here private void PauseGame() { Time.timeScale = 0; pausePanel.SetActive(true); } private void ContinueGame() { Time.timeScale = 1; pausePanel.SetActive(false); } public override void OnEnter() { //PauseGame(); } public override void OnExit() { //ContinueGame(); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Shaman.Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Reflection; #if false using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Tooling; using Microsoft.Dnx.Runtime.Common.CommandLine; #endif namespace Shaman.Roslyn.LinqRewrite { class Program { private static bool NoRewrite; private static bool ForProjBuild; private static bool WriteFiles; #if false private static IServiceProvider _hostServices; private static IApplicationEnvironment _environment; private static IRuntimeEnvironment _runtimeEnv; public Program(IServiceProvider hostServices, IApplicationEnvironment environment, IRuntimeEnvironment runtimeEnv) { _hostServices = hostServices; _environment = environment; _runtimeEnv = runtimeEnv; } #endif public static int Main(string[] args) { var p = new Program(); return p.MainInternal(args); } private int MainInternal(string[] args) { CompileExample("Example2.cs"); return 0; } private void CompileExample(string path) { var workspace = new AdhocWorkspace(); var proj = workspace.AddProject("LinqRewriteExample", "C#").WithMetadataReferences( new[] { MetadataReference.CreateFromFile(typeof(int).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).GetTypeInfo().Assembly.Location), } ).WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); proj = proj.AddDocument("FastLinqExtensions.cs", File.ReadAllText("../../../Shaman.FastLinq.Sources/FastLinqExtensions.cs")).Project; var doc = proj.AddDocument("source.cs", File.ReadAllText(Path.Combine("../../Samples/", path))); if (!workspace.TryApplyChanges(doc.Project.Solution)) throw new Exception(); proj = doc.Project; var comp = proj.GetCompilationAsync().Result; var hasErrs = false; foreach (var item in comp.GetDiagnostics()) { if (item.Severity == DiagnosticSeverity.Error) hasErrs = true; PrintDiagnostic(item); } if (hasErrs) return; var syntaxTree = doc.GetSyntaxTreeAsync().Result; var rewriter = new LinqRewriter(comp.GetSemanticModel(syntaxTree)); var rewritten = rewriter.Visit(syntaxTree.GetRoot()); proj = doc.WithSyntaxRoot(rewritten).Project; hasErrs = false; foreach (var item in proj.GetCompilationAsync().Result.GetDiagnostics()) { if (item.Severity == DiagnosticSeverity.Error) hasErrs = true; if (item.Severity == DiagnosticSeverity.Warning) continue; PrintDiagnostic(item); } if (hasErrs) return; Console.WriteLine(rewritten.ToString()); } private static void PrintDiagnostic(Diagnostic item) { if (item.Severity == DiagnosticSeverity.Hidden) return; if (item.Severity == DiagnosticSeverity.Error) Console.ForegroundColor = ConsoleColor.Red; if (item.Severity == DiagnosticSeverity.Warning) Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(item); Console.ResetColor(); } private static void CompileSolution(string path, string projectName) { var properties = new Dictionary<string, string>(); properties.Add("Configuration", "Release"); #if CORECLR throw new NotSupportedException("Compiling CSPROJ files is not supported on CORECLR"); #else var workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(properties); Solution solution = null; if (".csproj".Equals(Path.GetExtension(path), StringComparison.OrdinalIgnoreCase)) { CompileProject(workspace.OpenProjectAsync(path).Result); } else { solution = workspace.OpenSolutionAsync(path).Result; if (projectName != null) { CompileProject(solution.Projects.Single(x => x.Name == projectName)); } else { foreach (var project in solution.Projects) { CompileProject(project); } } } #endif } private static void CompileProject(Microsoft.CodeAnalysis.Project project) { project = project.WithParseOptions(((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols(project.ParseOptions.PreprocessorSymbolNames.Concat(new[] { "LINQREWRITE" }))); var compilation = project.GetCompilationAsync().Result; var hasErrs = false; foreach (var item in compilation.GetDiagnostics()) { PrintDiagnostic(item); if (item.Severity == DiagnosticSeverity.Error) hasErrs = true; } if (hasErrs) throw new ExitException(1); var updatedProject = project; if (!NoRewrite) { foreach (var doc in project.Documents) { Console.WriteLine(doc.FilePath); var syntaxTree = doc.GetSyntaxTreeAsync().Result; var rewriter = new LinqRewriter(compilation.GetSemanticModel(syntaxTree)); var rewritten = rewriter.Visit(syntaxTree.GetRoot()).NormalizeWhitespace(); if (WriteFiles) { var tostring = rewritten.ToFullString(); if (syntaxTree.ToString() != tostring) { File.WriteAllText(doc.FilePath, tostring, Encoding.UTF8); } } updatedProject = updatedProject.GetDocument(doc.Id).WithSyntaxRoot(rewritten).Project; } project = updatedProject; compilation = project.GetCompilationAsync().Result; hasErrs = false; foreach (var item in compilation.GetDiagnostics()) { PrintDiagnostic(item); if (item.Severity == DiagnosticSeverity.Error) { hasErrs = true; if (item.Location != Location.None) { Console.ForegroundColor = ConsoleColor.White; //var lines = item.Location.GetLineSpan(); var node = item.Location.SourceTree.GetRoot().FindNode(item.Location.SourceSpan); var k = node.AncestorsAndSelf().FirstOrDefault(x => x is MethodDeclarationSyntax); if (k != null) { Console.WriteLine(k.ToString()); } Console.ResetColor(); } } } } string outputPath = project.OutputFilePath.Replace("\\", "/"); var objpath = outputPath.Replace("/bin/", "/obj/"); if (ForProjBuild) outputPath = objpath; var ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003"); var xml = XDocument.Load(project.FilePath); var hasResources = xml .DescendantNodes() .OfType<XElement>() .Where(x => x.Name == ns + "EmbeddedResource" || x.Name == ns + "Resource") .Any(); if (hasResources) { foreach (var resource in Directory.GetFiles(Path.GetDirectoryName(objpath), "*.resources")) { File.Delete(resource); } var args = new object[] { project.FilePath, new Shaman.Runtime.ProcessUtils.RawCommandLineArgument("/p:Configuration=Release") }; try { ProcessUtils.RunPassThrough("msbuild", args); } catch (Exception ex) when (!(ex is ProcessException)) { ProcessUtils.RunPassThrough("xbuild", args); } } var resources = hasResources ? Directory.EnumerateFiles(Path.GetDirectoryName(objpath), "*.resources") .Select(x => { return new ResourceDescription(Path.GetFileName(x), () => File.OpenRead(x), true); }).ToList() : Enumerable.Empty<ResourceDescription>(); /* var resources = XDocument.Load(project.FilePath) .DescendantNodes() .OfType<XElement>().Where(x => x.Name == ns + "EmbeddedResource") .Select(x => x.Attribute(ns + "Include")) .Select(x => Path.Combine(Path.GetDirectoryName(project.FilePath), x.Value)) .Select(x => { var rd = new ResourceDescription(); }).ToList(); */ compilation.Emit(outputPath, manifestResources: resources); //compilation.Emit(@"C:\temp\roslynrewrite\" + project.AssemblyName + ".dll"); if (hasErrs) throw new ExitException(1); } } }
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using VictorBu.Tool.Web; namespace VictorBu.ToolTest { [TestClass] public class UriHelperTest { [TestMethod] public void DecodeQueryParameters() { DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>()); DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>()); DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml" , new Dictionary<string, string> { { "key", "bla/blub.xml" } }); DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2" , new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } }); DecodeQueryParametersTest("http://test/test.html?empty" , new Dictionary<string, string> { { "empty", "" } }); DecodeQueryParametersTest("http://test/test.html?empty=" , new Dictionary<string, string> { { "empty", "" } }); DecodeQueryParametersTest("http://test/test.html?key=1&" , new Dictionary<string, string> { { "key", "1" } }); DecodeQueryParametersTest("http://test/test.html?key=value?&b=c" , new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } }); DecodeQueryParametersTest("http://test/test.html?key=value=what" , new Dictionary<string, string> { { "key", "value=what" } }); DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22" , new Dictionary<string, string> { { "q", "energy+edge" }, { "rls", "com.microsoft:en-au" }, { "ie", "UTF-8" }, { "oe", "UTF-8" }, { "startIndex", "" }, { "startPage", "1%22" }, }); DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue" , new Dictionary<string, string> { { "key", "value,anotherValue" } }); } private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected) { Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters(); Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri); foreach (var key in expected.Keys) { Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri); Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri); } } } }
using EPI.HashTables; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.HashTables { [TestClass] public class CollatzUnitTest { [TestMethod] public void TestCollatzConjecture() { Collatz.DoesNumberConvergeToOne(11).Should().BeTrue(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace SolutionsAssembly { public class FactorialDigitSum: ISolutionsContract { public string ProblemName => "Factorial Digit Sum"; public string ProblemDescription => @"n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! "; public int ProblemNumber => 20; public string Solution() { return Dry.DryCode.StringDigitSum(ProblemSolution(100)).ToString(); } private string ProblemSolution(int starVal) { int finalVal = starVal; BigInteger moo = 100; for (int n = starVal; n > 1; n--) moo = BigInteger.Multiply(moo, (n - 1)); return moo.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { // Max velocity to keep track of float maxVelocity; // Use this for initialization void Start () { maxVelocity = 0.0f; } // Update is called once per frame void Update () { // Updating the new Max Velocity if (this.GetComponent<Rigidbody>().velocity.magnitude > maxVelocity) { maxVelocity = this.GetComponent<Rigidbody>().velocity.magnitude; } this.GetComponent<Rigidbody>().velocity = maxVelocity * this.GetComponent<Rigidbody>().velocity.normalized; } // Function that deals with the Collision void OnCollisionEnter(Collision col) { // When it Collides with the Border Wall if(col.gameObject.tag == "Border" || col.gameObject.tag == "Tank" || (this.gameObject.tag != "InvincibleRound" && col.gameObject.tag == "InnerWall")) { Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class GradeBookResult { public float MinValue { get; set; } public float MaxValue { get; set; } public float AvgValue { get; set; } public override string ToString() { return string.Format("Min: {0}\nMax:{1}\nAverage:{2}\n", MinValue, MaxValue, AvgValue); //base.ToString(); } } }
using MmsApi.Helpers; using MmsApi.Models; using MmsDb; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Web.Http; namespace MmsApi.Controllers { public class ImagesController : HomeController<ImageEntity> { public ImagesController(Repository<ImageEntity> repo) : base(repo) { } public IHttpActionResult Get() { try { var images = Repository.Get().ToList().Select(x => Factory.Create(x)).ToList(); return Ok(images); } catch (Exception) { return BadRequest(); } } public IHttpActionResult Get(int id) { try { ImageEntity image = Repository.Get(id); if (image != null) return Ok(image); return NotFound(); } catch (Exception) { return BadRequest(); } } public IHttpActionResult Post(ImageModel image) { if (image != null) { try { string addToImage = "../images/"; string location = string.Concat(addToImage, image.Location); image.Location = location; Repository.Insert(Parser.Create(image, Repository.HomeContext())); var loc = AppDomain.CurrentDomain.BaseDirectory; string name = image.Location.Substring(0,image.Location.Length - 4); name = name.Substring(10, name.Length-10); loc = loc.Substring(0, loc.Length - 8) + "\\MmsWebSite\\images\\" + name+".jpg"; Image newImage = Image.FromFile(loc); ImageHelper.SaveJpeg(image.Location, newImage, 1, image, name); ImageHelper.SaveJpeg(image.Location, newImage, 5, image, name); ImageHelper.SaveJpeg(image.Location, newImage, 10, image, name); ImageHelper.SaveJpeg(image.Location, newImage, 30, image, name); ImageHelper.SaveJpeg(image.Location, newImage, 50, image, name); ImageHelper.SaveJpeg(image.Location, newImage, 70, image, name); ImageHelper.SaveJpeg(image.Location, newImage, 90, image, name); return Ok(image); } catch (Exception ex) { return BadRequest(ex.Message); } } return NotFound(); } public IHttpActionResult Put(int id, ImageModel model) { if (model != null) { ImageModel imageToReturn = new ImageModel(); imageToReturn.Description = "Compressed image"; string loc = model.Location.Substring(0, 10)+"compressed/"; string name = model.Location.Substring(10, model.Location.Length-14); imageToReturn.Location = loc + name + "-" + model.Ratio + ".jpeg"; if (imageToReturn != null) { return Ok(imageToReturn); } return NotFound(); } return NotFound(); } public IHttpActionResult Delete(int id) { try { ImageEntity image = Repository.Get(id); if (image != null) { Repository.Delete(id); return Ok(); } return NotFound(); } catch (Exception) { return BadRequest(); } } } }
using System; using Microsoft.CQRS; namespace Microsoft.UnifiedPlatform.Service.Application.Commands { public class AuthenticateClientCommand : Command<TokenCommandResult> { public override string DisplayName => "Authenticate Client"; private readonly string _id; public override string Id => _id; public string ClusterName { get; set; } public string AppName { get; set; } public string AppSecret { get; set; } public AuthenticateClientCommand(string clusterName, string appName, string appSecret) { _id = Guid.NewGuid().ToString(); ClusterName = clusterName; AppName = appName; AppSecret = appSecret; } public override bool Validate(out string ValidationErrorMessage) { ValidationErrorMessage = null; if (string.IsNullOrWhiteSpace(ClusterName)) ValidationErrorMessage = "Cluster Name is missing"; if (string.IsNullOrWhiteSpace(AppName)) ValidationErrorMessage = "App Name is missing"; if (string.IsNullOrWhiteSpace(AppSecret)) ValidationErrorMessage = "App Secret is missing"; return string.IsNullOrWhiteSpace(ValidationErrorMessage); } } public class TokenCommandResult : CommandResult { public string Token { get; set; } public string Resource { get; set; } public long ExpiresOn { get; set; } public TokenCommandResult(string token, string resource, long expiresOn) : base(true) { Token = token; Resource = resource; ExpiresOn = expiresOn; } } }
using Library.DataProcessing.Contracts.DataServices; using Library.DataProcessing.Implementation.DataServices; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; namespace Library.DataProcessing.Implementation { public static class DataProcessingServiceCollectionExtensions { public static IServiceCollection AddDataProcessingServices(this IServiceCollection services) { services.AddScoped<IBookService, BookService>(); services.AddScoped(typeof(IGenericService<>), typeof(GenericService<>)); return services; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Aurora.Framework.Modules; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace Aurora.Framework.ClientInterfaces { public class EventData : IDataTransferable { public uint amount; public string category; public uint cover; public string creator; public string date; public uint dateUTC; public string description; public uint duration; public uint eventFlags; public uint eventID; public Vector3 globalPos; public Vector3 regionPos; public int maturity; public string name; public string simName; public EventData() { } public override OSDMap ToOSD() { OSDMap map = new OSDMap(); map["eventID"] = eventID; map["creator"] = creator; map["name"] = name; map["category"] = category; map["description"] = description; map["date"] = date; map["dateUTC"] = dateUTC; map["duration"] = duration; map["cover"] = cover; map["amount"] = amount; map["simName"] = simName; map["globalPos"] = globalPos; map["regionPos"] = regionPos; map["eventFlags"] = eventFlags; map["maturity"] = maturity; return map; } public override void FromOSD(OSDMap map) { eventID = map["eventID"]; creator = map["creator"]; name = map["name"]; category = map["category"]; description = map["description"]; date = map["date"]; dateUTC = map["dateUTC"]; duration = map["duration"]; cover = map["cover"]; amount = map["amount"]; simName = map["simName"]; globalPos = map["globalPos"]; regionPos = map["regionPos"]; eventFlags = map["eventFlags"]; maturity = map["maturity"]; } } }
using System; namespace AreaDotnet.Figures { public class Triangle : IFigure { protected const int RIGHT_PRECISION = 12; public double SideA { get; protected set; } public double SideB { get; protected set; } public double SideC { get; protected set; } /// <inheritdoc/> /// <see>https://en.wikipedia.org/wiki/Heron%27s_formula</see> public double Area { get { var p = (SideA + SideB + SideC) / 2; return Math.Sqrt(p * (p - SideA) * (p - SideB) * (p - SideC)); } } /// <value>True if triangle is right.</value> /// <see>https://en.wikipedia.org/wiki/Right_triangle</see> /// <see>https://en.wikipedia.org/wiki/Pythagorean_theorem</see> public bool IsRight { get { double hypotenuse = SideC; double leg1 = SideA; double leg2 = SideB; if (SideA > SideB && SideA > SideC) { hypotenuse = SideA; leg1 = SideB; leg2 = SideC; } else if (SideB > SideA && SideB > SideC) { hypotenuse = SideB; leg1 = SideA; leg2 = SideC; } return Math.Round(leg1 * leg1 + leg2 * leg2, RIGHT_PRECISION) == Math.Round(hypotenuse * hypotenuse, RIGHT_PRECISION); } } /// <summary><c>Triangle</c> class constructor.</summary> /// <param name="sideA">A double precision number.</param> /// <param name="sideB">A double precision number.</param> /// <param name="sideC">A double precision number.</param> public Triangle(double sideA, double sideB, double sideC) { SetSides(sideA, sideB, sideC); } /// <summary>Sets the sides of triangle.</summary> /// <param name="sideA">A double precision number.</param> /// <param name="sideB">A double precision number.</param> /// <param name="sideC">A double precision number.</param> /// <exception cref="System.ArgumentException">If one of the sides is invalid.</exception> /// <exception cref="AreaDotnet.Figures.NonExistentTriangleException"> /// If the triangle cannot exists with these sides.</exception> public Triangle SetSides(double sideA, double sideB, double sideC) { if (sideA < 0 || double.IsNaN(sideA) || double.IsInfinity(sideA)) { throw new ArgumentException("Side A must be a positive finite double"); } if (sideB < 0 || double.IsNaN(sideB) || double.IsInfinity(sideB)) { throw new ArgumentException("Side B must be a positive finite double"); } if (sideC < 0 || double.IsNaN(sideC) || double.IsInfinity(sideC)) { throw new ArgumentException("Side C must be a positive finite double"); } if (!((sideA <= sideB + sideC) && (sideB <= sideA + sideC) && (sideC <= sideA + sideB))) { throw new NonExistentTriangleException("A triangle with such sides cannot exist"); } SideA = sideA; SideB = sideB; SideC = sideC; return this; } } public class NonExistentTriangleException : ArgumentException { public NonExistentTriangleException() : base() { } public NonExistentTriangleException(string message) : base(message) { } public NonExistentTriangleException(string message, Exception innerException) : base(message, innerException) { } public NonExistentTriangleException(string message, string paramName) : base(message, paramName) { } public NonExistentTriangleException(string message, string paramName, Exception innerException) : base(message, paramName, innerException) { } } }
using System; using System.Collections; namespace Reverse_String { class Program { static void Main(string[] args) { var stringToReverse = Console.ReadLine(); var result = new Stack(); foreach (var letter in stringToReverse) { result.Push(letter); } while (result.Count > 0) { Console.Write(result.Pop()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Trains.Contracts.Repository; using Trains.Model; namespace Trains.Repositories { public class JourneyRepository:BaseRepository, IJourneyRepository { private static readonly List<Journey> AllJourneys = new List<Journey>() { new Journey { JourneyId = 1, FromCityId = 1, ToCityId = 2, DepartureTime = DateTime.Now.AddHours(1), ArrivalTime = DateTime.Now.AddHours(2), JourneyDate = DateTime.Now, Platform = "12", Price = 50 }, new Journey { JourneyId = 2, FromCityId = 2, ToCityId = 1, DepartureTime = DateTime.Now.AddHours(2), ArrivalTime = DateTime.Now.AddHours(3), JourneyDate = DateTime.Now, Platform = "6", Price = 100 }, new Journey { JourneyId = 3, FromCityId = 1, ToCityId = 2, DepartureTime = DateTime.Now.AddHours(4), ArrivalTime = DateTime.Now.AddHours(5), JourneyDate = DateTime.Now, Platform = "6", Price = 100 }, new Journey { JourneyId = 4, FromCityId = 1, ToCityId = 2, DepartureTime = DateTime.Now.AddHours(6), ArrivalTime = DateTime.Now.AddHours(7), JourneyDate = DateTime.Now, Platform = "6", Price = 100 } }; public async Task<Journey> GetJourneyDetails(int journeyId) { return await Task.FromResult(AllJourneys.FirstOrDefault(j => j.JourneyId == journeyId)); } public async Task<IEnumerable<Journey>> SearchJourney(int fromCity, int toCity, DateTime journeyDate, DateTime departureTime) { return await Task.FromResult(AllJourneys.Where(fr => fr.FromCityId == fromCity && fr.ToCityId == toCity)); } } }
using System.Drawing; using System.Threading.Tasks; using System.Windows.Forms; namespace Tic_Tac_Toe_WF { public partial class Checkboxes_Disabled : Form { public Checkboxes_Disabled() { InitializeComponent(); Blink(); } private async void Blink() { while (true) { await Task.Delay(100); textBox1.BackColor = textBox1.BackColor == Color.Red ? Color.White : Color.Red; textBox1.ForeColor = textBox1.ForeColor == Color.White ? Color.Green : Color.White; } } } }
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace CESI_Afficheur.BDD { public class MyDatabase { public MySqlConnection con; public bool OpenConnection() { try { string cs = @"Server=localhost;Database=accueildb;User Id=root;Password=;"; con = new MySqlConnection(cs); con.Open(); return true; } catch (MySqlException ex) { //When handling errors, you can your application's response based //on the error number. //The two most common error numbers when connecting are as follows: //0: Cannot connect to server. //1045: Invalid user name and/or password. switch (ex.Number) { case 0: //MessageBox.Show("Impossible de se connecter au server. Contactez l'administrateur", "Erreur", MessageBoxButton.OK, MessageBoxImage.Information); break; case 1045: MessageBox.Show("Le mot de passe ou le nom d'utilisateur de la base de données est incorrect, veuillez réessayer", "Erreur", MessageBoxButton.OK, MessageBoxImage.Information); break; } return false; } } public bool CloseConnection() { try { con.Close(); return true; } catch (MySqlException ex) { MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK, MessageBoxImage.Information); return false; } } public static MySqlConnection getCon() { string cs = @"Server=localhost;Database=accueildb;User Id=root;Password=;"; MySqlConnection connection = new MySqlConnection(cs); return connection; } } }
using System; using UnityEngine.Events; [Serializable] public class UnityStatChangedEvent : UnityEvent<OnStatChangedEventArgs> { }
using appglobal.models; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Text.RegularExpressions; namespace appglobal { /// <summary> /// Class utama untuk mengeset parameter project .netcore /// - Author : Kurniawan /// - Modified : 2018-09-03 /// </summary> public static class AppGlobal { internal static string BASE_URL = ""; internal static string LOG_DIR = @"./LOGS"; internal static string MYSQL_CS = "Server=127.0.0.1;Port=30000;Database=gls_model;Uid=root;Pwd=GL-System123"; internal static string OVERRIDE_CS = ""; internal static string OVERRIDE_TM = ""; /// <summary> /// Get primary connection string for .netcore project /// </summary> /// <param name="db_server"></param> /// <returns></returns> static internal string get_connection_string(string db_server = "MySQL") { string connection = ""; if (db_server == "MySQL") { string file_setting = OVERRIDE_CS; connection = file_setting == "" ? MYSQL_CS : file_setting; } return connection; } /// <summary> /// Get primary working directory for application path searching /// </summary> /// <returns></returns> public static string get_working_directory() { return BASE_URL; //Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } /// <summary> /// Used in defining which connection to be used in a db_context /// </summary> /// <returns></returns> public static dynamic get_db_option() { DbContextOptionsBuilder ob = new DbContextOptionsBuilder<gls_model>(); ob.UseMySql(get_connection_string()); return ob.Options; } /// <summary> /// Used in determining whether system is activated or not /// </summary> /// <returns></returns> public static bool get_system_active_status() { /*DataHandler dh = new DataHandler(); string check_connection = dh.ExecuteScalar("SELECT GETDATE() AS CurrentDateTime", null, "unlogged"); string NPSN = dh.ExecuteScalar("SELECT NPSN FROM MstSekolah WHERE NPSN<>'00000000'", null, "unlogged"); bool activated = false; try { IDGenerator ig = new IDGenerator(); string get_serial_number = ig.MD5SerialNumber(); string get_serial_number_from_file = ig.GetSerialNumberFromFile(); activated = get_serial_number == get_serial_number_from_file && NPSN.Length == 8; } catch (Exception e) { activated = true; } */ return true; } /// <summary> /// Used in getting multiple trademark options /// </summary> /// <returns></returns> public static string get_system_trademark() { string trademark = OVERRIDE_TM; trademark = trademark == "" ? "gls" : trademark; return trademark; } /// <summary> /// Used in getting nama instansi from database /// </summary> /// <returns></returns> public static string get_nama_instansi() { return "[NAMA INSTANSI]"; } /// <summary> /// Used in getting tahun aktif from database /// </summary> /// <returns></returns> public static string get_tahun_aktif() { return "Tahun Akademik: " + "[TAHUN AKTIF]"; } /// <summary> /// Used in getting semester aktif from database /// </summary> /// <returns></returns> public static string get_semester_aktif() { return "Semester Aktif: " + "[SEMESTER AKTIF]"; } /// <summary> /// Get session timout value from db /// </summary> /// <returns></returns> public static int get_session_timeout() { gls_model _context = new gls_model(AppGlobal.get_db_option()); //simplifying context initializer by override int session_timeout = 0; try { session_timeout = Convert.ToInt32(_context.m_parameter.Where(e => e.parameter_key == "Session Timeout").Single().parameter_value); } catch (Exception e) { Console.WriteLine(e); } return session_timeout; } /// <summary> /// Standardize console logging /// </summary> public static void console_log(string name, string content) { Console.WriteLine("======================================================"); Console.Write(name + " >> "); Console.WriteLine(content); Console.WriteLine("======================================================"); } /// <summary> /// Get url componen from path /// </summary> /// <returns></returns> public static string get_url_from_path(string path, string part = "feature") { int part_index = part == "feature" ? 2 : 1; string result = ""; string base_path = "/scope"; string split_url = path.Substring(base_path.Length); string[] urls = split_url.Split("/"); result = urls[part_index]; return result; } /// <summary> /// Get id from current logged in user /// </summary> /// <returns></returns> public static int get_user_login_id() { return Convert.ToInt32(System.Web.HttpContext.Current.User.FindFirst("user_id").Value); } /// <summary> /// Get id from current logged in user /// </summary> /// <returns></returns> public static int get_user_group_login_id() { gls_model _context = new gls_model(AppGlobal.get_db_option()); //simplifying context initializer by override return _context.m_user.Include(e => e.m_user_group).Where(e => e.m_user_id == get_user_login_id()).Single().m_user_group_id; } /// <summary> /// Get user validity with defined user_id & feature_id derived from url /// </summary> /// <returns></returns> public static bool get_user_validity() { gls_model _context = new gls_model(AppGlobal.get_db_option()); //simplifying context initializer by override bool valid = false; string path = System.Web.HttpContext.Current.Request.Path; string url_feature = get_url_from_path(path, "feature"); string url_feature_group = get_url_from_path(path, "feature_group"); int feature_id = 0; try { feature_id = _context.m_feature .Include(e => e.m_feature_group) .Where(e => e.feature_url == url_feature && e.m_feature_group.feature_group_name.ToLower().Replace(" ", "_") == url_feature_group) .Single().m_feature_id; } catch (Exception e) { console_log("error feature_id", e.ToString()); } int feature_count = _context.feature_map .Where(e => e.m_feature_id == feature_id && e.m_user_group_id == get_user_group_login_id()).Count(); valid = feature_count == 1 ? true : false; return valid; } /// <summary> /// Encode string before saving to the database /// Increasing consistency /// </summary> /// <param name="input">string to be encoded</param> /// <param name="mode">determining wether encode all or only non-ASCII character</param> /// <returns></returns> public static string string_encode(string input, string mode = "lite") { string pattern = mode == "lite" ? @"[^\u0020-\u007E]" : @"[^A-Za-z\\d]"; return Regex.Replace(input, pattern, delegate (Match m) { Char c = Convert.ToChar(m.Value); return string.Format("&#{0};", (Int32)c); }); } } }
using UnityEngine; public class TaskRegulateTemperature : TaskBase<EntityWorker> { [SerializeField] private UnlockableStat temperatureStat = null; [SerializeField] private float overheatRate = 1f; public override bool continueExecuting() { return this.temperatureStat != null; } public override void preform() { float cellTemp = this.owner.world.storage.getTemperature(this.owner.position); if(cellTemp > 0) { this.temperatureStat.increase(cellTemp * this.overheatRate * Time.deltaTime); } else { // Temp is 0 or lower (Cool) this.temperatureStat.decrease(Time.deltaTime); } } public override bool shouldExecute() { return this.temperatureStat != null; } public override bool allowLowerPriority() { return true; } }
using UnityEngine; using System.Collections; public class DialogController : MonoBehaviour { public static DialogController instance; Dialog activeDialog; void Awake() { instance = this; } public void ShowDialog(Dialog dialog) { activeDialog = dialog; activeDialog.ShowInParent (PausedOverlay.instance.transform); PausedOverlay.instance.PausedOverlayTouched += OnPausedOverlayTouched; TimeController.instance.SetTimeState (TimeController.TimeState.PAUSE_FOR_DIALOG); } public void HideDialog(Dialog dialog) { if (dialog != activeDialog) { return; } activeDialog.OnHidden (); activeDialog = null; PausedOverlay.instance.PausedOverlayTouched -= OnPausedOverlayTouched; TimeController.instance.SetTimeState (TimeController.TimeState.PLAYING); } void OnPausedOverlayTouched() { HideDialog (activeDialog); } public bool IsDialogShowing() { return (activeDialog != null); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Model.Models; using Data.Models; using Service; using Data.Infrastructure; using Presentation.ViewModels; using Presentation; using Core.Common; using System.Data.Entity.Validation; using System.Data.Entity.Infrastructure; using Model.ViewModel; using System.Xml.Linq; namespace Web { [Authorize] public class LogActivity { public static void LogActivityDetail(int? DocTypeId, int DocId, int? DocLineId, int ActivityType, string UserRemark, string User, string DocName, XElement Mods) { ActivityLog log = new ActivityLog() { DocTypeId = DocTypeId, DocLineId = DocLineId, ActivityType = ActivityType, CreatedBy = User, Modifications = Mods != null ? Mods.ToString() : "", CreatedDate = DateTime.Now, DocId = DocId, }; if (ActivityType == (int)ActivityTypeContants.Added) { log.Narration = "DocNo: " + DocName; } else if (ActivityType == (int)ActivityTypeContants.Modified) { log.Narration = "DocNo: " + DocName; log.UserRemark = UserRemark; } else if (ActivityType == (int)ActivityTypeContants.Submitted) { log.UserRemark = UserRemark; log.Narration = "DocNo: " + DocName; } else if (ActivityType == (int)ActivityTypeContants.Approved) { log.Narration = "DocNo: " + DocName; log.UserRemark = UserRemark; } else if (ActivityType == (int)ActivityTypeContants.ModificationSumbitted) { log.Narration = "DocNo: " + DocName; log.UserRemark = UserRemark; } else if (ActivityType == (int)ActivityTypeContants.Deleted) { log.Narration = "DocNo: " + DocName; log.UserRemark = UserRemark; } log.ObjectState = Model.ObjectState.Added; using (ApplicationDbContext context = new ApplicationDbContext()) { context.ActivityLog.Add(log); context.SaveChanges(); } } } public class ActivityLogController : System.Web.Mvc.Controller { private ApplicationDbContext db = new ApplicationDbContext(); IActivityLogService _ActivityLogService; IUnitOfWork _unitOfWork; IExceptionHandlingService _exception; public ActivityLogController(IActivityLogService ActivityLogService, IUnitOfWork unitOfWork, IExceptionHandlingService exec) { _ActivityLogService = ActivityLogService; _unitOfWork = unitOfWork; _exception = exec; } public ActionResult LogEditReason() { return PartialView("~/Views/Shared/_Reason.cshtml"); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult PostLogReason(ActivityLogForEditViewModel vm) { if(ModelState.IsValid) { return Json(new { success = true,UserRemark=vm.UserRemark }); } return PartialView("~/Views/Shared/_Reason.cshtml", vm); } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace SecurityPlusCore { /* [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StringData { public short Length; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPWStr, SizeConst = 128)] public byte[] Buffer; public override string ToString() { unsafe { fixed (byte* data = this.Buffer) { return Encoding.Unicode.GetString(data, this.Length); } } } } */ [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StringData { public short Length; public string Buffer; public override string ToString() { return this.Buffer; } } /* [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct StringData { public short Length; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Buffer; public override string ToString() { return this.Buffer.ToString(); } }*/ }
using EddiDataDefinitions; using Newtonsoft.Json; using System; using System.Collections.ObjectModel; namespace EddiConfigService.Configurations { /// <summary>Storage for configuration of navigation details</summary> [JsonObject(MemberSerialization.OptOut), RelativePath(@"\navigationmonitor.json")] public class NavigationMonitorConfiguration : Config { public DateTime updatedat { get; set; } // Search parameters public int? maxSearchDistanceFromStarLs { get; set; } = 10000; public bool prioritizeOrbitalStations { get; set; } = true; // Search data public string searchQuery { get; set; } public string searchQuerySystemArg { get; set; } public string searchQueryStationArg { get; set; } public string carrierDestinationArg { get; set; } // Ship touchdown data public decimal? tdLat { get; set; } public decimal? tdLong { get; set; } public string tdPOI { get; set; } // Saved bookmarks public ObservableCollection<NavBookmark> bookmarks { get; set; } = new ObservableCollection<NavBookmark>(); // Current in-game route public NavWaypointCollection navRouteList { get; set; } = new NavWaypointCollection(); // Plotted routes public NavWaypointCollection plottedRouteList { get; set; } = new NavWaypointCollection(); public NavWaypointCollection carrierPlottedRoute { get; set; } = new NavWaypointCollection(); } }
using System.Collections.Generic; using System.IO; using System.Linq; using Cradiator.Config; using Cradiator.Extensions; using log4net; namespace Cradiator.Model { public class BuildBusterImageDecorator : IBuildBuster { static readonly ILog _log = LogManager.GetLogger(nameof(BuildBusterImageDecorator)); readonly IBuildBuster _buildBuster; readonly string _imageFolder; readonly List<char> InvalidCharacterList = Path.GetInvalidFileNameChars().ToList(); public BuildBusterImageDecorator([InjectBuildBuster] IBuildBuster buildBuster, IAppLocation appLocation) { _buildBuster = buildBuster; _imageFolder = Path.Combine(appLocation.DirectoryName, "images"); } public string FindBreaker(string currentMessage) { var username = _buildBuster.FindBreaker(currentMessage); if (username.ContainsInvalidChars()) { foreach (var c in username.ToCharArray().Where(InvalidCharacterList.Contains)) { username = username.Replace(c.ToString(), ""); } } var imagePath = $@"{_imageFolder}\{username}.jpg".Trim(); _log.DebugFormat("Breaker image='{0}'", imagePath); return imagePath; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LCode { class LCode36 { HashSet<char> char_sets = new HashSet<char>(); public bool IsValidSudoku(char[][] board) { for (int i = 0; i < 9; i++) { if (!CheckRow(board, i)) { return false; } } for (int j = 0; j < 9; j++) { if (!CheckColumn(board, j)) { return false; } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (!CheckBlock(board, i, j)) { return false; } } } return true; } bool CheckRow(char[][] board, int rowIdx) { char_sets.Clear(); for (int i = 0; i < board.Length; i++) { char thisChar = board[rowIdx][i]; if (thisChar != '.') { if (char_sets.Contains(thisChar)) { Console.WriteLine(rowIdx + " Row Duplication!!"); return false; } else { char_sets.Add(thisChar); } } } return true; } bool CheckColumn(char[][] board, int colIdx) { char_sets.Clear(); for (int i = 0; i < board.Length; i++) { char thisChar = board[i][colIdx]; if (thisChar != '.') { if (char_sets.Contains(thisChar)) { Console.WriteLine(colIdx + " Col Duplication!!"); return false; } else { char_sets.Add(thisChar); } } } return true; } bool CheckBlock(char[][] board, int block_i, int block_j) { char_sets.Clear(); int start_i = block_i * 3; int start_j = block_j * 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int idx_i = start_i + i; int idx_j = start_j + j; char thisChar = board[idx_i][idx_j]; if (thisChar != '.') { if (char_sets.Contains(thisChar)) { Console.WriteLine(string.Format("({0},{1}) Duplication", block_i, block_j)); return false; } else { char_sets.Add(thisChar); } } } } return true; } } }
using DSSLib; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DSSCriterias.Logic { public class MtxStatFactory : MtxCellFactory<Alternative, Case, double> { public override string ToString() { return $"Фабрика статистической игры"; } public override MtxCell<Alternative, Case, double> NewCell() { return new AltCase(Coords.Of(0, 0), NewRow(0), NewCol(0), NewValue); } public override MtxCell<Alternative, Case, double> NewCell(Coords coords, Alternative r, Case c, double v) { return new AltCase(coords, r, c, v); } public override Case NewCol(int index) { return new Case($"С{index}"); } public override Alternative NewRow(int index) { return new Alternative($"А{index}"); } public override double NewValue => 0; } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using NUnit.Framework; using Spring.Messaging.Amqp.Core; namespace Spring.Messaging.Amqp.Tests.Core { /// <summary> /// Address tests. /// </summary> /// <remarks></remarks> [TestFixture] public class AddressTests { /// <summary> /// Toes the string. /// </summary> /// <remarks></remarks> [Test] public void ToString() { var address = new Address(ExchangeTypes.Direct, "my-exchange", "routing-key"); var replyToUri = "direct://my-exchange/routing-key"; Assert.AreEqual(replyToUri, address.ToString()); } /// <summary> /// Parses this instance. /// </summary> /// <remarks></remarks> [Test] public void Parse() { var replyToUri = "direct://my-exchange/routing-key"; var address = new Address(replyToUri); Assert.AreEqual(address.ExchangeType, ExchangeTypes.Direct); Assert.AreEqual(address.ExchangeName, "my-exchange"); Assert.AreEqual(address.RoutingKey, "routing-key"); } /// <summary> /// Unstructureds the with routing key only. /// </summary> /// <remarks></remarks> [Test] public void UnstructuredWithRoutingKeyOnly() { var address = new Address("my-routing-key"); Assert.AreEqual("my-routing-key", address.RoutingKey); Assert.AreEqual("direct:///my-routing-key", address.ToString()); } /// <summary> /// Withouts the routing key. /// </summary> /// <remarks></remarks> [Test] public void WithoutRoutingKey() { var address = new Address("fanout://my-exchange"); Assert.AreEqual(ExchangeTypes.Fanout, address.ExchangeType); Assert.AreEqual("my-exchange", address.ExchangeName); Assert.AreEqual(string.Empty, address.RoutingKey); Assert.AreEqual("fanout://my-exchange/", address.ToString()); } /// <summary> /// Withes the default exchange and routing key. /// </summary> /// <remarks></remarks> [Test] public void WithDefaultExchangeAndRoutingKey() { var address = new Address("direct:///routing-key"); Assert.AreEqual(ExchangeTypes.Direct, address.ExchangeType); Assert.AreEqual(string.Empty, address.ExchangeName); Assert.AreEqual("routing-key", address.RoutingKey); Assert.AreEqual("direct:///routing-key", address.ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassicCraft { public class Player : Entity { public class HitChances { public HitChances(Dictionary<ResultType, double> whiteHitChancesMH, Dictionary<ResultType, double> yellowHitChances, Dictionary<ResultType, double> whiteHitChancesOH = null) { WhiteHitChancesMH = whiteHitChancesMH; WhiteHitChancesOH = whiteHitChancesOH; YellowHitChances = yellowHitChances; } public Dictionary<ResultType, double> WhiteHitChancesMH { get; set; } public Dictionary<ResultType, double> WhiteHitChancesOH { get; set; } public Dictionary<ResultType, double> YellowHitChances { get; set; } } public enum Races { Human, Dwarf, NightElf, Gnome, Orc, Undead, Tauren, Troll } public static Races ToRace(string s) { switch (s) { case "Human": return Races.Human; case "Dwarf": return Races.Dwarf; case "NightElf": return Races.NightElf; case "Gnome": return Races.Gnome; case "Orc": return Races.Orc; case "Undead": return Races.Undead; case "Tauren": return Races.Tauren; case "Troll": return Races.Troll; default: throw new Exception("Race not found"); } } public static string FromRace(Races r) { switch (r) { case Races.Human: return "Human"; case Races.Dwarf: return "Dwarf"; case Races.NightElf: return "NightElf"; case Races.Gnome: return "Gnome"; case Races.Orc: return "Orc"; case Races.Undead: return "Undead"; case Races.Tauren: return "Tauren"; case Races.Troll: return "Troll"; default: throw new Exception("Race not found"); } } public enum Classes { Priest, Rogue, Warrior, Mage, Druid, Hunter, Warlock, Shaman, Paladin } public static Classes ToClass(string s) { switch(s) { case "Priest": return Classes.Priest; case "Rogue": return Classes.Rogue; case "Warrior": return Classes.Warrior; case "Mage": return Classes.Mage; case "Druid": return Classes.Druid; case "Hunter": return Classes.Hunter; case "Warlock": return Classes.Warlock; case "Shaman": return Classes.Shaman; case "Paladin": return Classes.Paladin; default: throw new Exception("Class not found"); } } public static string FromClass(Classes c) { switch(c) { case Classes.Priest: return "Priest"; case Classes.Rogue: return "Rogue"; case Classes.Warrior: return "Warrior"; case Classes.Mage: return "Mage"; case Classes.Druid: return "Druid"; case Classes.Hunter: return "Hunter"; case Classes.Warlock: return "Warlock"; case Classes.Shaman: return "Shaman"; case Classes.Paladin: return "Paladin"; default: throw new Exception("Class not found"); } } public enum Slot { Head, Neck, Shoulders, Back, Chest, Wrist, Hands, Waist, Legs, Feet, Ring1, Ring2, Trinket1, Trinket2, MH, OH, Ranged } public static Slot ToSlot(string s) { switch(s) { case "Head": return Slot.Head; case "Neck": return Slot.Neck; case "Shoulders": return Slot.Shoulders; case "Back": return Slot.Back; case "Chest": return Slot.Chest; case "Wrist": return Slot.Wrist; case "Hands": return Slot.Hands; case "Waist": return Slot.Waist; case "Legs": return Slot.Legs; case "Feet": return Slot.Feet; case "Ring1": return Slot.Ring1; case "Ring2": return Slot.Ring2; case "Trinket1": return Slot.Trinket1; case "Trinket2": return Slot.Trinket2; case "MH": return Slot.MH; case "OH": return Slot.OH; case "Ranged": return Slot.Ranged; default: throw new Exception("Slot not found"); } } public static string FromSlot(Slot s) { switch(s) { case Slot.Head: return "Head"; case Slot.Neck: return "Neck"; case Slot.Shoulders: return "Shoulders"; case Slot.Back: return "Back"; case Slot.Chest: return "Chest"; case Slot.Wrist: return "Wrist"; case Slot.Hands: return "Hands"; case Slot.Waist: return "Waist"; case Slot.Legs: return "Legs"; case Slot.Feet: return "Feet"; case Slot.Ring1: return "Ring1"; case Slot.Ring2: return "Ring2"; case Slot.Trinket1: return "Trinket1"; case Slot.Trinket2: return "Trinket2"; case Slot.MH: return "MH"; case Slot.OH: return "OH"; case Slot.Ranged: return "Ranged"; default: throw new Exception("Slot not found"); } } #region Propriétés public static double GCD = 1.5; private int ressource; public int Ressource { get { return ressource; } set { if(value > 100) { ressource = 100; } else if(value < 0) { ressource = 0; } else { ressource = value; } } } public Dictionary<Slot, Item> Equipment { get; set; } public Dictionary<string, int> Talents { get; set; } public List<Enchantment> Buffs { get; set; } public Weapon MH { get { return (Weapon)Equipment[Slot.MH]; } set { Equipment[Slot.MH] = value; } } public Weapon OH { get { if (Equipment[Slot.OH] != null) { return (Weapon)Equipment[Slot.OH]; } else { return null; } } set { Equipment[Slot.OH] = value; } } public Weapon Ranged { get { if (Equipment[Slot.Ranged] != null) { return (Weapon)Equipment[Slot.Ranged]; } else { return null; } } set { Equipment[Slot.Ranged] = value; } } public double GCDUntil { get; set; } public double AP { get { return Attributes.GetValue(Attribute.AP) + BonusAttributes.GetValue(Attribute.AP); } } public double CritRating { get { return Attributes.GetValue(Attribute.CritChance) + BonusAttributes.GetValue(Attribute.CritChance); } } public double HitRating { get { return Attributes.GetValue(Attribute.HitChance) + BonusAttributes.GetValue(Attribute.HitChance); } } public Attributes Attributes { get; set; } public Attributes BonusAttributes { get; set; } public double HasteMod { get; set; } public double DamageMod { get; set; } public Races Race { get; set; } public Classes Class { get; set; } public Action applyAtNextAA = null; public Dictionary<Weapon.WeaponType, int> WeaponSkill { get; set; } public Dictionary<Entity, HitChances> HitChancesByEnemy { get; set; } public bool WindfuryTotem { get; set; } public List<string> Cooldowns { get; set; } #endregion public Player(Player p, Dictionary<Slot, Item> items = null, Dictionary<string, int> talents = null, List<Enchantment> buffs = null) : this(null, p, items, talents, buffs) { } public Player(Simulation s, Player p, Dictionary<Slot, Item> items = null, Dictionary<string, int> talents = null, List<Enchantment> buffs = null) : this(s, p.Class, p.Race, p.Level, p.Armor, p.MaxLife, items, talents, buffs) { } public Player(Simulation s = null, Classes c = Classes.Warrior, Races r = Races.Orc, int level = 60, int armor = 0, int maxLife = 1000, Dictionary<Slot, Item> items = null, Dictionary<string, int> talents = null, List<Enchantment> buffs = null) : base(s, level, armor, maxLife) { Race = r; Class = c; Talents = talents; Buffs = buffs; int skill = Level * 5; WeaponSkill = new Dictionary<Weapon.WeaponType, int>(); foreach (Weapon.WeaponType type in (Weapon.WeaponType[])Enum.GetValues(typeof(Weapon.WeaponType))) { if(Race == Races.Orc && type == Weapon.WeaponType.Axe) { WeaponSkill[type] = skill + 5; } else if(Race == Races.Human && (type == Weapon.WeaponType.Mace || type == Weapon.WeaponType.Sword)) { WeaponSkill[type] = skill + 5; } else { WeaponSkill[type] = skill; } } if(items == null) { Equipment = new Dictionary<Slot, Item>(); foreach (Slot slot in (Slot[])Enum.GetValues(typeof(Slot))) { Equipment[slot] = null; } } else { Equipment = new Dictionary<Slot, Item>(items); } HitChancesByEnemy = new Dictionary<Entity, HitChances>(); Reset(); } public int GetTalentPoints(string talent) { return Talents != null && Talents.ContainsKey(talent) ? Talents[talent] : 0; } public override void Reset() { base.Reset(); Ressource = 0; GCDUntil = 0; HasteMod = 1; DamageMod = 1; BonusAttributes = new Attributes(); } public void CalculateHitChances(Entity enemy = null) { if(enemy == null) { enemy = Sim.Boss; } Dictionary<ResultType, double> whiteHitChancesMH = new Dictionary<ResultType, double>(); whiteHitChancesMH.Add(ResultType.Miss, MissChance(DualWielding(), HitRating, WeaponSkill[MH.Type], enemy.Level)); whiteHitChancesMH.Add(ResultType.Dodge, enemy.DodgeChance(WeaponSkill[MH.Type])); whiteHitChancesMH.Add(ResultType.Parry, enemy.ParryChance()); whiteHitChancesMH.Add(ResultType.Glancing, GlancingChance(WeaponSkill[MH.Type], enemy.Level)); whiteHitChancesMH.Add(ResultType.Block, enemy.BlockChance()); whiteHitChancesMH.Add(ResultType.Crit, RealCritChance(CritRating, whiteHitChancesMH[ResultType.Miss], whiteHitChancesMH[ResultType.Glancing], whiteHitChancesMH[ResultType.Dodge], whiteHitChancesMH[ResultType.Parry], whiteHitChancesMH[ResultType.Block])); whiteHitChancesMH.Add(ResultType.Hit, RealHitChance(whiteHitChancesMH[ResultType.Miss], whiteHitChancesMH[ResultType.Glancing], whiteHitChancesMH[ResultType.Crit], whiteHitChancesMH[ResultType.Dodge], whiteHitChancesMH[ResultType.Parry], whiteHitChancesMH[ResultType.Block])); Dictionary<ResultType, double> whiteHitChancesOH = null; if (DualWielding()) { whiteHitChancesOH = new Dictionary<ResultType, double>(); whiteHitChancesOH.Add(ResultType.Miss, MissChance(true, HitRating + (OH.Buff == null ? 0 : OH.Buff.Attributes.GetValue(Attribute.HitChance)), WeaponSkill[OH.Type], enemy.Level)); whiteHitChancesOH.Add(ResultType.Dodge, enemy.DodgeChance(WeaponSkill[OH.Type])); whiteHitChancesOH.Add(ResultType.Parry, enemy.ParryChance()); whiteHitChancesOH.Add(ResultType.Glancing, GlancingChance(WeaponSkill[OH.Type], enemy.Level)); whiteHitChancesOH.Add(ResultType.Block, enemy.BlockChance()); whiteHitChancesOH.Add(ResultType.Crit, RealCritChance(CritRating + (OH.Buff == null ? 0 : OH.Buff.Attributes.GetValue(Attribute.CritChance)), whiteHitChancesOH[ResultType.Miss], whiteHitChancesOH[ResultType.Glancing], whiteHitChancesOH[ResultType.Dodge], whiteHitChancesOH[ResultType.Parry], whiteHitChancesOH[ResultType.Block])); whiteHitChancesOH.Add(ResultType.Hit, RealHitChance(whiteHitChancesOH[ResultType.Miss], whiteHitChancesOH[ResultType.Glancing], whiteHitChancesOH[ResultType.Crit], whiteHitChancesOH[ResultType.Dodge], whiteHitChancesOH[ResultType.Parry], whiteHitChancesOH[ResultType.Block])); } Dictionary<ResultType, double> yellowHitChances = new Dictionary<ResultType, double>(); yellowHitChances.Add(ResultType.Miss, MissChanceYellow(HitRating, WeaponSkill[MH.Type], enemy.Level)); yellowHitChances.Add(ResultType.Dodge, enemy.DodgeChance(WeaponSkill[MH.Type])); yellowHitChances.Add(ResultType.Parry, enemy.ParryChance()); yellowHitChances.Add(ResultType.Block, enemy.BlockChance()); yellowHitChances.Add(ResultType.Crit, RealCritChanceYellow(CritRating, yellowHitChances[ResultType.Miss], yellowHitChances[ResultType.Dodge])); yellowHitChances.Add(ResultType.Hit, RealHitChanceYellow(yellowHitChances[ResultType.Crit], yellowHitChances[ResultType.Miss], yellowHitChances[ResultType.Dodge])); if (HitChancesByEnemy.ContainsKey(enemy)) { HitChancesByEnemy[enemy] = new HitChances(whiteHitChancesMH, yellowHitChances, whiteHitChancesOH); } else { HitChancesByEnemy.Add(enemy, new HitChances(whiteHitChancesMH, yellowHitChances, whiteHitChancesOH)); } } #region WhiteAttackChances public static double MissChance(bool dualWield, double hitRating, int skill, int enemyLevel) { int enemySkill = enemyLevel * 5; int skillDif = Math.Abs(enemySkill - skill); return Math.Max(0, Math.Max(BASE_MISS + (dualWield ? 0.19 : 0) - hitRating, 0) + (skillDif > 10 ? 0.02 : 0) + (skillDif > 10 ? (enemySkill - skill - 10) * 0.004 : (enemySkill - skill) * 0.001)); } public static double GlancingChance(int level, int enemyLevel) { return Math.Max(0, 0.10 + (enemyLevel * 5 - level * 5) * 0.02); } public static double RealCritChance(double netCritChance, double realMiss, double realGlancing, double enemyDodgeChance, double enemyParryChance, double enemyBlockChance) { return Math.Max(0, Math.Min(netCritChance, 1 - realMiss - realGlancing - enemyDodgeChance - enemyParryChance - enemyBlockChance)); } public static double RealHitChance(double realMiss, double realGlancing, double realCrit, double enemyDodgeChance, double enemyParryChance, double enemyBlockChance) { return Math.Max(0, 1 - realMiss - realGlancing - realCrit - enemyDodgeChance - enemyParryChance - enemyBlockChance); } #endregion #region YellowAttackChances public static double MissChanceYellow(double hitRating, int skill, int enemyLevel) { int enemySkill = enemyLevel * 5; int skillDif = Math.Abs(enemySkill - skill); return Math.Max(0, Math.Max(BASE_MISS - hitRating, 0) + (skillDif > 10 ? 0.02 : 0) + (skillDif > 10 ? (enemySkill - skill - 10) * 0.004 : (enemySkill - skill) * 0.001)); } public static double RealCritChanceYellow(double netCritChance, double realMiss, double enemyDodgeChance) { return Math.Max(0, netCritChance * (1 - realMiss - enemyDodgeChance)); } public static double RealHitChanceYellow(double realCrit, double realMiss, double enemyDodgeChance) { return Math.Max(0, 1 - realCrit - realMiss - enemyDodgeChance); } #endregion public ResultType WhiteAttackEnemy(Entity enemy, bool MH) { if (!HitChancesByEnemy.ContainsKey(enemy)) { CalculateHitChances(enemy); } return PickFromTable(MH ? HitChancesByEnemy[enemy].WhiteHitChancesMH : HitChancesByEnemy[enemy].WhiteHitChancesOH, Sim.random.NextDouble()); } public ResultType YellowAttackEnemy(Entity enemy) { if (!HitChancesByEnemy.ContainsKey(enemy)) { CalculateHitChances(enemy); } return PickFromTable(HitChancesByEnemy[enemy].YellowHitChances, Sim.random.NextDouble()); } public ResultType PickFromTable(Dictionary<ResultType, double> table, double rand) { Dictionary<ResultType, double> pickTable = new Dictionary<ResultType, double>(table); bool reckless = Effects.Any(e => e is RecklessnessBuff); if(Effects.Any(e => e is RecklessnessBuff)) { pickTable[ResultType.Hit] = 0; pickTable[ResultType.Crit] = 1; } /* string debug = "rand " + rand; foreach (ResultType type in pickTable.Keys) { debug += " | " + type + " - " + table[type]; } if(Program.logFight) { Program.Log(debug); } */ double i = 0; foreach(ResultType type in pickTable.Keys) { i += pickTable[type]; if(rand <= i) { return type; } } throw new Exception("Hit Table Failed"); } public bool DualWielding() { return OH != null; } public void StartGCD() { GCDUntil = Sim.CurrentTime + GCD; } public bool HasGCD() { return GCDUntil <= Sim.CurrentTime; } public void CalculateAttributes() { Attributes = new Attributes(new Dictionary<Attribute, double> { // TODO : attributs de base par level par classe { Attribute.Stamina, BaseStaByRace(Race) + BonusStaByClass(Class) + 88 }, { Attribute.Strength, BaseStrByRace(Race) + BonusStrByClass(Class) + 97 }, { Attribute.Agility, BaseAgiByRace(Race) + BonusAgiByClass(Class) + 60 }, { Attribute.Intelligence, BaseIntByRace(Race) + BonusIntByClass(Class) }, { Attribute.Spirit, BaseSpiByRace(Race) + BonusSpiByClass(Class) }, { Attribute.AP, 160 }, // Base armor + dodge + etc. // Base health + mana ? }); foreach(Slot s in Equipment.Keys.Where(v => Equipment[v] != null)) { Item i = Equipment[s]; Attributes += i.Attributes; if(i.Enchantment != null) { Attributes += i.Enchantment.Attributes; } if (s == Slot.MH) { Weapon w = ((Weapon)i); if (w.Buff != null) Attributes += w.Buff.Attributes; } } int wbonus = (int)Math.Round(Attributes.GetValue(Attribute.WeaponDamage)); MH.DamageMin += wbonus; MH.DamageMax += wbonus; if(OH != null) { OH.DamageMin += wbonus; OH.DamageMax += wbonus; } Attributes += BonusAttributesByRace(Race, Attributes); Attributes.SetValue(Attribute.Health, 20 + (Attributes.GetValue(Attribute.Stamina) - 20) * 10); Attributes.SetValue(Attribute.AP, Attributes.GetValue(Attribute.AP) + Attributes.GetValue(Attribute.Strength) * StrToAPRatio(Class)); Attributes.SetValue(Attribute.RangedAP, Attributes.GetValue(Attribute.AP) + Attributes.GetValue(Attribute.Agility) * AgiToRangedAPRatio(Class)); Attributes.SetValue(Attribute.CritChance, Attributes.GetValue(Attribute.CritChance) + Attributes.GetValue(Attribute.Agility) * AgiToCritRatio(Class)); HasteMod = 1 + Attributes.GetValue(Attribute.AS); if (Class == Classes.Warrior) { Attributes.SetValue(Attribute.CritChance, Attributes.GetValue(Attribute.CritChance) + 0.01 * GetTalentPoints("Cruelty") + 0.03); // Berserker Stance } foreach (Enchantment e in Buffs.Where(v => v != null)) { Attributes += e.Attributes; } } public static int StrToAPRatio(Classes c) { return (c == Classes.Druid || c == Classes.Warrior || c == Classes.Shaman || c == Classes.Paladin) ? 2 : 1; } public static int AgiToRangedAPRatio(Classes c) { return (c == Classes.Warrior || c == Classes.Hunter || c == Classes.Rogue) ? 2 : 1; } public static double AgiToCritRatio(Classes c) { switch(c) { case Classes.Hunter: return (double)1 / 5300; case Classes.Rogue: return (double)1 / 2900; default: return (double)1 / 2000; } } public static int BaseStrByRace(Races r) { switch (r) { case Races.Human: return 20; case Races.Dwarf: return 22; case Races.NightElf: return 17; case Races.Gnome: return 15; case Races.Orc: return 23; case Races.Undead: return 19; case Races.Tauren: return 25; case Races.Troll: return 21; default: return 0; } } public static int BaseAgiByRace(Races r) { switch (r) { case Races.Human: return 20; case Races.Dwarf: return 16; case Races.NightElf: return 25; case Races.Gnome: return 23; case Races.Orc: return 17; case Races.Undead: return 18; case Races.Tauren: return 15; case Races.Troll: return 22; default: return 0; } } public static int BaseStaByRace(Races r) { switch (r) { case Races.Human: return 20; case Races.Dwarf: return 23; case Races.NightElf: return 19; case Races.Gnome: return 19; case Races.Orc: return 22; case Races.Undead: return 21; case Races.Tauren: return 22; case Races.Troll: return 21; default: return 0; } } public static int BaseIntByRace(Races r) { switch (r) { case Races.Human: return 20; case Races.Dwarf: return 19; case Races.NightElf: return 20; case Races.Gnome: return 24; case Races.Orc: return 17; case Races.Undead: return 18; case Races.Tauren: return 15; case Races.Troll: return 16; default: return 0; } } public static int BaseSpiByRace(Races r) { switch (r) { case Races.Human: return 21; case Races.Dwarf: return 19; case Races.NightElf: return 20; case Races.Gnome: return 20; case Races.Orc: return 23; case Races.Undead: return 25; case Races.Tauren: return 22; case Races.Troll: return 21; default: return 0; } } public static int BonusStrByClass(Classes c) { switch (c) { case Classes.Warrior: return 3; default: return 0; } } public static int BonusAgiByClass(Classes c) { switch (c) { case Classes.Warrior: return 0; default: return 0; } } public static int BonusStaByClass(Classes c) { switch (c) { case Classes.Warrior: return 2; default: return 0; } } public static int BonusIntByClass(Classes c) { switch (c) { case Classes.Warrior: return 0; default: return 0; } } public static int BonusSpiByClass(Classes c) { switch (c) { case Classes.Warrior: return 0; default: return 0; } } public Attributes BonusAttributesByRace(Races r, Attributes a) { Attributes res = new Attributes(); switch(r) { case Races.Gnome: res.SetValue(Attribute.Intelligence, (int)Math.Round(a.GetValue(Attribute.Intelligence) * 0.05)); break; case Races.Human: res.SetValue(Attribute.Spirit, (int)Math.Round(a.GetValue(Attribute.Spirit) * 0.05)); break; default: break; } return res; } public override double BlockChance() { return 0; } public override double ParryChance() { return 0; } public Dictionary<Spell, int> CooldownsListToSpellsDic(List<string> cds) { Dictionary<Spell, int> res = new Dictionary<Spell, int>(); foreach(string s in cds) { switch(s) { case "DeathWish": res.Add(new DeathWish(this), DeathWishBuff.LENGTH); break; case "JujuFlurry": res.Add(new JujuFlurry(this), JujuFlurryBuff.LENGTH); break; case "MightyRage": res.Add(new MightyRage(this), MightyRageBuff.LENGTH); break; case "Recklessness": res.Add(new Recklessness(this), RecklessnessBuff.LENGTH); break; case "BloodFury": res.Add(new BloodFury(this), BloodFuryBuff.LENGTH); break; case "Berserking": res.Add(new Berserking(this), BerserkingBuff.LENGTH); break; } } return res; } public override string ToString() { return string.Format("{0} {1} level {2} | Stats : {3}", Race, Class, Level, Attributes); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace OneDayInOutset002 { public class Construct { public World world; public Loc Loc0 { get; set; } public Loc Loc1 { get; set; } public Loc Loc2 { get; set; } public Loc Loc3 { get; set; } public Loc Loc4 { get; set; } public Loc Loc5 { get; set; } public Loc Loc6 { get; set; } public Loc Loc7 { get; set; } public Loc Loc8 { get; set; } public Loc Loc9 { get; set; } public Loc Loc10 { get; set; } public Loc Loc11 { get; set; } public Cho Startup1 { get; set; } public Cho Startup2 { get; set; } public Cho Startup3 { get; set; } public Cho Startup4 { get; set; } public Cho neighborGood1 { get; set; } public Cho neighborGood2 { get; set; } public Cho neighborGood3 { get; set; } public void BuildButton1() { } public void LocConnect(Loc loc, Loc con) { loc.locconnect.Add(con); } public void LocLink(Loc loc, Loc loc2) { loc.locconnect.Add(loc2); loc2.locconnect.Add(loc); } public void LocArray(Loc loc, params Loc[] locs) { for (int i = 0; i < locs.Length; i++) { LocLink(loc, locs[i]); } } public void ChoiceChain(Cho cho, Cho cho2) { cho.choices.Add(cho2); } public void ChoiceArray(Cho cho, params Cho[] chos) { for (int i = 0; i < chos.Length; i++) { ChoiceChain(cho, chos[i]); } } public void Startup() { world = new World(Loc0); // Loc0 = new Loc(LocInfo.LocStart, LocInfo.Loc0Desc); Loc1 = new Loc(LocInfo.Loc1Name, LocInfo.Loc1Desc); Loc2 = new Loc(LocInfo.Loc2Name, LocInfo.Loc2Desc); Loc3 = new Loc(LocInfo.Loc3Name, LocInfo.Loc3Desc); Loc4 = new Loc(LocInfo.Loc4Name, LocInfo.Loc4Desc); Loc5 = new Loc(LocInfo.Loc5Name, LocInfo.Loc5Desc); Loc6 = new Loc(LocInfo.Loc6Name, LocInfo.Loc6Desc); Loc7 = new Loc(LocInfo.Loc7Name, LocInfo.Loc7Desc); Loc8 = new Loc(LocInfo.Loc8Name, LocInfo.Loc8Desc); Loc9 = new Loc(LocInfo.Loc9Name, LocInfo.Loc9Desc); Loc10 = new Loc(LocInfo.Loc10Name, LocInfo.Loc10Desc); Loc11 = new Loc(LocInfo.Loc11Name, LocInfo.Loc11Desc); // LocConnect(Loc1, Loc2); // LocArray(Loc2, Loc3, Loc4); // LocArray(Loc4, Loc5, Loc6, Loc7); // LocLink(Loc5, Loc6); // LocLink(Loc7, Loc8); // LocLink(Loc8, Loc9); // LocLink(Loc9, Loc10); // LocLink(Loc10, Loc11); // // // Startup1 = new Cho("startup1", ChoInfo.Startup1); Startup2 = new Cho("startup2", ChoInfo.Startup2); Startup3 = new Cho("startup3", ChoInfo.Startup3); Startup4 = new Cho("startup3", ChoInfo.Startup4); neighborGood1 = new Cho(ChoInfo.neighborGood1Name, ChoInfo.neighborGood1Text); neighborGood2 = new Cho(ChoInfo.neighborGood2Name, ChoInfo.neighborGood2Text); // ChoiceChain(Startup1, Startup2); ChoiceChain(Startup2, Startup3); ChoiceChain(Startup3, Startup4); ChoiceArray(Startup4, neighborGood1, neighborGood2); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Utilities; namespace EddiEddnResponder.Toolkit { public class GameVersionAugmenter { // We keep track of game version and active expansions locally // Ref. https://github.com/EDCD/EDDN/blob/master/docs/Developers.md#horizons-and-odyssey-flags public string gameVersion { get; private set; } public string gameBuild { get; private set; } public bool? inHorizons { get; private set; } public bool? inOdyssey { get; private set; } internal void GetVersionInfo(string eventType, IDictionary<string, object> data) { try { if (string.Equals("FileHeader", eventType, StringComparison.InvariantCultureIgnoreCase)) { // Do not attempt to use the 'Horizons' and 'Odyssey' value(s) from a Fileheader event as the semantics are different. // In the Fileheader event the Odyssey flag is indicating whether it's a 4.0 game client. // In the LoadGame event the Horizons and Odyssey flags indicate if those features are active, // but in the 3.8 game client case you only get the Horizons boolean. gameVersion = JsonParsing.getString(data, "gameversion") ?? gameVersion; gameBuild = JsonParsing.getString(data, "build") ?? gameBuild; } else if (string.Equals("LoadGame", eventType, StringComparison.InvariantCultureIgnoreCase)) { gameVersion = JsonParsing.getString(data, "gameversion") ?? gameVersion; gameBuild = JsonParsing.getString(data, "build") ?? gameBuild; inHorizons = JsonParsing.getOptionalBool(data, "Horizons") ?? inHorizons; inOdyssey = JsonParsing.getOptionalBool(data, "Odyssey") ?? inOdyssey; } else if (string.Equals("Outfitting", eventType, StringComparison.InvariantCultureIgnoreCase) || string.Equals("Shipyard", eventType, StringComparison.InvariantCultureIgnoreCase)) { inHorizons = JsonParsing.getOptionalBool(data, "Horizons") ?? inHorizons; inOdyssey = JsonParsing.getOptionalBool(data, "Odyssey") ?? inOdyssey; } } catch (Exception ex) { Logging.Error("Failed to parse Elite Dangerous version data for EDDN", ex); } } internal IDictionary<string, object> AugmentVersion(IDictionary<string, object> data) { // Apply game version augment (only if the game is running) if (Process .GetProcesses() .Where(p => p.ProcessName.StartsWith("EliteDangerous32") || p.ProcessName.StartsWith("EliteDangerous64")) .Any()) { // Only include flags that are present in the source files. // If the source value is null, do not add anything. if (!data.ContainsKey("horizons") && inHorizons != null) { data.Add("horizons", inHorizons); } if (!data.ContainsKey("odyssey") && inOdyssey != null) { data.Add("odyssey", inOdyssey); } } return data; } } }
namespace OptionalTypes.JsonConverters.Tests.TestDtos { public class NonOptionalApplicationReceived { public string FirstName { get; set; } public string LastName { get; set; } public string Company { get; set; } public string EmailAddres { get; set; } public string Position { get; set; } public int BrandId { get; set; } public int DepartmentId { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections; namespace FXB.Dialog { public partial class PageSelect : Form { private string selectPage = ""; private DataRowCollection rows; public PageSelect(DataRowCollection tp) { InitializeComponent(); rows = tp; } private void OkBtn_Click(object sender, EventArgs e) { if (PageCb.SelectedIndex == -1) { MessageBox.Show("请选择一个页签"); return; } selectPage = PageCb.Items[PageCb.SelectedIndex].ToString(); DialogResult = DialogResult.OK; Close(); } private void PageSelect_Load(object sender, EventArgs e) { this.FormBorderStyle = FormBorderStyle.FixedSingle; foreach (DataRow row in rows) { PageCb.Items.Add(row["TABLE_NAME"].ToString()); } } public string SelectPage { get {return selectPage;} } } }
using JhinBot.GlobalConst; using JhinBot.Interface; namespace JhinBot.Formatters { public class StrikenFormatter : IMessageFormatter { public string GetFormattedMessage(string msg) { return $"{Global.Params.STRIKEN_CHAR}{msg}{Global.Params.STRIKEN_CHAR}"; } } }
using System.ComponentModel.DataAnnotations; using Alabo.Web.Mvc.Attributes; namespace Alabo.Industry.Shop.Categories.Domain.Enums { [ClassProperty(Name = "控件显示类型")] public enum PropertyControlType { /// <summary> /// 文本框 /// </summary> [LabelCssClass("m-badge--success", IsDataField = true)] [Display(Name = "文本框")] TextBox = 1, /// <summary> /// 多选框 /// </summary> [LabelCssClass("m-badge--success", IsDataField = true)] [Display(Name = "多选框")] CheckBox = 3, /// <summary> /// 单选框 /// </summary> [LabelCssClass("m-badge--success", IsDataField = true)] [Display(Name = "单选框")] RadioButton = 4, /// <summary> /// 下拉列表 /// </summary> [LabelCssClass("m-badge--success", IsDataField = true)] [Display(Name = "下拉列表")] DropdownList = 5, /// <summary> /// 数字框 /// </summary> [LabelCssClass("m-badge--success", IsDataField = true)] [Display(Name = "数字框")] Numberic = 6, /// <summary> /// 时间框 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "时间框")] DateTimePicker = 8, /// <summary> /// 样式参考:http://ui.5ug.com/metronic_v4.5.4/theme/admin_4/components_bootstrap_switch.html /// </summary> [LabelCssClass("m-badge--success", IsDataField = true)] [Display(Name = "Switch切换")] Switch = 14 } }
namespace Uintra.Core.MediaToolkit.Options { public enum Target { Default, VCD, SVCD, DVD, DV, DV50 } public enum TargetStandard { Default, PAL, NTSC, FILM } public enum AudioSampleRate { Default, Hz22050, Hz44100, Hz48000 } public enum VideoAspectRatio { Default, R3_2, R4_3, R5_3, R5_4, R16_9, R16_10, R17_9 } public enum VideoSize { Default, _16Cif, _2K, _2Kflat, _2Kscope, _4Cif, _4K, _4Kflat, _4Kscope, Cga, Cif, Ega, Film, Fwqvga, Hd1080, Hd480, Hd720, Hqvga, Hsxga, Hvga, Nhd, Ntsc, Ntsc_Film, Pal, Qcif, Qhd, Qntsc, Qpal, Qqvga, Qsxga, Qvga, Qxga, Sntsc, Spal, Sqcif, Svga, Sxga, Uxga, Vga, Whsxga, Whuxga, Woxga, Wqsxga, Wquxga, Wqvga, Wsxga, Wuxga, Wvga, Wxga, Xga, Custom } }
 using Nop.Core.Configuration; namespace Nop.Plugin.Widgets.TypeProducts { public class TypeProductsSettings : ISettings { public int NumberOfBestsellersOnHomepage { get; set; } public int NumberOfNewProductOnHomepage { get; set; } public int NumberOfHomePageProductOnHomepage { get; set; } public bool ShowBestSellerProduct { get; set; } public bool ShowNewProduct { get; set; } public bool ShowHomePageProduct { get; set; } public int CacheTime { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UFIDA.U9.SM.SO; using HBH.DoNet.DevPlatform.EntityMapping; using UFSoft.UBF.Business; using U9.VOB.Cus.HBHTianRiSheng.HBHHelper; using UFIDA.U9.SM.Enums; using UFIDA.U9.CBO.SCM.Enums; using UFIDA.U9.SM; using UFSoft.UBF.PL.ObjectAccess; using UFIDA.U9.PriceCal.PriceCalSV; using UFIDA.U9.PriceCal.PriceCalSV.Proxy; using UFSoft.UBF.PL.Engine; using UFIDA.U9.CBO.TradePath; using System.Reflection; namespace U9.VOB.Cus.HBHTianRiSheng.BEPlugIn { public class SO_BeforeDefaultValue : UFSoft.UBF.Eventing.IEventSubscriber { public void Notify(params object[] args) { if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent)) { return; } UFSoft.UBF.Business.BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey; if (key != null) { SO entity = key.GetEntity() as SO; if (entity != null && entity.OriginalData != null && entity.OriginalData.Status == SODocStatusEnum.Open && entity.Status == SODocStatusEnum.Open ) { // UI 更新修改变动了金额 if (entity.SysState != UFSoft.UBF.PL.Engine.ObjectState.Inserted && entity.Status == SODocStatusEnum.Open //&& entity.ActionSrc == SMActivityEnum.FOUIUpd && entity.ActionSrc != SMActivityEnum.OBAUpdate ) { List<UIChangeInfoData> list = new List<UIChangeInfoData>(); int num = 0; //bool isRecalcByVouchers = false; foreach (SOLine line in entity.SOLines) { // 券分摊金额 Pri 2 // 原含税金额 Pri 3 if (line != null && line.OriginalData != null && line.OriginalData.TotalMoneyTC != line.TotalMoneyTC ) { // 重新分摊 抵用卷金额 line.DescFlexField.PrivateDescSeg3 = line.TotalMoneyTC.ToString("G0"); string strVouMoney = line.DescFlexField.PrivateDescSeg2; decimal dVouchers = PubClass.GetDecimal(strVouMoney); // 有抵用券金额,重新分摊 if (dVouchers != 0) { line.TotalMoneyTC -= dVouchers; line.PriceCalField = "TotalMoneyTC"; //line.OriginalData.TotalMoneyTC = //isRecalcByVouchers = true; UIChangeInfoData uIChangeInfoData = new UIChangeInfoData { ActionEnum = 2, ID = line.ID, ObjectName = 1, Sequence = num++ }; if (entity.IsPriceIncludeTax) { uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; uIChangeInfoData.OldValue = line.NetMoneyTC != 0 ? 0 : 1; uIChangeInfoData.NewValue = line.TotalMoneyTC; } else { uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; uIChangeInfoData.OldValue = line.NetMoneyTC != 0 ? 0 : 1; uIChangeInfoData.NewValue = line.NetMoneyTC; } if (line.ApportionPriceTC == 1M) { line.ApportionPriceTC = 0M; } if (uIChangeInfoData != null) { list.Add(uIChangeInfoData); } } } } //if (isRecalcByVouchers) { //new SOPriceCal(entity).DealPriceCal(BusinessOperatorTypeEnumData.NewCreate); //entity.IsQuickCreate = true; //entity.ActionSrc = SMActivityEnum.OBAUpdate; if (SMTools.IsNotNull<UIChangeInfoData>(list)) { //priceCalc.DealPriceCal(list, true); DealPriceCal(new SOPriceCal(entity), list, true); } } } } } } #region SO PriceCal public void DealPriceCal(BusinessOperatorTypeEnumData action, SO so, SOPriceCal priceCalc , List<UIChangeInfoData> list ) { if (!SMTools.IsNull((ObjectList)so.SOLines)) { //List<UIChangeInfoData> list = new List<UIChangeInfoData>(); int num = 0; foreach (SOLine line in so.SOLines) { UIChangeInfoData uIChangeInfoData = null; //if ((so.ActionSrc == SMActivityEnum.OBAUpdate) && !so.IsQuickCreate) //{ // uIChangeInfoData = new UIChangeInfoData // { // ActionEnum = 2 // }; // if ((line.FinallyPriceTC > 0M) && (line.OrderPriceTC == 0M)) // { // line.OrderPriceTC = line.FinallyPriceTC; // } // if (((line.OrderPriceTC == 0M) && (line.FinallyPriceTC == 0M)) && SMConstant.IsDiscountItemMaster(line.ItemInfo.ItemID)) // { // line.FinallyPriceTC = -1M; // line.OrderPriceTC = -1M; // line.SrcDocPrice = -1M; // line.PriceSource = PriceSourceEnum.SourceDoc; // } // if (!string.IsNullOrEmpty(line.PriceCalField)) // { // priceCalc.SetChangeInfoData(line, uIChangeInfoData); // } // else if (((ObjectState)line.get_SysState()).Equals((ObjectState)2)) // { // if (line.PriceSource == PriceSourceEnum.PriceList) // { // uIChangeInfoData.FieldName = "QtyPriceUOM"; // } // else if ((((line.TotalMoneyTC > 0M) || (line.NetMoneyTC > 0M)) || (line.FinallyPriceTC > 0M)) || (line.OrderPriceTC > 0M)) // { // if ((line.PriceSource == PriceSourceEnum.Empty) && (so.ActionSrc == SMActivityEnum.OBAUpdate)) // { // line.PriceSource = PriceSourceEnum.Custom; // } // if ((line.TotalMoneyTC > 0M) || (line.NetMoneyTC > 0M)) // { // if (so.IsPriceIncludeTax && (line.TotalMoneyTC > 0M)) // { // uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; // uIChangeInfoData.OldValue = line.TotalMoneyTC; // uIChangeInfoData.NewValue = line.TotalMoneyTC; // } // else if (!(so.IsPriceIncludeTax || (line.NetMoneyTC <= 0M))) // { // uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; // uIChangeInfoData.OldValue = line.NetMoneyTC; // uIChangeInfoData.NewValue = line.NetMoneyTC; // } // else if (line.TotalMoneyTC > 0M) // { // uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; // uIChangeInfoData.OldValue = line.TotalMoneyTC; // uIChangeInfoData.NewValue = line.TotalMoneyTC; // } // else // { // uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; // uIChangeInfoData.OldValue = line.NetMoneyTC; // uIChangeInfoData.NewValue = line.NetMoneyTC; // } // } // else if (line.FinallyPriceTC > 0M) // { // if (line.OrderPriceTC == 0M) // { // line.OrderPriceTC = line.FinallyPriceTC; // uIChangeInfoData.FieldName = "OrderPrice"; // } // else // { // uIChangeInfoData.FieldName = "FinallyPrice"; // uIChangeInfoData.OldValue = line.OriginalData.FinallyPriceTC; // uIChangeInfoData.NewValue = line.FinallyPriceTC; // } // } // else if (line.OrderPriceTC > 0M) // { // uIChangeInfoData.FieldName = "OrderPrice"; // uIChangeInfoData.OldValue = line.OrderPriceTC; // } // } // else // { // uIChangeInfoData.ActionEnum = 0; // } // } // else if (!string.IsNullOrEmpty(line.PriceCalField)) // { // priceCalc.SetChangeInfoData(line, uIChangeInfoData); // } // else if (line.PriceListID != line.OriginalData.PriceListID) // { // line.PriceSource = PriceSourceEnum.Empty; // uIChangeInfoData.FieldName = "PriceList"; // } // else if ((((line.TotalMoneyTC > 0M) || (line.NetMoneyTC > 0M)) || (line.FinallyPriceTC > 0M)) || (line.OrderPriceTC > 0M)) // { // if (line.OrderByQtyPU != line.OriginalData.OrderByQtyPU) // { // uIChangeInfoData.FieldName = "FinallyPrice"; // uIChangeInfoData.OldValue = line.OriginalData.FinallyPriceTC; // uIChangeInfoData.NewValue = line.FinallyPriceTC; // } // else if (((line.TotalMoneyTC > 0M) && (line.TotalMoneyTC != line.OriginalData.TotalMoneyTC)) || ((line.NetMoneyTC > 0M) && (line.NetMoneyTC != line.OriginalData.NetMoneyTC))) // { // if (so.IsPriceIncludeTax && (line.TotalMoneyTC > 0M)) // { // uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; // uIChangeInfoData.OldValue = line.OriginalData.TotalMoneyTC; // uIChangeInfoData.NewValue = line.TotalMoneyTC; // } // else if (!(so.IsPriceIncludeTax || (line.NetMoneyTC <= 0M))) // { // uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; // uIChangeInfoData.OldValue = line.OriginalData.NetMoneyTC; // uIChangeInfoData.NewValue = line.NetMoneyTC; // } // else if (line.TotalMoneyTC > 0M) // { // uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; // uIChangeInfoData.OldValue = line.OriginalData.TotalMoneyTC; // uIChangeInfoData.NewValue = line.TotalMoneyTC; // } // else // { // uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; // uIChangeInfoData.OldValue = line.OriginalData.NetMoneyTC; // uIChangeInfoData.NewValue = line.NetMoneyTC; // } // } // else if ((line.FinallyPriceTC > 0M) && (line.FinallyPriceTC != line.OriginalData.FinallyPriceTC)) // { // if (line.OrderPriceTC == 0M) // { // line.OrderPriceTC = line.FinallyPriceTC; // uIChangeInfoData.FieldName = "OrderPrice"; // } // else // { // uIChangeInfoData.FieldName = "FinallyPrice"; // uIChangeInfoData.OldValue = line.OriginalData.FinallyPriceTC; // uIChangeInfoData.NewValue = line.FinallyPriceTC; // } // } // else if ((line.OrderPriceTC > 0M) && (line.OrderPriceTC != line.OriginalData.OrderPriceTC)) // { // uIChangeInfoData.FieldName = "OrderPrice"; // uIChangeInfoData.OldValue = line.OrderPriceTC; // } // else // { // uIChangeInfoData.ActionEnum = 3; // } // } // else // { // uIChangeInfoData.ActionEnum = 0; // } // uIChangeInfoData.ID = line.ID; // uIChangeInfoData.ObjectName = 1; // uIChangeInfoData.Sequence = num++; //} //else { if (line.IsSrcPO() && line.IsFreeSOLine()) { continue; } if (line.IsSrcLoanToSale() && ((ObjectState)so.SysState).Equals((ObjectState)2)) { uIChangeInfoData = new UIChangeInfoData(); if (line.PriceSource == PriceSourceEnum.Empty) { uIChangeInfoData.FieldName = "PriceList"; uIChangeInfoData.OldValue = line.PriceListID; } else if (line.PriceSource == PriceSourceEnum.Custom) { uIChangeInfoData.FieldName = "OrderPrice"; uIChangeInfoData.OldValue = line.OrderPriceTC; } uIChangeInfoData.ActionEnum = 0; uIChangeInfoData.ID = line.ID; uIChangeInfoData.ObjectName = 1; uIChangeInfoData.Sequence = num++; } else if ((!line.IsSrcQuotation() || (line.IsSrcQuotation() && (line.ApportionPriceTC != 1M))) && ((ObjectState)line.SysState).Equals((ObjectState)2)) { uIChangeInfoData = new UIChangeInfoData(); if (line.IsSrcPO() || line.IsSrcDSO()) { uIChangeInfoData.ActionEnum = 2; } else { uIChangeInfoData.ActionEnum = 0; } uIChangeInfoData.ID = line.ID; uIChangeInfoData.ObjectName = 1; uIChangeInfoData.Sequence = num++; if ((line.TotalMoneyTC > 0M) || (line.NetMoneyTC > 0M)) { if (line.IsSrcPO()) { //line.IsPriceCalDoingForPO = true; SetSOLine_IsPriceCalDoingForPO(line,true); if (line.TradePathControlMoney.Equals(ControlMoneyEnum.PriceTaxTotal)) { uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; uIChangeInfoData.OldValue = 0; uIChangeInfoData.NewValue = line.TotalMoneyTC; } else { uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; uIChangeInfoData.OldValue = 0; uIChangeInfoData.NewValue = line.NetMoneyTC; } } else if (so.IsPriceIncludeTax || (line.NetMoneyTC == 0M)) { uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; uIChangeInfoData.OldValue = line.TotalMoneyTC; uIChangeInfoData.NewValue = line.TotalMoneyTC; uIChangeInfoData.ActionEnum = 2; } else { uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; uIChangeInfoData.OldValue = line.NetMoneyTC; uIChangeInfoData.NewValue = line.NetMoneyTC; uIChangeInfoData.ActionEnum = 2; } } else if (line.FinallyPriceTC > 0M) { uIChangeInfoData.FieldName = "FinallyPrice"; uIChangeInfoData.OldValue = line.FinallyPriceTC; uIChangeInfoData.NewValue = line.FinallyPriceTC; } else if (line.OrderPriceTC > 0M) { uIChangeInfoData.FieldName = "OrderPrice"; uIChangeInfoData.OldValue = line.OrderPriceTC; } else { uIChangeInfoData.FieldName = "QtyPriceUOM"; } } else { if (((line.IsSrcPO() || ((line.TradePathKey != null) && line.TradePath.FirstSetRange.Equals(FirstSetRangeEnum.SOPositive))) && (line.NetMoneyTC == line.OriginalData.NetMoneyTC)) && (line.TotalMoneyTC == line.OriginalData.TotalMoneyTC)) { continue; } uIChangeInfoData = new UIChangeInfoData { ActionEnum = 2, ID = line.ID, ObjectName = 1, Sequence = num++ }; if (line.IsSrcPO()) { //line.IsPriceCalDoingForPO = true; SetSOLine_IsPriceCalDoingForPO(line, true); if (line.TradePathControlMoney.Equals(ControlMoneyEnum.PriceTaxTotal)) { uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; uIChangeInfoData.OldValue = 0; uIChangeInfoData.NewValue = line.TotalMoneyTC; } else { uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; uIChangeInfoData.OldValue = 0; uIChangeInfoData.NewValue = line.NetMoneyTC; } } else if ((line.TradePathKey != null) && line.TradePath.FirstSetRange.Equals(FirstSetRangeEnum.SOPositive)) { if (line.TradePathControlMoney.Equals(ControlMoneyEnum.PriceTaxTotal)) { uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; uIChangeInfoData.OldValue = line.OriginalData.TotalMoneyTC; uIChangeInfoData.NewValue = line.TotalMoneyTC; } else { uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; uIChangeInfoData.OldValue = line.OriginalData.NetMoneyTC; uIChangeInfoData.NewValue = line.NetMoneyTC; } } else if (so.IsPriceIncludeTax) { uIChangeInfoData.FieldName = "TotalMoneyIncludeTax"; uIChangeInfoData.OldValue = line.OriginalData.TotalMoneyTC; uIChangeInfoData.NewValue = line.TotalMoneyTC; } else { uIChangeInfoData.FieldName = "TotalMoneyExcludeTax"; uIChangeInfoData.OldValue = line.OriginalData.NetMoneyTC; uIChangeInfoData.NewValue = line.NetMoneyTC; } if (line.ApportionPriceTC == 1M) { line.ApportionPriceTC = 0M; } } } if (uIChangeInfoData != null) { list.Add(uIChangeInfoData); } } if (SMTools.IsNotNull<UIChangeInfoData>(list)) { //priceCalc.DealPriceCal(list, true); DealPriceCal(priceCalc, list, true); } } } private void SetSOLine_IsPriceCalDoingForPO(SOLine line, bool value) { //line.IsPriceCalDoingForPO = true; Type tp = typeof(SOLine); foreach (PropertyInfo rInfo in tp.GetProperties()) { if (rInfo.Name == "IsPriceCalDoingForPO") { if (rInfo.CanWrite) { rInfo.SetValue(line, value, null); } } } } internal static void DealPriceCal(SOPriceCal priceCalc, List<UIChangeInfoData> changeList, bool isReCalFeeAfterBaseChange) { Type type = typeof(SOPriceCal); MethodInfo method = type.GetMethod("DealPriceCal" //, new Type[2] { typeof(List<UIChangeInfoData>), typeof(bool) } , BindingFlags.Instance | BindingFlags.NonPublic ); object[] param = new object[2] { changeList , isReCalFeeAfterBaseChange }; try { method.Invoke(priceCalc, param); } catch (TargetInvocationException ex) { throw ex.InnerException; } //return result; } //internal static void DealPriceCal(this SOPriceCal priceCalc, List<UIChangeInfoData> changeList, bool isReCalFeeAfterBaseChange) //{ // if ((changeList != null) && (changeList.Count != 0)) // { // SDCalculatePriceProxy proxy = new SDCalculatePriceProxy // { // Ctx = new PriceCalContextData() // }; // proxy.Ctx.DiscountDiffTo = priceCalc.GetDiffToSOLineOfDiscount(); // proxy.Ctx.FeeDiffTo = proxy.Ctx.DiscountDiffTo; // proxy.Ctx.IsReCalFeeAfterBaseChange = isReCalFeeAfterBaseChange; // proxy.Ctx.TaxDiffTo = 0; // proxy.Doc = priceCalc.ToDocPriceInfo(); // proxy.Changes = changeList; // DocPriceInfoData docPriceInfoData = proxy.Do(); // if (docPriceInfoData != null) // { // this.SetPriceInfo(docPriceInfoData); // } // } //} #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Logging; using Steeltoe.CircuitBreaker.Hystrix; using WingtipToys.Models; namespace WingtipToys.Client { public class GetProductCommand : HystrixCommand<Product> { public IProductService _productService; public ILogger<GetProductCommand> _logger; public int ProductID { get { return _productId; } set{ _productId = value; } } private int _productId; private IDistributedCache _cache; public GetProductCommand(IHystrixCommandOptions options, IProductService productService, ILogger<GetProductCommand> logger, IDistributedCache cache) : base(options) { _productService = productService; _logger = logger; _cache = cache; IsFallbackUserDefined = true; } protected override async Task<Product> RunAsync() { return await _productService.GetProductAsync(_productId); } protected override async Task<Product> RunFallbackAsync() { _logger.LogInformation($"Running Get Product Fallback - Product ID {_productId} not found."); return await Task.FromResult(new Product()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SceneLoader : SingletonMonoBehaviour<SceneLoader>{ // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void LoadCardMenuScene(){ BackgroundManager.Instance.setFadeOutFinishedListener( new FadeOutFinishedListener() ); BackgroundManager.Instance.fadeOut (); } class FadeOutFinishedListener : BackgroundManager.FadeOutFinishedListener{ public void fadeOutFinished (){ SceneManager.LoadScene ("CardMenu"); } } }
namespace Web_banh_ngot.Models.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("BILL")] public partial class BILL { [Key] public int ID_BILL { get; set; } public int? ID_CUS { get; set; } [Column(TypeName = "date")] public DateTime? DATE_ORDER { get; set; } [StringLength(100)] public string PAYMENT { get; set; } [StringLength(255)] public string NOTE_BILL { get; set; } [StringLength(100)] public string STATUS_BILL { get; set; } public virtual CUSTOMER CUSTOMER { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Microsoft.Azure.Batch.SoftwareEntitlement.Common; namespace Microsoft.Azure.Batch.SoftwareEntitlement { /// <summary> /// A factory object that tries to create a <see cref="ServerOptions"/> instance when given the /// <see cref="ServerCommandLine"/> specified by the user. /// </summary> public class ServerOptionBuilder { // Reference to the server command line we wrap private readonly ServerCommandLine _commandLine; // Reference to a store in which we can search for certificates private readonly CertificateStore _certificateStore = new CertificateStore(); // Options used to configure validation private readonly ServerOptionBuilderOptions _options; /// <summary> /// Build an instance of <see cref="ServerOptions"/> from the information supplied on the /// command line by the user /// </summary> /// <param name="commandLine">Command line parameters supplied by the user.</param> /// <param name="options">Options for configuring validation.</param> /// <returns>Either a usable (and completely valid) <see cref="ServerOptions"/> or a set /// of errors.</returns> public static Errorable<ServerOptions> Build( ServerCommandLine commandLine, ServerOptionBuilderOptions options = ServerOptionBuilderOptions.None) { var builder = new ServerOptionBuilder(commandLine, options); return builder.Build(); } /// <summary> /// Initializes a new instance of the <see cref="ServerOptionBuilder"/> class /// </summary> /// <param name="commandLine">Options provided on the command line.</param> /// <param name="options">Options for configuring validation.</param> private ServerOptionBuilder( ServerCommandLine commandLine, ServerOptionBuilderOptions options) { _commandLine = commandLine; _options = options; } /// <summary> /// Build an instance of <see cref="ServerOptions"/> from the information supplied on the /// command line by the user /// </summary> /// <returns>Either a usable (and completely valid) <see cref="ServerOptions"/> or a set /// of errors.</returns> private Errorable<ServerOptions> Build() { var options = new ServerOptions(); var errors = new List<string>(); void Configure<V>(Func<Errorable<V>> readConfiguration, Func<V, ServerOptions> applyConfiguration) { readConfiguration().Match( whenSuccessful: value => options = applyConfiguration(value), whenFailure: e => errors.AddRange(e)); } void ConfigureOptional<V>(Func<Errorable<V>> readConfiguration, Func<V, ServerOptions> applyConfiguration) where V : class { readConfiguration().Match( whenSuccessful: value => { if (value != null) { options = applyConfiguration(value); } }, whenFailure: e => errors.AddRange(e)); } void ConfigureSwitch(Func<bool> readConfiguration, Func<ServerOptions> applySwitch) { if (readConfiguration()) { options = applySwitch(); } } Configure(ServerUrl, url => options.WithServerUrl(url)); ConfigureOptional(ConnectionCertificate, cert => options.WithConnectionCertificate(cert)); ConfigureOptional(SigningCertificate, cert => options.WithSigningCertificate(cert)); ConfigureOptional(EncryptingCertificate, cert => options.WithEncryptionCertificate(cert)); ConfigureOptional(Audience, audience => options.WithAudience(audience)); ConfigureOptional(Issuer, issuer => options.WithIssuer(issuer)); ConfigureSwitch(ExitAfterRequest, () => options.WithAutomaticExitAfterOneRequest()); if (errors.Any()) { return Errorable.Failure<ServerOptions>(errors); } return Errorable.Success(options); } /// <summary> /// Find the server URL for our hosting /// </summary> /// <returns>An <see cref="Errorable{Uri}"/> containing either the URL to use or any /// relevant errors.</returns> private Errorable<Uri> ServerUrl() { if (string.IsNullOrWhiteSpace(_commandLine.ServerUrl)) { if (_options.HasFlag(ServerOptionBuilderOptions.ServerUrlOptional)) { return Errorable.Success(new Uri("http://test")); } return Errorable.Failure<Uri>("No server endpoint URL specified."); } try { var result = new Uri(_commandLine.ServerUrl); if (!result.HasScheme("https")) { return Errorable.Failure<Uri>("Server endpoint URL must specify https://"); } return Errorable.Success(result); } catch (Exception e) { return Errorable.Failure<Uri>($"Invalid server endpoint URL specified ({e.Message})"); } } /// <summary> /// Find the certificate to use for HTTPS connections /// </summary> /// <returns>Certificate, if found; error details otherwise.</returns> private Errorable<X509Certificate2> ConnectionCertificate() { if (string.IsNullOrEmpty(_commandLine.ConnectionCertificateThumbprint)) { if (_options.HasFlag(ServerOptionBuilderOptions.ConnectionThumbprintOptional)) { return Errorable.Success<X509Certificate2>(null); } return Errorable.Failure<X509Certificate2>("A connection thumbprint is required."); } return FindCertificate("connection", _commandLine.ConnectionCertificateThumbprint); } /// <summary> /// Find the certificate to use for signing tokens /// </summary> /// <returns>Certificate, if found; error details otherwise.</returns> private Errorable<X509Certificate2> SigningCertificate() { if (string.IsNullOrEmpty(_commandLine.SigningCertificateThumbprint)) { // No certificate requested, no need to look for one return Errorable.Success<X509Certificate2>(null); } return FindCertificate("signing", _commandLine.SigningCertificateThumbprint); } /// <summary> /// Find the certificate to use for encrypting tokens /// </summary> /// <returns>Certificate, if found; error details otherwise.</returns> private Errorable<X509Certificate2> EncryptingCertificate() { if (string.IsNullOrEmpty(_commandLine.EncryptionCertificateThumbprint)) { // No certificate requested, no need to look for one return Errorable.Success<X509Certificate2>(null); } return FindCertificate("encrypting", _commandLine.EncryptionCertificateThumbprint); } /// <summary> /// Return the audience required /// </summary> /// <returns>Audience from the commandline, if provided; default value otherwise.</returns> private Errorable<string> Audience() { if (string.IsNullOrEmpty(_commandLine.Audience)) { return Errorable.Success(Claims.DefaultAudience); } return Errorable.Success(_commandLine.Audience); } /// <summary> /// Return the issuer required /// </summary> /// <returns>Issuer from the commandline, if provided; default value otherwise.</returns> private Errorable<string> Issuer() { if (string.IsNullOrEmpty(_commandLine.Issuer)) { return Errorable.Success(Claims.DefaultIssuer); } return Errorable.Success(_commandLine.Issuer); } /// <summary> /// Return whether the server should shut down after processing one request /// </summary> /// <returns></returns> private bool ExitAfterRequest() { return _commandLine.ExitAfterRequest; } /// <summary> /// Find a certificate for a specified purpose, given a thumbprint /// </summary> /// <param name="purpose">A use for which the certificate is needed (for human consumption).</param> /// <param name="thumbprint">Thumbprint of the required certificate.</param> /// <returns>The certificate, if found; an error message otherwise.</returns> private Errorable<X509Certificate2> FindCertificate(string purpose, string thumbprint) { if (string.IsNullOrWhiteSpace(thumbprint)) { return Errorable.Failure<X509Certificate2>($"No thumbprint supplied; unable to find a {purpose} certificate."); } var certificateThumbprint = new CertificateThumbprint(thumbprint); return _certificateStore.FindByThumbprint(purpose, certificateThumbprint); } } [Flags] public enum ServerOptionBuilderOptions { None, ServerUrlOptional, ConnectionThumbprintOptional } }
using University.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace University.Repository.Interface { public interface IProductUserGuideRepository { List<ProductUserGuide> GetProductUserGuideList(); List<ProductUserGuide> GetSearchUserGuides(string SearchTxt); IEnumerable<ProductUserGuide> GetUserGuideList(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FizzBuzz { class Program { static void Main(string[] args) { for (int i = 0; i <= 100; i++) { if (i%3 == 0 && i%5 == 0) { Console.Write(",Fizz Buzz"); } else if (i % 3 == 0) { Console.Write(",Fizz"); } else if (i % 5 == 0) { Console.Write(",Buzz"); } else { Console.Write("," + i); } } Console.ReadLine(); } } }
namespace CheckIt.Tests.CheckReferences { using CheckIt.Tests.CheckAssembly; using Xunit; public class CheckProjectReferenceAssemblyTests { public CheckProjectReferenceAssemblyTests() { AssemblySetup.Initialize(); } [Fact] public void Should_project_reference_When_check_code() { Check.Project("CheckIt.csproj").Contains().Any().Reference("System"); } [Fact] public void Should_throw_error_When_project_not_contains_reference() { var e = Assert.Throws<MatchException>( () => Check.Project("CheckIt.csproj").Contains().Any().Reference("NotFoundReference")); Assert.Equal("No reference found that match pattern 'NotFoundReference'.", e.Message); } [Fact] public void Should_throw_error_When_project_contains_reference() { var e = Assert.Throws<MatchException>( () => Check.Project("CheckIt.csproj").Contains().No().Reference("System")); Assert.Equal("Reference found that match pattern 'System'.", e.Message); } } }
namespace SpaceHosting.Index { public interface IVector { int Dimension { get; } } }
using System; using System.Linq; using kata_payslip_v2.DataObjects; namespace kata_payslip_v2 { public static class ArgumentParser { public static Arguments ParseArguments(string[] argumentStrings) { PayslipInputType inputType; PayslipOutputType outputType; string outputFilePath = null; string inputFilePath = null; if (argumentStrings.Length == 0) { return new Arguments(PayslipInputType.ConsoleInput, PayslipOutputType.ConsoleOutput, null, null); } inputType = argumentStrings.Contains("csvInput") ? PayslipInputType.CsvFileInput : PayslipInputType.ConsoleInput; outputType = argumentStrings.Contains("csvOutput") ? PayslipOutputType.CsvFileOutput : PayslipOutputType.ConsoleOutput; if (outputType == PayslipOutputType.CsvFileOutput) { outputFilePath = argumentStrings[^1]; if (inputType == PayslipInputType.CsvFileInput) { inputFilePath = argumentStrings[^2]; } } else { if (inputType == PayslipInputType.CsvFileInput) { inputFilePath = argumentStrings[^1]; } } return new Arguments(inputType, outputType, inputFilePath, outputFilePath); } } }
using AutoMapper; using FamilyAccounting.BL.DTO; using FamilyAccounting.BL.Interfaces; using FamilyAccounting.Web.Interfaces; using FamilyAccounting.Web.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace FamilyAccounting.Web.Services { public class TransactionWebService : ITransactionWebService { private readonly ITransactionService transactionService; private readonly IMapper mapper; public TransactionWebService(IMapper mapper, ITransactionService transactionService) { this.transactionService = transactionService; this.mapper = mapper; } public async Task<TransactionViewModel> Get(int walletId, int transactionId) { try { TransactionDTO transaction = await transactionService.GetAsync(walletId, transactionId); return mapper.Map<TransactionViewModel>(transaction); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<IEnumerable<CategoryViewModel>> GetExpenseCategories() { IEnumerable<CategoryDTO> categories = await transactionService.GetExpenseCategoriesAsync(); return mapper.Map<IEnumerable<CategoryViewModel>>(categories); } public async Task<IEnumerable<CategoryViewModel>> GetIncomeCategories() { IEnumerable<CategoryDTO> categories = await transactionService.GetIncomeCategoriesAsync(); return mapper.Map<IEnumerable<CategoryViewModel>>(categories); } public async Task<TransactionViewModel> MakeExpense(TransactionViewModel transaction) { try { TransactionDTO _transaction = await transactionService.MakeExpenseAsync(mapper.Map<TransactionDTO>(transaction)); return mapper.Map<TransactionViewModel>(_transaction); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TransactionViewModel> MakeIncome(TransactionViewModel transaction) { try { TransactionDTO _transaction = await transactionService.MakeIncomeAsync(mapper.Map<TransactionDTO>(transaction)); return mapper.Map<TransactionViewModel>(_transaction); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TransactionViewModel> MakeTransfer(TransactionViewModel transaction) { try { TransactionDTO _transaction = await transactionService.MakeTransferAsync(mapper.Map<TransactionDTO>(transaction)); return mapper.Map<TransactionViewModel>(_transaction); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TransactionViewModel> SetInitialBalance(TransactionViewModel transaction) { try { TransactionDTO _transaction =await transactionService.SetInitialBalanceAsync(mapper.Map<TransactionDTO>(transaction)); return mapper.Map<TransactionViewModel>(_transaction); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TransactionViewModel> Update(int id, TransactionViewModel transaction) { try { TransactionDTO newTransaction = mapper.Map<TransactionDTO>(transaction); TransactionDTO updatedTransaction = await transactionService.UpdateAsync(id, newTransaction); return mapper.Map<TransactionViewModel>(updatedTransaction); } catch (Exception ex) { throw new Exception(ex.Message); } } } }
namespace GraphicalEditorServer.DTO { public class EquipmentInExaminationDTO { public int EquipmentID { get; set; } public int ExaminationId { get; set; } public EquipmentInExaminationDTO() { } public EquipmentInExaminationDTO(int equipmentID, int examinationId) { this.EquipmentID = equipmentID; this.ExaminationId = examinationId; } } }
using System.Reflection; namespace AutoTests.Framework.Core.Exceptions { public class PropertyConstraintException : ConstraintException { public PropertyConstraintException(PropertyInfo propertyInfo, string format) : base(string.Format(format, $"{propertyInfo.DeclaringType.Name}.{propertyInfo.Name}")) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EntityContainer : MonoBehaviour { [SerializeField] Animator animator; public Animator Animator { get { return animator; } } [SerializeField] new SkinnedMeshRenderer renderer; public SkinnedMeshRenderer Renderer { get { return renderer; } } // [SerializeField] Material[] materials; // public Material[] Materials { get { return materials; } } [SerializeField] ParticleSystem stun; public ParticleSystem Stun { get { return stun; } } [SerializeField] ParticleSystem mslow; public ParticleSystem MSlow { get { return mslow; } } [SerializeField] ParticleSystem cslow; public ParticleSystem CSlow { get { return cslow; } } [SerializeField] ParticleSystem chaste; public ParticleSystem CHaste { get { return chaste; } } [SerializeField] ParticleSystem mhaste; public ParticleSystem MHaste { get { return mhaste; } } [SerializeField] ParticleSystem silence; public ParticleSystem Silence { get { return silence; } } [SerializeField] ParticleSystem nani; public ParticleSystem Nani { get { return nani; } } [SerializeField] ParticleSystem dot; public ParticleSystem DOT { get { return dot; } } [SerializeField] ParticleSystem root; public ParticleSystem Root { get { return root; } } [SerializeField] ParticleSystem heal; public ParticleSystem Heal { get { return heal; } } }
using System; namespace Lab4.Ind._2 { class Program { static void Main(string[] args) { string text = Console.ReadLine(); Console.WriteLine("The first way"); char[] textchar = text.ToCharArray(); int k = 0; char[] letters = "ABCDEFGHIJKLMNOPRSTVUQWXYZ".ToCharArray(); for (int i = 0; i < textchar.Length; i++) { if (textchar[i] == ' ' || textchar[i] == ',' || textchar[i] == '.') { if (i - k - 1 < 6) { for (int l = 0; l < letters.Length; l++) { if (k == 0 && textchar[0] == letters[l]) { textchar[0] = '_'; } else if (textchar[k + 1] == letters[l]) { textchar[k + 1] = '_'; } } } k = i; } } for (int j = 0; j < textchar.Length; j++) { Console.Write(textchar[j]); } Console.WriteLine(); Console.WriteLine("The second way"); string[] word = text.Split(' '); string resultText = ""; for (int i = 0; i < word.Length; i++) { char[] wordchar = word[i].ToCharArray(); if (wordchar.Length < 6&& char.IsUpper(wordchar[0])) { wordchar[0] = '_'; } word[i] = string.Join("", wordchar); resultText = resultText+ word[i]+" "; } Console.WriteLine(resultText); } } }
using HouseRent.Data; using HouseRent.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HouseRent.Areas.Admin.Controllers { [Authorize(Roles = "Admin")] [Area("Admin")] public class UserController : Controller { UserManager<IdentityUser>_userManager; ApplicationDbContext _db; public UserController(UserManager<IdentityUser> userManager, ApplicationDbContext db) { _userManager = userManager; _db = db; } public IActionResult Index() { return View(); } public ActionResult GetAll() { List<ApplicationUser> applicationUsers = _db.ApplicationUsers.ToList<ApplicationUser>(); return Json(new { data = applicationUsers }); } [AllowAnonymous] public IActionResult Create() { return View(); } [AllowAnonymous] public async Task<ActionResult> Edit(string id) { var user = await _db.ApplicationUsers.FindAsync(id); return View(user); } [AllowAnonymous] [HttpPost] public async Task<IActionResult> Create(ApplicationUser applicationUser) { if (ModelState.IsValid) { var result = await _userManager.CreateAsync(applicationUser,applicationUser.PasswordHash); if (result.Succeeded) { var roleSave = await _userManager.AddToRoleAsync(applicationUser, "Customer"); TempData["save"] = "User has been created Successfully"; return RedirectToPage("/Account/Login", new { area = "Identity" }); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return View(); } [AllowAnonymous] [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit(ApplicationUser user) { if (ModelState.IsValid) { var userInfo = _db.ApplicationUsers.FirstOrDefault(x => x.Id == user.Id); userInfo.FirstName = user.FirstName; userInfo.LastName = user.LastName; userInfo.UserName = user.UserName; var result = await _userManager.UpdateAsync(userInfo); if (result.Succeeded) { TempData["edit"] = "User has been Updated"; return RedirectToAction(nameof(Index)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return View(); } [HttpPost] public ActionResult Delete(string id) { var user = _db.ApplicationUsers.Where(x => x.Id == id).FirstOrDefault<ApplicationUser>(); _db.Remove(user); _db.SaveChanges(); return Json(new { success = true, message = "Deleted Successfully" }); } } }
using CarritoCompras.Modelo; using CarritoCompras.Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CarritoCompras.View { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PageDetalleProducto : ContentPage { public string nombreGlobalCategoria; public Producto oGlobalProducto; public PageDetalleProducto (Producto oProducto,string nombreCategoria) { InitializeComponent (); nombreGlobalCategoria = nombreCategoria; oGlobalProducto = oProducto; ImagenProducto.Source = oProducto.imagen; txtNombre.Text = oProducto.nombre; txtDescripcion.Text = oProducto.descripcion; txtDetalle.Text = oProducto.detalle; txtPrecio.Text = string.Format("S/.{0}", oProducto.precio.ToString()); } private void TapMenos_Tapped(object sender, EventArgs e) { int cantidad = Convert.ToInt32(lblCantidad.Text); if (cantidad > 1) { cantidad -= 1; } lblCantidad.Text = cantidad.ToString(); } private void TapMas_Tapped(object sender, EventArgs e) { int cantidad = Convert.ToInt32(lblCantidad.Text); cantidad += 1; lblCantidad.Text = cantidad.ToString(); } private async void BtnAgregarBolsa_Clicked(object sender, EventArgs e) { bool encontrado = await validarProductoEnBolsa(); if (encontrado) { await DisplayAlert("Mensaje", "El producto ya se encuentra en la bolsa", "Ok"); return; } Bolsa oBolsa = new Bolsa() { cantidad = Convert.ToInt32(lblCantidad.Text), categoria = nombreGlobalCategoria, producto = oGlobalProducto }; bool resultado = await ApiServiceFirebase.AgregarenBolsa(oBolsa); if (resultado) { var DisplayResultado = await DisplayAlert("Mensaje", "Producto agregado a la bolsa", "Ir a la bolsa", "Seguir comprando"); if (DisplayResultado) { var st = nameof(PageBolsa); var ttt = nameof(PageBolsa).ToString(); Routing.RegisterRoute(nameof(PageBolsa), typeof(PageBolsa)); await Shell.Current.GoToAsync(nameof(PageBolsa)); //await Shell.Current.Navigation.PushAsync(new PageBolsa()); } } else { await DisplayAlert("Mensaje", "No se pudo agregar a la bolsa","Ok"); } } private async Task<bool> validarProductoEnBolsa() { bool encontrado = false; Dictionary<string, Bolsa> oObjecto = await ApiServiceFirebase.ObtenerBolsa(); if (oObjecto !=null) { foreach (KeyValuePair<string, Bolsa> item in oObjecto) { if (item.Value.producto.idproducto == oGlobalProducto.idproducto) { encontrado = true; break; } } } return encontrado; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Filters { class Glass: Filters { protected override Color сonvertPixel(Bitmap sourceMap, int x, int y) { Random rand = new Random(); int positionX = (int)(x + (rand.Next(1) - 0.5f) * 10); int positionY = (int)(y + (rand.Next(1) - 0.5f) * 10); //positionX = clamp(positionX, 0, sourceMap.Width); //positionY = clamp(positionY, 0, sourceMap.Height); if (positionX < sourceMap.Width && positionX > 0 && positionY < sourceMap.Height && positionY > 0) { Color c = sourceMap.GetPixel(positionX, positionY); return c; } else { Color c = Color.FromArgb(255, 255, 255); return c; } throw new NotImplementedException(); } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Core.Enums.Enum { /// <summary> /// 卡券类型 /// </summary> [ClassProperty(Name = "卡券类型")] public enum CardCouponsType { /// <summary> /// 折扣券 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "折扣券")] Discount = 1, /// <summary> /// 兑换券 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "兑换券")] Exchange = 2, /// <summary> /// 优惠券 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "优惠券")] Preferential = 3, /// <summary> /// 代金券 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "代金券")] Kims = 4, /// <summary> /// 红包 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "红包")] RedPacket = 5, /// <summary> /// 免邮卡 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "免邮卡")] FreeShipping = 6 } }
using gView.Framework.Data; using gView.Framework.Data.Filters; using gView.Framework.IO; using gView.Framework.system; namespace gView.Framework.Carto { /// <summary> /// Porvide access to members and properties that control the functionality of renderers. /// </summary> public interface IFeatureRenderer : IRenderer, IPersistable, IClone, IClone2 { /// <summary> /// Draws features from the specified Featurecursor on the given display. /// </summary> /// <param name="disp"></param> /// <param name="fCursor"></param> /// <param name="drawPhase"></param> /// <param name="cancelTracker"></param> //void Draw(IDisplay disp,IFeatureCursor fCursor,DrawPhase drawPhase,ICancelTracker cancelTracker); void Draw(IDisplay disp, IFeature feature); void StartDrawing(IDisplay display); void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker); /// <summary> /// Prepares the query filter for the rendering process. /// </summary> /// <remarks> /// </remarks> /// This member is called by the framework befor querying the features. /// <param name="layer"></param> /// <param name="filter">The filter for querying the features</param> void PrepareQueryFilter(IFeatureLayer layer, IQueryFilter filter); /// <summary> /// Indicates if the specified feature class can be rendered on the given display. /// </summary> /// <param name="layer"></param> /// <param name="map"></param> /// <returns></returns> bool CanRender(IFeatureLayer layer, IMap map); bool HasEffect(IFeatureLayer layer, IMap map); bool UseReferenceScale { get; set; } /// <summary> /// The name of the renderer. /// </summary> string Name { get; } /// <summary> /// The category for the renderer. /// </summary> string Category { get; } bool RequireClone(); } }
using System; using System.Collections.Generic; using AbstractFactory.Classes.PizzaIngredientFactories.Ingredients; namespace AbstractFactory.Classes.Pizzas { public abstract class Pizza { public string Name { get; set; } protected IDough Dough { get; set; } protected ISause Sause { get; set; } protected List<string> Toppings = new List<string>(); public abstract void Prepare(); public void Bake() { Console.WriteLine("Bake for 25 minutes at 350"); } public void Cut() { Console.WriteLine("Cutting the pizza into diagonal slices"); } public void Box() { Console.WriteLine("Place pizza in official PizzaStore box"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UcenikShuffle.Common; namespace ManualTests { class Program { static void Main(string[] args) { var groupSizesList = new List<List<int>>() { new List<int>() { 1, 2, 2 }, new List<int>(){ 1,3,3,3,3 }, //new List<int>(){ 1,3,3,3,3 }, //new List<int>(){ 1,3,3,3,3 }, //new List<int>(){ 1,3,3,3,3,3,3,3,3 }, //new List<int>(){ 1,3,3,3,3,3,3,3,3 }, new List<int>(){ 2,2,2,2,2,2,2,2,2,2,2,2,2 } }; var combinationCountList = new List<int>() { 10, 1, //14, //100, //1, //100, 1 }; var watch = new Stopwatch(); for (int i = 0; i < groupSizesList.Count; i++) { var groupSizes = groupSizesList[i]; var students = new List<Student>(); for (int j = 1; j <= groupSizes.Sum(); j++) { students.Add(new Student(j)); } Console.WriteLine($"Combination count: {new LvCombinationCountCalculator(groupSizes, students.Count).GetLvCombinationCount()}"); watch.Restart(); var shuffler = new Shuffler(combinationCountList[i], groupSizes, null); shuffler.Shuffle(); watch.Stop(); foreach (var combination in shuffler.ShuffleResult) { foreach (var group in combination.Combination) { foreach (var student in group) { Console.Write($"{student.Id},"); } Console.Write("\t\t"); } Console.WriteLine(); } Console.WriteLine(); if (args.Select(a => a.ToLowerInvariant()).Contains("y")) { foreach (var student in students) { Console.WriteLine(student.Label); foreach (var student2 in students.Except(new List<Student>() { student })) { Console.WriteLine($"{student2.Label} \t {shuffler.ShuffleResult.Where(r => r.Combination.Any(g => g.Any(s => s.Id == student.Id) && g.Any(s => s.Id == student2.Id))).Count()}"); } Console.WriteLine(); } } Console.WriteLine($"ELAPSED SECONDS: {watch.ElapsedMilliseconds / (double)1000}\n\n\n"); } } } }
using iSukces.Code.AutoCode; using Sample.AppWithCSharpCodeEmbedding.AutoCode; namespace Sample.AppWithCSharpCodeEmbedding { class Program { static void Main(string[] args) { CreateAutoCode(); } private static void CreateAutoCode() { var prov2 = SlnAssemblyBaseDirectoryProvider.Make<DemoAutoCodeGenerator>("isukces.code.sln", "samples"); IAssemblyFilenameProvider provider = new SimpleAssemblyFilenameProvider(prov2, "--Autocode--.cs"); var gen = new DemoAutoCodeGenerator(provider); gen.WithGenerator(new Generators.EqualityGenerator(new JetbrainsAttributeNullValueChecker())); gen.TypeBasedOutputProvider = new CodeFilePathContextProvider(); gen.Make<DemoAutoCodeGenerator>(); } } }
using RabbitMQ.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rabbit.Sender { class Program { // echagne is the RabbitMQ name for the topic. This is in lieu of a standard queue private static string exchangeName = "someExchange"; static void Main(string[] args) { // create the conneciton factory var factory = new ConnectionFactory() { HostName = "localhost" }; // usign disposable scopes for the channel and the model using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { // we are creating the exchange // the options for an exchage are: // fanout (pub/sub without filters), direct (allows subsciption with a binding key), topic (allows subscription with routing keys) channel.ExchangeDeclare(exchangeName, "topic"); // this option prevent the blind round robin (just based on number of messages) but instead turns on dispatiching to a new listener in case of competing listeners. channel.BasicQos(0, 1, false); // and at thsi point we will declare the queue // in the other exercises the queue has no name. // as the consumer can retrieve the queue name and, frankly, it is not interested in the queue name as it can subscribe via the end point + routing keys // nonetheless here we are declaring a queue name in case this is needed var properties = channel.CreateBasicProperties(); properties.SetPersistent(true); // get the routing key (dot format) var routingKey = (args.Length > 0) ? args[0] : "anonymous.info"; var msg = (args.Length > 1) ? string.Join("", args.Skip(1).ToArray()) : "Message"; var body = Encoding.UTF8.GetBytes(msg); // basically the routing key is used to create the queue as the name channel.BasicPublish(exchangeName, routingKey, properties, body); Console.WriteLine("sent message {0} : {1}", msg, routingKey); } } // create queue/ exchange // delete exchange nif already existing // demand acknowledgements // make queue durable // send messasges with binding keys } private static string GetMessage(string[] args) { // the API for the routing keys is to send messages associated with channels. // e.g. rabbit.sender some.channel.here // the subscirber can hook to #.here or to some.*.here // allowing extra flexibility and reduced coupling // With binding keys we instead need to know exacltly what we are subscribing to. return ((args.Length > 0) ? string.Join(" ", args) : "This works!!"); } } }
using LeadChina.CCDMonitor.Infrastrue.Entity; using ServiceStack.OrmLite; using ServiceStack.Text; namespace LeadChina.CCDMonitor.Infrastrue { public class Test { public static void tst() { var dbFactory = new OrmLiteConnectionFactory("server = localhost;port=3306;User Id = root;password = root;Database = lgccd", MySqlDialect.Provider); using (var db = dbFactory.Open()) { var roles = db.Select<WorkshopEntity>(); "Roles: {0}".Print(roles.Dump()); } } } }
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin.Security.OAuth; using RestLogger.Infrastructure.Service; using RestLogger.Infrastructure.Service.Model.ApplicationDtos; namespace RestLogger.WebApi.Providers { public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { private readonly IApplicationService _applicationService; public SimpleAuthorizationServerProvider(IApplicationService applicationService) { _applicationService = applicationService; } public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); ApplicationDto applicationDto = await _applicationService.FindApplicationAsync(context.UserName, context.Password); if (applicationDto == null) { context.SetError("invalid_grant", "Application Id or Secret is incorrect."); return; } ClaimsIdentity identity = new ClaimsIdentity(new User() { AuthenticationType = context.Options.AuthenticationType, IsAuthenticated = true, Name = context.UserName }); context.Validated(identity); } } }
using System.Collections.Generic; namespace ProjectCompany.Models.DTO { public class EmployeeDetailDTO { public int Id { get; set; } public string Name { get; set; } public List<Skill> Skills { get; set; } public List<Contribution> Contributions { get; set; } public EmployeeDetailDTO(){} } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BanSupport { public class ExBase : MonoBehaviour { #region Update [NonSerialized] public bool needUpdate; /// <summary> /// for manager call /// </summary> public bool DoUpdate() { this.needUpdate = false; ForeachAllWidgets(aWidget => aWidget.Update()); return this.needUpdate; } /// <summary> /// for widgets call /// </summary> public void StartUpdate() { UIExtensionManager.Add(this); } /// <summary> /// for widgets call /// </summary> public void StopUpdate() { UIExtensionManager.Remove(this); } #endregion #region Widget private Dictionary<Type, List<Widget>> widgetDic = new Dictionary<Type, List<Widget>>(); /// <summary> /// 增加一个小功能 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="widget"></param> /// <param name="unique">保持这种类型小功能只有这一个实体</param> protected void AddWidget<T>(T widget, bool unique = false) where T : Widget { if (widget == null) { return; } var type = typeof(T); if (!widgetDic.ContainsKey(type)) { widgetDic.Add(type, ListPool<Widget>.Get()); } var widgets = widgetDic[type]; if (unique) { if (widgets.Count > 0) { widgets.ForEach(aWidget => aWidget.Dispose()); widgets.Clear(); } widgets.Add(widget); } else { if (!widgets.Contains(widget)) { widgets.Add(widget); } } } public bool RemoveWidget<T>() where T : Widget { var type = typeof(T); if (!widgetDic.ContainsKey(type)) { return false; } var widgets = widgetDic[type]; widgets.ForEach(aWidget => aWidget.Dispose()); ListPool<Widget>.Release(widgets); widgetDic.Remove(type); return true; } public bool RemoveWidget(Widget widget) { if (widget == null) { return false; } var type = widget.GetType(); if (!widgetDic.ContainsKey(type)) { return false; } var widgets = widgetDic[type]; if (widgets.Contains(widget)) { widgets.Remove(widget); widget.Dispose(); if (widgets.Count <= 0) { ListPool<Widget>.Release(widgets); widgetDic.Remove(type); } return true; } else { return false; } } public void ForeachWidgets<T>(Action<T> action) where T : Widget { var type = typeof(T); if (!widgetDic.ContainsKey(type)) { return; } var widgets = widgetDic[type]; foreach (var aWidget in widgets) { action((T)aWidget); } } private void ForeachAllWidgets(Action<Widget> action) { foreach (var type in widgetDic.Keys) { foreach (var widget in widgetDic[type]) { action(widget); } } } public string GetWidgetState() { var list = ListPool<string>.Get(); foreach (var type in widgetDic.Keys) { foreach (var widget in widgetDic[type]) { list.Add(widget.ToString()); } } var resultStr = string.Join("\n", list); ListPool<string>.Release(list); return resultStr; } #endregion #region Event private Dictionary<string, List<IActionTrigger>> eventDic = new Dictionary<string, List<IActionTrigger>>(); public void RegistEvent(string eventName, IActionTrigger actionTrigger) { if (!eventDic.ContainsKey(eventName)) { eventDic.Add(eventName, ListPool<IActionTrigger>.Get()); } var triggerList = eventDic[eventName]; if (!triggerList.Contains(actionTrigger)) { triggerList.Add(actionTrigger); } } public void UnRegistEvent(IActionTrigger actionTrigger) { bool deleteKey = false; string deleteKeyName = ""; foreach (var eventName in eventDic.Keys) { var triggerList = eventDic[eventName]; if (triggerList.Contains(actionTrigger)) { triggerList.Remove(actionTrigger); if (triggerList.Count <= 0) { ListPool<IActionTrigger>.Release(triggerList); deleteKey = true; deleteKeyName = eventName; } break; } } if (deleteKey) { eventDic.Remove(deleteKeyName); } } public void SendEvent(string eventName) { if (!eventDic.ContainsKey(eventName)) { return; } var triggerList = eventDic[eventName]; foreach (var aTrigger in triggerList) { aTrigger.OnAction(); } } public void SendEvent<T>(string eventName, T t) { if (!eventDic.ContainsKey(eventName)) { return; } var triggerList = eventDic[eventName]; foreach (var aTrigger in triggerList) { aTrigger.OnAction(t); } } public void SendEvent<T1, T2>(string eventName, T1 t1, T2 t2) { if (!eventDic.ContainsKey(eventName)) { return; } var triggerList = eventDic[eventName]; foreach (var aTrigger in triggerList) { aTrigger.OnAction(t1, t2); } } #endregion #region Unity private void Awake() { UIExtensionManager.Init(); } private void OnEnable() { ForeachAllWidgets(aWidget => aWidget.OnEnable()); StartUpdate(); } private void OnDisable() { ForeachAllWidgets(aWidget => aWidget.OnDisable()); StopUpdate(); } private void OnDestroy() { foreach (var type in widgetDic.Keys) { var widgets = widgetDic[type]; foreach (var aWidget in widgets) { aWidget.Dispose(); } ListPool<Widget>.Release(widgets); } this.widgetDic.Clear(); this.widgetDic = null; } #endregion } }
using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; // Component that takes all rigidbodies in its children, makes them non-kinematic, // and sends them flying with explosive force. public class ExplodeChildrenScript : ExplodeComponent, IObserver<Transform> { List<Rigidbody> childRBs = new List<Rigidbody>(); List<(Vector3, Quaternion)> rbInitTransforms = new List<(Vector3, Quaternion)>(); [Tooltip("How far around the explosion center the children will be affected by the explosion force")] public float ExplosionRadius = 1f; [Tooltip("How strong the explosion is")] public float ExplosionForce = 1f; [Tooltip("How much the explosion force should be adjusted upwards, regardless of position relative to explosion center")] public float ExplosionUpForce = 1f; // IDEA: forward force? push children in direction of (with) collision? [Tooltip("Optional explosion center object, will use the center of this object if left empty")] public Transform ExplosionCenter; [Tooltip("If the explosion should be triggered by collision with a collider on this object")] public bool OnCollision = false; [Tooltip("If the explosion should be triggered by trigger collision with a collider on this object")] public bool OnTrigger = false; public MoveToRaycastNormalScript OptionalMoveToRaycast; private void SetInitTransforms() { rbInitTransforms.Clear(); foreach (var item in childRBs.Select(rb => (rb.transform.position, rb.transform.rotation))) rbInitTransforms.Add(item); } private void Awake() { GetComponentsInChildren<Rigidbody>(false, childRBs); SetInitTransforms(); if (!ExplosionCenter) ExplosionCenter = transform; OptionalMoveToRaycast?.Observers.Add(this); } private void OnTriggerEnter(Collider other) { if (OnTrigger) Explode(); } private void OnCollisionEnter(Collision other) { if (OnCollision) Explode(); } public override void Explode() { foreach (var item in childRBs) { item.isKinematic = false; item.AddExplosionForce( ExplosionForce, ExplosionCenter.position, ExplosionRadius, ExplosionUpForce ); } } public override void UndoExplode() { foreach ((Rigidbody rb, (Vector3 rbInitPos, Quaternion rbInitRot)) in childRBs.Zip(rbInitTransforms, (rb, rbInitTransform) => (rb, rbInitTransform))) { rb.isKinematic = true; rb.position = rbInitPos; rb.rotation = rbInitRot; } } public void Notify(Transform t){ SetInitTransforms(); } }
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public IList<IList<int>> PathSum(TreeNode root, int targetSum) { var res = new List<IList<int>>(); if (root == null) return res; DFSHelper(root, targetSum, new List<int>(), res); return res; } private void DFSHelper(TreeNode root, int targetSum, IList<int> currRes, IList<IList<int>> res) { currRes.Add(root.val); if (root.left == null && root.right == null) { if (root.val == targetSum) { res.Add(new List<int>(currRes)); } currRes.RemoveAt(currRes.Count - 1); return; } if (root.left != null) DFSHelper(root.left, targetSum - root.val, currRes, res); if (root.right != null) DFSHelper(root.right, targetSum - root.val, currRes, res); currRes.RemoveAt(currRes.Count - 1); } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using SAPAPI.Models; using System.Linq; using System.Text; using System.Web.Mvc; using SupplyChain.Models; using System; using System.Collections.Generic; using Autofac.Integration.WebApi; using System.Data.Entity; namespace SAPAPI.Controllers { [AutofacControllerConfiguration] [Route("api/[controller]")] public class ItemsController : BaseController { SAPAPIContext context; public ItemsController(SAPAPIContext ctx) { context = ctx; } public override JsonResult Get() { throw new NotImplementedException(); } [HttpGet] public JsonResult GetForLookUp() { var items = context.Items.SqlQuery(string.Format("SELECT ItemCode,ItemName, CodeBars FROM OITM ")).ToList(); //var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; return Json(items, JsonRequestBehavior.AllowGet); } } }
namespace PaymentService.Application.Common.Models { using System; using System.IO; using System.Linq; using System.Collections.Generic; using PaymentService.Application.Common.Exceptions; public class BankStatementFile { public BankStatementFile(string path, DateTimeOffset importDate) { this.FilePath = path ?? throw new ArgumentNullException(nameof(path)); this.FileName = this.ConstructFileNameFromDate(importDate); } private string FilePath { get; } private string FileName { get; } private string FullPath => Path.Combine(FilePath, FileName); private string ProcessedFullPath => Path.Combine(FilePath, $"_processed_{FileName}"); private BankStatement ReadRow(string row) { string[] cells = row.Split(","); return new BankStatement(accountNumber: cells[3], amountAsString: cells[4], accountingDateAsIsoDateString: cells[2]); } private string ConstructFileNameFromDate(DateTimeOffset importDate) => $"bankStatements_{importDate.Year}_{importDate.Month}_{importDate.Day}.csv"; public bool Exists() => File.Exists(FullPath); public List<BankStatement> Read() { try { return File.ReadAllLines(FullPath).Skip(1).Select(ReadRow).ToList(); } catch (FileNotFoundException ex) { throw new BankStatementsFileNotFound(ex); } catch (IOException ex) { throw new BankStatementsFileReadingError(ex); } } public void MarkProcessed() => File.Copy(FullPath, ProcessedFullPath); } }
using System; using System.Collections; using System.Collections.Generic; using Assets.Scripts.Ui; using UnityEngine; using UnityEngine.Advertisements; using UnityEngine.Purchasing; namespace Assets.Scripts.UI.ShopNew { public class NewShopView : View { public List<NewShopCategoryButton> SelectButtons; public NewShopCategoryItem CategoryItemPrefab; public NewShopCategoryIapItem CategoryIapItemPrefab; public NewShopRewardItem OfferRewardItemPrefab; public GameObject CategoryItemsRoot; public GameObject CategoryItemsDescrObject; public GameObject CategoryOfferItemsDescrObject; public GameObject CategoryGoldItemsDescrObject; public UIGrid CategoryIapItemsGrid; public UIGrid CategoryItemsGrid; public UIGrid OfferRewardItemsGrid; public GameObject CloseButton; public GameObject BuyButton; public GameObject RestorePursahceButton; public GameObject Panel; public UILabel CurrentBalanceLabel; public UISprite CurrentOfferItemIcon; public UILabel CurrentOfferItemDescr; public UILabel CurrentItemPrice; public UILabel CurrentItemPriceDescr; public UISprite CurrentGoldItemIcon; public UILabel CurrentGoldItemDescr; public UILabel CurrentGoldItemAmount; public GameObject TimeObject; public UILabel TimeLabel; private List<NewShopCategoryItem> _categoryItems; private List<NewShopCategoryIapItem> _categoryOffersItems; private List<NewShopCategoryIapItem> _categoryGoldItems; private List<NewShopRewardItem> _currentOfferRewardItems; private NewShopCategoryIapItem _currentIapItem; private float _tickTime = 0.0f; private bool _initialized; public override void Init(GameManager gameManager) { base.Init(gameManager); foreach (var newShopCategoryButton in SelectButtons) newShopCategoryButton.Init(GameManager, OnCategorySelect); _categoryItems = new List<NewShopCategoryItem>(); _categoryOffersItems = new List<NewShopCategoryIapItem>(); _categoryGoldItems = new List<NewShopCategoryIapItem>(); _currentOfferRewardItems = new List<NewShopRewardItem>(); StartCoroutine(InitItems()); UpdateBalance(); CurrentItemPriceDescr.text = Localization.Get("buy"); UIEventListener.Get(CloseButton).onClick += go => Hide(); UIEventListener.Get(BuyButton).onClick += OnBuyClick; UIEventListener.Get(RestorePursahceButton).onClick += OnRestorePurshaceClick; CurrencyManager.OnChangeCurrency += UpdateBalance; GameManager.IapManager.OnBuyCurrency += CurrencyByued; #if UNITY_ANDROID RestorePursahceButton.SetActive(false); #endif } private void OnRestorePurshaceClick(GameObject go) { GameManager.IapManager.RestorePurchases(); } private IEnumerator InitItems() { int i = 0; while (!GameManager.IapManager.IsInitialized()) { yield return new WaitForSeconds(0.5f); i++; if(i > 30) yield break; } AddShopItems(); AddShopIapItems(); CategoryItemsGrid.Reposition(); CategoryIapItemsGrid.Reposition(); _initialized = true; } private void AddShopItems() { foreach (IapGoodItem item in GameManager.IapManager.GoodItems) { var shopItem = NGUITools.AddChild(CategoryItemsGrid.gameObject, CategoryItemPrefab.gameObject).GetComponent<NewShopCategoryItem>(); shopItem.Init(GameManager, item, this); shopItem.Show(); _categoryItems.Add(shopItem); } } private void AddShopIapItems() { AddIapItem(IapStoreManager.BUY_1000_DOLLARS_ID, false); AddIapItem(IapStoreManager.BUY_5000_DOLLARS_ID, false); if (GameManager.IapManager.IsBuyFirst30000) AddIapItem(IapStoreManager.BUY_30000_DOLLARS_ID, false); else AddIapItem(IapStoreManager.BUY_30000_DOLLARS_ID, false, IapStoreManager.BUY_30000_DOLLARS_FIRST_ID, true); AddIapItem(IapStoreManager.BUY_20000_DOLLARS_ID, false); AddIapItem(IapStoreManager.FREE_GOLD, false); AddIapItem(IapStoreManager.STARTER_PACK, true, null, false, 5); AddIapItem(IapStoreManager.WEAPON_PACK, true, null, false, 5); AddIapItem(IapStoreManager.FIGHTER_KIT, true); AddIapItem(IapStoreManager.BUILDER_KIT, true); AddIapItem(IapStoreManager.SURVIVAL_KIT, true); if(!GameManager.IapManager.IsBuyNoAds) AddIapItem(IapStoreManager.NO_ADS, true); } private void AddIapItem(string iapItem, bool isOffer, string firstIapItem = null, bool isFirst = false, int maxPerLineItems = 4) { var shopIapItem = NGUITools.AddChild(CategoryIapItemsGrid.gameObject, CategoryIapItemPrefab.gameObject).GetComponent<NewShopCategoryIapItem>(); shopIapItem.Init(GameManager, this, iapItem, isOffer, firstIapItem, isFirst, maxPerLineItems); if(isOffer) _categoryOffersItems.Add(shopIapItem); else _categoryGoldItems.Add(shopIapItem); } private void OnBuyClick(GameObject go) { if (_currentIapItem.ID == IapStoreManager.FREE_GOLD) { ShowRewardedAd(); } else { GameManager.IapManager.BuyProductId(_currentIapItem.IapItem.definition.id); } } public void ShowRewardedAd() { if (Advertisement.IsReady("rewardedVideo")) { var options = new ShowOptions { resultCallback = HandleShowResult }; Advertisement.Show("rewardedVideo", options); } } private void HandleShowResult(ShowResult result) { switch (result) { case ShowResult.Finished: CurrencyManager.AddCurrency(_currentIapItem.Definition.Currency); break; case ShowResult.Skipped: break; case ShowResult.Failed: break; } } public void SelectIapItem(NewShopCategoryIapItem item) { foreach (var newShopCategoryIapItem in _categoryOffersItems) { newShopCategoryIapItem.Select(newShopCategoryIapItem == item); } foreach (var newShopCategoryIapItem in _categoryGoldItems) { newShopCategoryIapItem.Select(newShopCategoryIapItem == item); } if (item.IsOffer) { CurrentOfferItemIcon.spriteName = item.Definition.IconName; CurrentOfferItemDescr.text = Localization.Get(item.Definition.DetailDescription); CurrentItemPrice.text = item.IapItem.metadata.localizedPriceString; foreach (var currentOfferRewardItem in _currentOfferRewardItems) Destroy(currentOfferRewardItem.gameObject); _currentOfferRewardItems.Clear(); if (item.Definition.Items != null) { OfferRewardItemsGrid.maxPerLine = item.MaxPerLineItems; foreach (var definitionItem in item.Definition.Items) { var rewardItem = NGUITools.AddChild(OfferRewardItemsGrid.gameObject, OfferRewardItemPrefab.gameObject).GetComponent<NewShopRewardItem>(); rewardItem.Init(definitionItem.Key, definitionItem.Value); _currentOfferRewardItems.Add(rewardItem); } if (item.Definition.Currency > 0) { var rewardItem = NGUITools.AddChild(OfferRewardItemsGrid.gameObject, OfferRewardItemPrefab.gameObject).GetComponent<NewShopRewardItem>(); rewardItem.Init("gold", item.Definition.Currency); _currentOfferRewardItems.Add(rewardItem); } OfferRewardItemsGrid.Reposition(); StartCoroutine(DelayMake(() => OfferRewardItemsGrid.Reposition(), 0.05f)); } TimeObject.SetActive(item.IapItem.definition.id == IapStoreManager.STARTER_PACK); } else { CurrentGoldItemIcon.spriteName = item.Definition.IconName; CurrentGoldItemDescr.text = Localization.Get(item.Definition.Description); if(item.ID == IapStoreManager.FREE_GOLD) CurrentItemPrice.text = Localization.Get("free"); else CurrentItemPrice.text = item.IapItem.metadata.localizedPriceString; CurrentGoldItemAmount.text = item.Definition.Currency.ToString(); } _currentIapItem = item; } private IEnumerator DelayMake(Action action, float delayTime) { yield return new WaitForSeconds(delayTime); action(); } public void Show(NewShopCategory category) { Panel.SetActive(true); IsShowing = true; SelectCategory(category); } private void OnCategorySelect(NewShopCategory newShopCategory) { SelectCategory(newShopCategory); } public void SelectCategory(NewShopCategory category) { foreach (var newShopCategoryButton in SelectButtons) { newShopCategoryButton.SetSelected(category == newShopCategoryButton.Category); } foreach (var shopItem in _categoryItems) { if (shopItem.CloneAnimateItem != null) { shopItem.StopAllCoroutines(); Destroy(shopItem.CloneAnimateItem); } } BuyButton.SetActive(category != NewShopCategory.Items); switch (category) { case NewShopCategory.Offers: CategoryOfferItemsDescrObject.SetActive(true); CategoryGoldItemsDescrObject.SetActive(false); CategoryItemsRoot.SetActive(true); CategoryItemsDescrObject.SetActive(false); foreach (var newShopCategoryIapItem in _categoryOffersItems) newShopCategoryIapItem.Show(); foreach (var newShopCategoryIapItem in _categoryGoldItems) newShopCategoryIapItem.Hide(); SelectIapItem(_categoryOffersItems[0]); break; case NewShopCategory.Gold: CategoryOfferItemsDescrObject.SetActive(false); CategoryGoldItemsDescrObject.SetActive(true); CategoryItemsRoot.SetActive(true); CategoryItemsDescrObject.SetActive(false); foreach (var newShopCategoryIapItem in _categoryOffersItems) newShopCategoryIapItem.Hide(); foreach (var newShopCategoryIapItem in _categoryGoldItems) newShopCategoryIapItem.Show(); SelectIapItem(_categoryGoldItems[0]); break; case NewShopCategory.Items: CategoryOfferItemsDescrObject.SetActive(false); CategoryGoldItemsDescrObject.SetActive(false); CategoryItemsRoot.SetActive(false); CategoryItemsDescrObject.SetActive(true); break; } CategoryIapItemsGrid.Reposition(); } private void CurrencyByued(string id) { if (!IsShowing) return; SoundManager.PlaySFX(WorldConsts.AudioConsts.Reward); StartCoroutine(AnimateAddCaps()); } private void UpdateBalance() { CurrentBalanceLabel.text = CurrencyManager.CurrentCurrency.ToString(); } public void NoManyAnimate() { StartCoroutine(AnimateAddCaps()); } private IEnumerator AnimateAddCaps() { TweenScale.Begin(CurrentBalanceLabel.gameObject, 0.5f, new Vector3(1.3f, 1.3f, 1.3f)); yield return new WaitForSeconds(0.6f); TweenScale.Begin(CurrentBalanceLabel.gameObject, 0.5f, new Vector3(1.0f, 1.0f, 1.0f)); yield break; } void Update() { if(!_initialized || _currentIapItem == null || !IsShowing) return; if (_currentIapItem.IapItem != null && _currentIapItem.IapItem.definition.id == IapStoreManager.STARTER_PACK) { _tickTime += Time.deltaTime; if (_tickTime >= 1.0f) { TimeLabel.text = GameManager.IapManager.GetStarterPackTime(); _tickTime = 0.0f; } } } public override void Hide() { Panel.SetActive(false); IsShowing = false; } void OnDestroy() { if(CurrencyManager.OnChangeCurrency != null) CurrencyManager.OnChangeCurrency -= UpdateBalance; if(GameManager.IapManager.OnBuyCurrency != null) GameManager.IapManager.OnBuyCurrency -= CurrencyByued; } } }
using CaveGeneration.Content_Generation.Map_Generation; using Microsoft.Xna.Framework; using static CaveGeneration.Content_Generation.Map_Generation.DrunkardWalk; namespace CaveGeneration.Content_Generation.Parameter_Settings { public class Settings { public string Seed { get; set; } public bool IncrementDifficulty { get; set; } public int IncrementChance { get; set; } public int EnemyCount { get; set; } public int StaticEnemyChance { get; set; } public bool EnemiesCanJump { get; set; } public int DistanceBetweenEnemies { get; set; } public bool GoalonGround { get; set; } public int IterationsOfsmoothmap { get; set; } public bool UseCopy { get; set; } public int NumberOfNeighborCells { get; set; } public MapGeneratorType MapGeneratorType { get; set; } public int NumberOfWalks { get; set; } public int NumberOfSteps { get; set; } public int DistanceBetweenWalks { get; set; } public Vector2 StartPositionForWalkers { get; set; } public int RandomFillPercent { get; set; } public int PlayerLives { get; set; } public Directions DrunkardDirections; public int NumberOfPitfalls { get; set; } public int PitfallWidth { get; set; } public int PitfallMaxHeight { get; set; } } }
using System; using System.Linq; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Filters; namespace Microsoft.UnifiedRedisPlatform.Service.API.Filters { public sealed class TrackingPropertiesFilterAttribute : ActionFilterAttribute { private readonly string _correlationIdHeaderKey; private readonly string _transactionIdHeaderKey; public TrackingPropertiesFilterAttribute(string correlationIdHeaderKey, string transactionIdHeaderKey) { _correlationIdHeaderKey = correlationIdHeaderKey; _transactionIdHeaderKey = transactionIdHeaderKey; } public override void OnActionExecuting(ActionExecutingContext context) { if (!context.HttpContext.Request.Headers.TryGetValue(_correlationIdHeaderKey, out _)) { context.HttpContext.Request.Headers.AddOrUpdate(_correlationIdHeaderKey, Guid.NewGuid().ToString()); } if (!context.HttpContext.Request.Headers.TryGetValue(_transactionIdHeaderKey, out _)) { context.HttpContext.Request.Headers.AddOrUpdate(_transactionIdHeaderKey, Guid.NewGuid().ToString()); } } public override void OnActionExecuted(ActionExecutedContext context) { var correlationId = Guid.NewGuid().ToString(); if (context.HttpContext.Request.Headers.TryGetValue(_correlationIdHeaderKey, out var headerValues)) { correlationId = headerValues.FirstOrDefault(); } if (!context.HttpContext.Response.Headers.TryGetValue(_correlationIdHeaderKey, out _)) { context.HttpContext.Response.Headers.AddOrUpdate(_correlationIdHeaderKey, correlationId); } var transactionId = Guid.NewGuid().ToString(); if (context.HttpContext.Request.Headers.TryGetValue(_transactionIdHeaderKey, out headerValues)) { transactionId = headerValues.FirstOrDefault(); } if (!context.HttpContext.Response.Headers.TryGetValue(_transactionIdHeaderKey, out _)) { context.HttpContext.Response.Headers.AddOrUpdate(_transactionIdHeaderKey, transactionId); } } } }
using AlgorithmProblems.Heaps.HeapHelper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Graphs.MinSpanningTree { /// <summary> /// Get the minimum spanning tree of a graph using Prim's algorithm /// minimum spanning tree - Given connected graph G with positive edge weights, find a min weight set of edges that connects all of the vertices. /// /// Algo: /// 1. Select any vertex from graph and put it in a set /// 2. Add all the edges from this vertex to the PriorityQueue /// 3. Select the min weight edge such that one vertex is in set and another is not in the set. /// 4. Add this to the mst (list<edge>) /// 5. Do this till all the vertices are in the set. /// /// This is also a greedy algorithm. /// The running time of this algorithm is O(Elog(V)) /// </summary> class PrimsAlgorithm { public List<Edge> GetMST(Graph graph) { List<Edge> mst = new List<Edge>(); MinHeap<Edge> priorityQueue = new MinHeap<Edge>(graph.TotalNumOfEdges); Dictionary<int, bool> verticesInMst = new Dictionary<int, bool>(); //1.Select any vertex from graph and put it in a set int vertexId = graph.Edges.ElementAt(0).Key; verticesInMst.Add(vertexId, true); while(verticesInMst.Count < graph.Edges.Count) { //2.Add all the edges from this vertex to the PriorityQueue foreach(Edge e in graph.Edges[vertexId]) { if ((verticesInMst.ContainsKey(e.StId) && !verticesInMst.ContainsKey(e.EndId)) || (!verticesInMst.ContainsKey(e.StId) && verticesInMst.ContainsKey(e.EndId))) { priorityQueue.Insert(e); } } //3. Select the min weight edge such that one vertex is in set and another is not in the set. Edge minEdge = null; do { minEdge = priorityQueue.ExtractMin(); } while (minEdge!= null && !IsOneVertexInMst(verticesInMst, minEdge)); mst.Add(minEdge); // 4. Add this to the mst (list<edge>) if(!verticesInMst.ContainsKey(minEdge.StId)) { verticesInMst[minEdge.StId] = true; vertexId = minEdge.StId; } else if (!verticesInMst.ContainsKey(minEdge.EndId)) { verticesInMst[minEdge.EndId] = true; vertexId = minEdge.EndId; } } return mst; } private bool IsOneVertexInMst(Dictionary<int, bool> verticesInMst, Edge minEdge) { if ((verticesInMst.ContainsKey(minEdge.StId) && !verticesInMst.ContainsKey(minEdge.EndId)) || (!verticesInMst.ContainsKey(minEdge.StId) && verticesInMst.ContainsKey(minEdge.EndId))) { return true; } return false; } internal class Graph { public Dictionary<int, List<Edge>> Edges { get; set; } public int TotalNumOfEdges { get; set; } public Graph() { Edges = new Dictionary<int, List<Edge>>(); TotalNumOfEdges = 0; } /// <summary> /// Adds an undirected weighted edge to the graph /// </summary> /// <param name="st"></param> /// <param name="end"></param> /// <param name="weight">weight of the edge</param> public void AddEdge(int st, int end, int weight) { if(!Edges.ContainsKey(st)) { Edges[st] = new List<Edge>() { new Edge(st, end, weight) }; } else { Edges[st].Add(new Edge(st, end, weight)); } if (!Edges.ContainsKey(end)) { Edges[end] = new List<Edge>() { new Edge(end, st, weight) }; } else { Edges[end].Add(new Edge(end, st, weight)); } TotalNumOfEdges += 2; } } /// <summary> /// This is a weighted undirected edge /// </summary> internal class Edge : IComparable { public int StId { get; set; } public int EndId { get; set; } public int Weight { get; set; } public Edge(int stId, int endId, int weight) { StId = stId; EndId = endId; Weight = weight; } /// <summary> /// Print a weighted Edge /// </summary> /// <returns></returns> public override string ToString() { return string.Format("{0} --{1}--> {2}", StId, Weight, EndId); } public int CompareTo(object obj) { Edge newObj = (Edge)obj; return Weight.CompareTo(newObj.Weight); } } #region TestArea public static void TestPrimsAlgorithm() { Graph g = new Graph(); g.AddEdge(0, 1, 4); g.AddEdge(0, 2, 6); g.AddEdge(0, 3, 16); g.AddEdge(1, 4, 24); g.AddEdge(2, 4, 23); g.AddEdge(3, 5, 10); g.AddEdge(2, 5, 5); g.AddEdge(2, 3, 8); g.AddEdge(5, 4, 18); g.AddEdge(5, 6, 11); g.AddEdge(6, 4, 9); g.AddEdge(6, 7, 7); g.AddEdge(5, 7, 14); g.AddEdge(3, 7, 21); PrimsAlgorithm pa = new PrimsAlgorithm(); List<Edge> mst = pa.GetMST(g); PrintMst(mst); } private static void PrintMst(List<Edge> mst) { Console.WriteLine("The mst edges are as shown below:"); foreach (Edge e in mst) { Console.WriteLine(e.ToString()); } } #endregion } }
namespace DesignPatterns.Interpreter { public class BelowPriceSpec : Spec { public float Price { get; private set; } public BelowPriceSpec(float price) { Price = price; } public override bool IsSatisfiedBy(Product product) { return product.Price < Price; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Depths { public class Player { //Basic Stats private int _hp; private int _energy; private int _mentalPower; private int _defence; private int _attack; public int Level { get; set; } //Advanced Stats public int Strength { get; set; } public int Speed { get; set; } public int Endurance { get; set; } public int Agility { get; set; } public int Intelligence { get; set; } public int Willpower { get; set; } public int Personality { get; set; } //Equipment Stats public Weapon PlayerWeapon { get; set; } public Armor PlayerArmor { get; set; } // Inventory Stats public List<Items> Inventory { get; set; } public int Gold { get; set; } //Other Stats public Locations PlayerLocation { get; set; } //Initialized Stats public int HP { get { _hp = Endurance * Convert.ToInt16(1.1); return _hp; } } public int Energy { get { _energy = Endurance * Agility / Convert.ToInt16(1.1); return _energy; } } public int MentalPower { get { _mentalPower = Intelligence * Willpower / Convert.ToInt16(1.1); return _mentalPower; } } public int Defence { get { _defence = Endurance * Convert.ToInt16(1.1) + PlayerArmor.ArmorStrength; return _defence; } } public int Attack { get { _attack = Strength * Convert.ToInt16(1.1) + PlayerWeapon.WeaponDamage; return _attack; } } //Inventory and equipment actions public void AddToInventory(Player player, List<Items> items) { foreach (Items item in items) { player.Inventory.Add(item); } } public void EquipWeapon(Player player, Weapon weapon) { player.PlayerWeapon = weapon; player.Inventory.Remove(weapon); } //Search actions public void Search(Player player) { Random random = new Random(); Locations location = new Locations(); GameItemCollection gameItemCollection = new GameItemCollection(); List<Locations> randomLocations = new List<Locations>() { new Cave(){Name = "Cave"}, new Dungeon(){Name = "Dungeon"}, new MonsterNest(){Name = "Monster Nest"}, new Tower(){Name = "Tower"}, new Town(){Name = "Town"}, new Camp(){Name = "Camp"}, new Locations(){Name ="Wilderness"} }; var randomWeapon = new Random(); randomWeapon.Next(0, 2); var lowLevelWeaponList = gameItemCollection.lowLevelWeapons.ToList(); var randomNumber = random.Next(1, 100); if (randomNumber > 0 && randomNumber < 5) { var currentLocation = randomLocations.ElementAt(0); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } else if (randomNumber > 5 && randomNumber < 10) { var currentLocation = randomLocations.ElementAt(1); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } else if (randomNumber > 10 && randomNumber < 15) { var currentLocation = randomLocations.ElementAt(2); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } else if (randomNumber > 15 && randomNumber < 20) { var currentLocation = randomLocations.ElementAt(3); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } else if (randomNumber > 20 && randomNumber < 25) { Random randomMerchantGenerator = new Random(); var merchGen = randomMerchantGenerator.Next(1, 10); if(merchGen > 0 && merchGen < 3) { location.HasBlacksmith = true; location.HasGeneralMerchant = true; location.HasHerbalist = true; } var currentLocation = randomLocations.ElementAt(4); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } else if (randomNumber > 25 && randomNumber < 30) { Random randomMerchantGenerator = new Random(); var merchGen = randomMerchantGenerator.Next(1, 10); if (merchGen > 0 && merchGen < 3) { location.HasTravelingMerchant = true; } var currentLocation = randomLocations.ElementAt(5); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } else { var currentLocation = randomLocations.ElementAt(6); location.PopulateLocation(currentLocation); player.PlayerLocation = currentLocation; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Methods { class Program { static void Main(string[] args) { int fnum = 1, snum = 2, tnum = 3, nvalue; int sum; String fname; sum = sumup(fnum, snum, tnum); // Pass variables into a method by variable. Console.WriteLine("The sum is: {0}, from {1} + {2} + {3}", sum, fnum, snum, tnum); sum = sumup(tnum: fnum, snum: fnum, fnum: fnum); // Pass variables into a method by name (methodvariable: passing-in variable). Console.WriteLine("The sum is: {0}, from {1} + {2} + {3}", sum, fnum, snum, tnum); sum = sumupOption(fnum); // Not passing in ALL variables. Console.WriteLine("The sum is: {0}, from {1} + {2} + {3}", sum, fnum, snum, tnum); sum = sumupRef(fnum, ref snum, tnum); // Passing in by reference (ref) Console.WriteLine("The sum is: {0}, from {1} + {2} + {3}", sum, fnum, snum, tnum); makeAName(out fname); Console.WriteLine(fname); } private static int sumup(int fnum, int snum, int tnum) { int sum; sum = fnum + snum + tnum; return sum; } private static int sumupOption(int fnum, int snum = 10, int tnum = 20) { int sum; sum = fnum + snum + tnum; return sum; } private static int sumupRef(int fnum, ref int bigFatPig, int tnum) { int sum; bigFatPig = 100; sum = fnum + bigFatPig + tnum; return sum; } private static void makeAName(out String myName) { myName = "Black Twat"; } } }
using System; using SpeedSlidingTrainer.Core.Model.State; namespace ConsoleApplication1.BoardSolverV4 { public sealed class BoardStateV4 { private readonly int eye; public BoardStateV4(int width, int height, int[] values, int eye) { this.Width = width; this.Height = height; this.Values = values; this.eye = eye; } public int Width { get; } public int Height { get; } public int[] Values { get; } public bool CanSlideLeft { get { return (this.eye % this.Width) < this.Width - 1; } } public bool CanSlideUp { get { return (this.eye / this.Width) < this.Height - 1; } } public bool CanSlideRight { get { return (this.eye % this.Width) > 0; } } public bool CanSlideDown { get { return (this.eye / this.Width) > 0; } } public bool Satisfies(BoardGoal goal) { if (goal == null) { throw new ArgumentNullException(nameof(goal)); } for (int i = 0; i < goal.TileCount; i++) { if (goal[i] != 0 && goal[i] != this.Values[i]) { return false; } } return true; } public BoardStateV4 SlideLeft() { return this.Slide(this.eye + 1); } public BoardStateV4 SlideUp() { return this.Slide(this.eye + this.Width); } public BoardStateV4 SlideRight() { return this.Slide(this.eye - 1); } public BoardStateV4 SlideDown() { return this.Slide(this.eye - this.Width); } private BoardStateV4 Slide(int newEyeIndex) { int[] newValues = (int[])this.Values.Clone(); newValues[this.eye] = this.Values[newEyeIndex]; newValues[newEyeIndex] = this.Values[this.eye]; return new BoardStateV4(this.Width, this.Height, newValues, newEyeIndex); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.EPS.Portal; namespace EasyDev.EPS.BusinessObject { public interface IBO { bool Save(IModel entity); bool Delete(IModel entity); bool Update(IModel entity); IModel FindByInstance(IModel instance); IList<IModel> FindAllInstance(); string GetNextSequenceId(string tableName); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using V50_IDOMBackOffice.AspxArea.MasterData.Models; using V50_IDOMBackOffice.AspxArea.MasterData.Repositorys; namespace V50_IDOMBackOffice.AspxArea.MasterData.Controllers { public class UnitOfferController { public List<UnitOfferViewModel> Init() { return TouristUnitRepository.GetUnitOfferViewModel(); } public void AddUnitOffer(UnitOfferViewModel model) { MasterDataRepository.AddMasterData(model); } public void UpdateUnitOffer(UnitOfferViewModel model) { MasterDataRepository.UpdateMasterData(model); } public void DeleteUnitOffer(string id) { MasterDataRepository.DeleteUnitOffer(id); } public bool ContainsOfferCode(string offercode) { return MasterDataRepository.UnitOfferContainsCode(offercode); } public List<string> GetUnitCodes() { return TouristUnitRepository.GetUnitCodes(); } public string GetSiteCode(string unitcode) { return TouristUnitRepository.GetSiteCodeFromUnit(unitcode); } public List<UnitOfferViewModel> GetUnitOfferByCode(string sitecode,string unitcode) { return TouristUnitRepository.GetUnitOfferByCode(sitecode, unitcode); } } }