text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace MAS_Końcowy.Model { //TODO: Zmienić nazwę na zgodne z konwencją DishIngredients public class DishContent { public int DishId { get; set; } public Dish Dish { get; set; } public int IngredientId { get; set; } public Ingredient Ingredient { get; set; } public double Quantity { get; set; } public DishContent() { } public DishContent(Dish dish, Ingredient ingredient, double quantity) { Dish = dish; Ingredient = ingredient; Quantity = quantity; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data.SqlClient; using System.Collections; using System.Drawing.Printing; namespace SoundServant { public class StoredDisc { public readonly int Id; string title; bool current = false; public readonly StoredRecording Recording; DirectoryInfo directory; TimeSpan length = new TimeSpan(0); ArrayList tracks = new ArrayList(); public StoredTrack CurrentTrack = null; public bool Flag = false; bool error = false; int copies = 0; public bool Error { get { return error; } } public bool Current { get { return current; } } public ArrayList Tracks { get { return tracks; } } public int Number { get { return Recording.Discs.IndexOf(this) + 1; } } public DirectoryInfo Directory { get { return directory; } } public TimeSpan Length { get { if (!current) { TimeSpan length = new TimeSpan(0); foreach (StoredTrack track in tracks) { length += track.Length; } return length; } else { return Recording.Recorder.RecorderDiscTimePassed; } } } public int Copies { get { return copies; } } public string Title { get { return title; } set { title = value; SqlConnection connection = SS.Connection(); SqlCommand dbCommand = new SqlCommand("UPDATE discs SET discTitle = '" + SS.MakeSQLSafe(title) + "' WHERE discId = " + Id, connection); dbCommand.ExecuteNonQuery(); if (Updated != null) Updated(); connection.Close(); connection.Dispose(); } } public string Summary { get { string summary = "Disc " + Number + "(" + SS.ParseTimeSpan(length) + ")"; foreach (StoredTrack track in tracks) { if (!track.IsSong) { summary += ", " + track.Title; } } return summary; } } public delegate void VoidEventHandler(); public event VoidEventHandler Updated; public event VoidEventHandler Finished; public event VoidEventHandler Deleted; public delegate void NewTrackCreatedEventHandler(); public event NewTrackCreatedEventHandler NewTrackCreated; public StoredDisc(StoredRecording r, int i) { Id = i; Recording = r; directory = new DirectoryInfo(Recording.Directory.FullName + "\\" + Id); if (directory.Exists) { SqlCommand dbCommand; SqlDataReader dbReader; SqlConnection connection = SS.Connection(); dbCommand = new SqlCommand("SELECT discTitle, discCopies FROM discs WHERE discId = " + Id, connection); dbReader = dbCommand.ExecuteReader(); dbReader.Read(); title = dbReader["discTitle"].ToString(); copies = (int)dbReader["discCopies"]; dbReader.Close(); dbCommand = new SqlCommand("SELECT trackID FROM tracks WHERE trackDisc = " + Id, connection); dbReader = dbCommand.ExecuteReader(); if (dbReader.HasRows) while (dbReader.Read()) { StoredTrack track = new StoredTrack((int)dbReader[0], this); tracks.Add(track); if (track.Error) error = true; } dbReader.Close(); connection.Close(); connection.Dispose(); } } public void IncrementCopies() { copies++; SqlConnection connection = SS.Connection(); SqlCommand dbCommand = new SqlCommand("UPDATE discs SET discCopies = " + copies + " WHERE discId = " + Id, connection); dbCommand.ExecuteNonQuery(); if (Updated != null) Updated(); connection.Close(); connection.Dispose(); } public StoredDisc(StoredRecording r, string t, out int i) { title = t; Recording = r; current = true; SqlConnection connection = SS.Connection(); SqlCommand dbCommand = new SqlCommand("INSERT INTO discs (discTitle, discRec) VALUES ('" + title + "', '" + Recording.Id + "') SELECT CAST(scope_identity() AS int)", connection); Id = (int)dbCommand.ExecuteScalar(); connection.Close(); connection.Dispose(); i = Id; directory = new DirectoryInfo(Recording.Directory.FullName + "\\" + Id); directory.Create(); if (Recording.CurrentDisc != null) Recording.CurrentDisc.Finish(); Recording.CurrentDisc = this; NewTrackCreated += new NewTrackCreatedEventHandler(Recording.NewTrackCreatedProxy); } public string CreateNewTrack(string t) { string newTrackPath; tracks.Add(new StoredTrack(this, t, out newTrackPath)); if (NewTrackCreated != null) NewTrackCreated(); return newTrackPath; } public void Finish() { if (current) { CurrentTrack.Finish(); current = false; if (Finished != null) Finished(); } } public void Delete() { if (!current) { foreach (StoredTrack track in tracks) { track.Delete(); } directory.Delete(true); SqlConnection connection = SS.Connection(); SqlCommand dbCommand = new SqlCommand("DELETE FROM discs WHERE discId = " + Id, connection); dbCommand.ExecuteNonQuery(); connection.Close(); connection.Dispose(); if (Deleted != null) Deleted(); } } public void PrintLabel() { PrintDocument label = new PrintDocument(); label.PrintPage += new PrintPageEventHandler(Label_Print); label.Print(); } void Label_Print(object sender, PrintPageEventArgs e) { } } }
using Stagehand; using UnityEngine; namespace Plugins.Backstage.Vendors.Unity { public class StagehandMonoBehaviour : MonoBehaviour { // Living and Breathing Code // // If you build it with no uncovered edge cases, // it will do exactly what you programmed it to do... // every time. // // Therefore, we always execute the code as its written // in order to immediately expose edge cases, as they // come up, and they cannot be ignored. #if UNITY_EDITOR private void OnValidate() { Stage<MonoBehaviour>.Hand(); } #else private void OnEnable() { Stage<MonoBehaviour>.Hand(); } #endif } }
using System; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; namespace BELCORP.GestorDocumental.Contratos.EH_Tareas.Layouts.BELCORP.GestorDocumental.Contratos.EH_Tareas { public partial class ERContratosCustomError : LayoutsPageBase { public const string MENSAJE_HTML_ERROR_PERSONALIZADO_CARGA_WEBPART = "<div class='content_advertencia'>" + "<h2>Mensaje del Sistema</h2>" + "<p>{0}</p>" + "</div>"; protected void Page_Load(object sender, EventArgs e) { string strMessage = Page.Request.QueryString["Message"]; //if (Page.Request.QueryString["codRC"] != null) //{ // string codRC = Page.Request.QueryString["codRC"]; // strMessage = strMessage + "<br><br>" + codRC; //} //Se crea HTML de error personalizado string strMensajeError = string.Format(MENSAJE_HTML_ERROR_PERSONALIZADO_CARGA_WEBPART, strMessage); //Se muestra HTML del error personalizado ltrMensajeErrorCarga.Text = strMensajeError; } } }
using System; using System.Reflection; using System.Windows.Input; using Xamarin.Forms; namespace AsNum.XFControls.Binders { public class CmdBinder { #region public static readonly BindableProperty EventProperty = BindableProperty.CreateAttached("Event", typeof(string), typeof(CmdBinder), null ); public static readonly BindableProperty CmdProperty = BindableProperty.CreateAttached("Cmd", typeof(ICommand), typeof(CmdBinder), null, propertyChanged: CommandChanged ); public static readonly BindableProperty ParamProperty = BindableProperty.CreateAttached("Param", typeof(object), typeof(CmdBinder), null); public static object GetParam(BindableObject o) { return o.GetValue(ParamProperty); } public static ICommand GetCmd(BindableObject o) { return (ICommand)o.GetValue(CmdProperty); } public static string GetEvent(BindableObject o) { return (string)o.GetValue(EventProperty); } #endregion private static MethodInfo CreateDelegateMethod = null; private static MethodInfo FireMethod = null; private static bool CanUse = false; static CmdBinder() { //CreateDelegateMethod = typeof(Delegate) // .GetRuntimeMethods() // .FirstOrDefault(m => m.Name.Equals("CreateDelegate")); CreateDelegateMethod = typeof(Delegate) .GetRuntimeMethod("CreateDelegate", new Type[] { typeof(Type), typeof(MethodInfo) }); if (CreateDelegateMethod != null) { FireMethod = typeof(CmdBinder).GetTypeInfo() .GetDeclaredMethod("Fire"); CanUse = true; } } private static void CommandChanged(BindableObject bindable, object oldValue, object newValue) { if (CanUse) { var evt = bindable.GetType().GetTypeInfo().GetDeclaredEvent(GetEvent(bindable)); if (evt != null) { var handler = (Delegate)CreateDelegateMethod.Invoke(null, new object[] { evt.EventHandlerType, FireMethod }); evt.AddEventHandler(bindable, handler); } } } private static void Fire(object sender, EventArgs e) { var ele = (BindableObject)sender; var param = GetParam(ele); var cmd = GetCmd(ele); if (cmd.CanExecute(param)) cmd.Execute(param); } } }
using System; using System.Collections; using UnityEngine; using UnityEngine.UI; //general manager of the UI public class HUDManager : MonoBehaviour { //On screen information public Image[] Lifes; public Text ScoreText; public Text HiScoreText; //Elements for "win/next level" screen public GameObject NextLevelScreen; public GameObject NextLevelBox; public Text NextLevelText; public Text LevelMessage; public GameObject ExtraLife; //Elements for "game over" screen public GameObject GameOverScreen; public GameObject NewHighBox; public Text ResultText; public Text ReplayText; //info values int currentScore; int currentHiScore; int enemies; //updates life icons when the player is damaged or win lifes public void UpdateHp (int lifes) { for(int i = 0; i < Lifes.Length; i++) { if(i < lifes) Lifes[i].enabled = true; else Lifes[i].enabled = false; } } //update the score on screen and save the value public void UpdateScore (int score) { ScoreText.text = String.Format("{0:00000}", score); currentScore = score; } //update the hi-score on screen and save the value public void SetHiScore (int score) { HiScoreText.text = String.Format("{0:00000}", score); currentHiScore = score; } //save how many enemies are on scene public void SetEnemies (int e) { enemies = e; } //display the next level screen and the correspondent info public void ShowNextLevel (string message, int hazards, bool extraLife) { NextLevelScreen.SetActive(true); if(hazards == -1) NextLevelBox.SetActive(false); else NextLevelText.text = string.Format("Next Level -{0} Hazard", hazards); StartCoroutine(NextLevelWait(message, hazards == -1)); //show extra life box ExtraLife.SetActive(extraLife); } //wait while the text is being displayed IEnumerator NextLevelWait (string msg, bool isLastLevel) { yield return StartCoroutine(WriteText(LevelMessage, msg)); yield return new WaitForSeconds(4); //if it is the last level, shows the "game over" screen, if is not load the next level if(!isLastLevel) UnityEngine.SceneManagement.SceneManager.LoadScene(1); else ShowGameOver(currentScore, currentScore > currentHiScore, enemies); } //shows the "game over" screen public void ShowGameOver (int score, bool newHigh, int hazards) { GameOverScreen.SetActive(true); NewHighBox.SetActive(newHigh); StartCoroutine(GameOverWait(score, hazards)); } //wait while the text is being displayed and later for the player to press start IEnumerator GameOverWait (int score, int hazards) { ResultText.text = string.Format("Final Score {0}\nWith {1} hazards", String.Format("{0:00000}", score), hazards); yield return StartCoroutine(WriteText(ReplayText, "Press ENTER to replay")); while(true) { if(Input.GetButtonDown("Submit")) break; yield return null; } //reload the game UnityEngine.SceneManagement.SceneManager.LoadScene(0); } //helpet method for the writing effect IEnumerator WriteText (Text t, string msg) { string str = string.Empty; WaitForSeconds wfs = new WaitForSeconds(0.075f); for(int i = 0; i < msg.Length; i++) { str = string.Concat(str, msg[i]); t.text = str; yield return wfs; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ImageSwitchScript : MonoBehaviour { public Sprite image1; public Sprite image2; public SpriteRenderer render; bool im1current; float time = 0.0f; // Use this for initialization void Start () { im1current = true; render = gameObject.GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update () { time += Time.deltaTime; if(time >= 1.0f) { time = 0.0f; changeImage(); } } public void changeImage() { if (im1current) { im1current = false; render.sprite = image2; } else { im1current = true; render.sprite = image1; } } }
using GraphicalEditor.Enumerations; using GraphicalEditor.Models; using GraphicalEditor.Models.MapObjectRelated; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphicalEditor.Repository { public class FileRepository : IRepository { private String Path { get; set; } public FileRepository(String path) { Path = path; } public void SaveMap(List<MapObject> allMapObjects) { JsonSerializer serializer = new JsonSerializer(); serializer.TypeNameHandling = TypeNameHandling.All; serializer.Formatting = Formatting.Indented; serializer.ContractResolver = new ContractResolver(); serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; using (StreamWriter writer = new StreamWriter("test.json")) using (JsonWriter jwriter = new JsonTextWriter(writer)) { serializer.Serialize(jwriter, allMapObjects); } } public IEnumerable<MapObject> LoadMap() { string jsonString = File.Exists("test.json") ? File.ReadAllText("test.json") : ""; var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; if (!string.IsNullOrEmpty(jsonString)) { return JsonConvert.DeserializeObject<List<MapObject>>(jsonString, settings); } else { return new List<MapObject>(); } } public void UpdateMapObject(MapObject mapObject) { IEnumerable<MapObject> allMapObjects = LoadMap(); var singleMapObject = allMapObjects.FirstOrDefault(e => e.MapObjectEntity.Id == mapObject.MapObjectEntity.Id); if (singleMapObject != null) { List<MapObject> objectToSave = new List<MapObject>(); foreach (MapObject anObject in allMapObjects) { objectToSave.Add(anObject); } for (int i = 0; i < objectToSave.Count; i++) { if (objectToSave[i].MapObjectEntity.Id == mapObject.MapObjectEntity.Id) { objectToSave[i].MapObjectEntity.MapObjectType = mapObject.MapObjectEntity.MapObjectType; objectToSave[i].MapObjectEntity.Description = mapObject.MapObjectEntity.Description; objectToSave[i].MapObjectMetrics = mapObject.MapObjectMetrics; objectToSave[i].Rectangle.Fill = mapObject.Rectangle.Fill; objectToSave[i].MapObjectDoor = mapObject.MapObjectDoor; objectToSave[i].MapObjectNameTextBlock = mapObject.MapObjectNameTextBlock; break; } } SaveMap(objectToSave); } } } }
 namespace Elm327.Core { /// <summary> /// Represents all OBD protocols supported by the ELM chip. /// </summary> public enum ObdProtocolType { /// <summary> /// The ELM chip will automatically determine the best protocol to use. /// </summary> Automatic = '0', /// <summary> /// SAE J1850 PWM (41.6 kbaud). /// </summary> SaeJ1850Pwm = '1', /// <summary> /// SAE J1850 VPW (10.4 kbaud). /// </summary> SaeJ1850Vpw = '2', /// <summary> /// ISO 9141-2 (5 baud init, 10.4 kbaud). /// </summary> Iso9141_2 = '3', /// <summary> /// ISO 14230-4 KWP (5 baud init, 10.4 kbaud). /// </summary> Iso14230_4_Kwp = '4', /// <summary> /// ISO 14230-4 KWP (fast init, 10.4 kbaud). /// </summary> Iso14230_4_KwpFastInit = '5', /// <summary> /// ISO 15765-4 CAN (11 bit ID, 500 kbaud). /// </summary> Iso15765_4_Can11BitFast = '6', /// <summary> /// ISO 15765-4 CAN (29 bit ID, 500 kbaud). /// </summary> Iso15765_4_Can29BitFast = '7', /// <summary> /// ISO 15765-4 CAN (11 bit ID, 250 kbaud). /// </summary> Iso15765_4_Can11Bit = '8', /// <summary> /// ISO 15765-4 CAN (29 bit ID, 250 kbaud). /// </summary> Iso15765_4_Can29Bit = '9', /// <summary> /// SAE J1939 CAN (29 bit ID, 250 kbaud). /// </summary> SaeJ1939Can = 'A' } }
using Discord; using Discord.Commands; using Discord.WebSocket; using JhinBot.Conversation; using JhinBot.DiscordObjects; using JhinBot.Enums; using JhinBot.Preconditions; using JhinBot.Services; using JhinBot.Utils; using NLog; using System.Collections.Generic; using System.Threading.Tasks; namespace JhinBot.Modules { [Summary("Contains all commands related to roles."), RequireContext(ContextType.Guild), RequireChannel(BotChannelType.BotSpam)] public class TestModule : BotModuleBase { private readonly DiscordSocketClient _client; public TestModule(IMessageFormatService formatter, IHelpService helpService, IOwnerLogger ownerLogger, IResourceService resources, IEmbedService embedService, DiscordSocketClient client, IBotConfig botConfig, IDbService dbService) : base(ownerLogger, formatter, resources, embedService, botConfig, dbService) { _client = client; } [Command("aaaa"), Summary("Test command")] public async Task Aaaa() { var embedBuilder = _embedService.CreateEmbed("cccc", "FFFFFF"); var p = new PagedEmbed(_ownerLogger, _botConfig); var list = new List<(string, string)> { ("1", "bbbb"), ("2", "bbbb"), ("3", "bbbb"), ("4", "bbbb"), ("5", "bbbb"), ("6", "bbbb"), ("7", "bbbb"), ("8", "bbbb"), ("9", "bbbb"), ("10", "bbbb"), ("11", "bbbb"), ("12", "bbbb"), ("13", "bbbb"), }; p.CreatePagedEmbed(embedBuilder, list, Context.User.Id); var msg = await SendEmbedMessageAsync(embedBuilder, "<:peepoCheer:344307726693826563>"); await p.AddReactionsToPagedEmbed(msg, _client); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using ViaTim.Plugin.Entities.Recipient; using ViaTim.Plugin.Entities.Types; namespace ViaTim.Plugin.Entities.Package { [JsonObject] public class ViaTimPackageInputFields : EntityBase<string> { [JsonProperty(PropertyName = "type")] public PackageTypes Type { get; set; } [JsonProperty(PropertyName = "recipient")] public ViaTimRecipientInputFields Recipient { get; set; } [JsonProperty(PropertyName = "weight")] public double Weight { get; set; } [JsonProperty(PropertyName = "value")] public double Value { get; set; } [JsonProperty(PropertyName = "photo")] public bool Photo { get; set; } [JsonProperty(PropertyName = "label")] public string Label { get; set; } } }
using System; using System.Threading.Tasks; using DFC.ServiceTaxonomy.GraphSync.Extensions; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts; using DFC.ServiceTaxonomy.UnpublishLater.Models; using Newtonsoft.Json.Linq; namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts { #pragma warning disable S1481 // need the variable for the new using syntax, see https://github.com/dotnet/csharplang/issues/2235 public class UnpublishLaterPartGraphSyncer : ContentPartGraphSyncer { public override string PartName => nameof(UnpublishLaterPart); private const string _contentTitlePropertyName = "ScheduledUnpublishUtc"; //todo: configurable?? public const string NodeTitlePropertyName = "unpublishlater_ScheduledUnpublishUtc"; public override Task AddSyncComponents(JObject content, IGraphMergeContext context) { context.MergeNodeCommand.AddProperty<DateTime>(NodeTitlePropertyName, content, _contentTitlePropertyName); return Task.CompletedTask; } public override Task<(bool validated, string failureReason)> ValidateSyncComponent(JObject content, IValidateAndRepairContext context) { return Task.FromResult(context.GraphValidationHelper.DateTimeContentPropertyMatchesNodeProperty( _contentTitlePropertyName, content, NodeTitlePropertyName, context.NodeWithRelationships.SourceNode!)); } } #pragma warning restore S1481 }
using System; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference of type `int`. Inherits from `AtomEventReference&lt;int, IntVariable, IntEvent, IntVariableInstancer, IntEventInstancer&gt;`. /// </summary> [Serializable] public sealed class IntEventReference : AtomEventReference< int, IntVariable, IntEvent, IntVariableInstancer, IntEventInstancer>, IGetEvent { } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `IntPair`. Inherits from `AtomDrawer&lt;IntPairEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(IntPairEvent))] public class IntPairEventDrawer : AtomDrawer<IntPairEvent> { } } #endif
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerRaycasting : MonoBehaviour { public float distanceToSee; RaycastHit hit; public bool isholding = false; void Start() { } void Update() { if (Input.GetKeyDown(KeyCode.F)) { if (!isholding) { if (Physics.Raycast(this.transform.position, this.transform.forward, out hit, distanceToSee)) { if (hit.collider.tag == "identable") { isholding = true; GameObject g = hit.collider.gameObject; g.GetComponent<Rigidbody>().useGravity = false; g.GetComponent<Rigidbody>().isKinematic = true; g.transform.parent = this.gameObject.transform; g.transform.rotation = Quaternion.LookRotation(this.transform.right, this.transform.up); g.transform.localPosition = new Vector3(0.7f, -0.7f, 1.5f); } } } else { isholding = false; this.gameObject.GetComponentInChildren<Rigidbody>().useGravity = true; this.gameObject.GetComponentInChildren<Rigidbody>().isKinematic = false; this.gameObject.transform.DetachChildren(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Level36 : MonoBehaviour { public float timer = 0f; public Vector2 position; private List<Record> leftLines = new List<Record>(); private List<Record> rightLines = new List<Record>(); private List<Record> distanseX = new List<Record>(); private List<Record> distanseY = new List<Record>(); public GameObject left; public GameObject right; public GameObject x; public GameObject y; private float offset = 8f; private float distanceOffset = 0.2f; private bool win = false; public struct Record { public GameObject go; public Vector3 initPosition; } private void OnDestroy() { TapListener.FingerMoving -= CheckTouch; } private void Start() { TapListener.FingerMoving += CheckTouch; leftLines = getItems(left); rightLines = getItems(right); distanseX = getItems(x); distanseY = getItems(y); } private List<Record> getItems(GameObject go) { var parent = Utilites.GetAllChildren(go); var result = new List<Record>(); foreach (var item in parent) { Record i = new Record { go = item, initPosition = item.transform.position }; result.Add(i); //move out item.transform.position = new Vector3(item.transform.position.x + offset, item.transform.position.y, item.transform.position.z); } return result; } private void CheckTouch(Vector2 vec) { var distY = Math.Abs(vec.y - position.y); var distX = Math.Abs(vec.x - position.x); var distance = Vector2.Distance(position, vec); //left foreach (var item in leftLines) { var initPos = item.initPosition; item.go.transform.position = new Vector3(initPos.x - distance + distanceOffset, initPos.y, initPos.z); } //right foreach (var item in rightLines) { var initPos = item.initPosition; item.go.transform.position = new Vector3(initPos.x + distance - distanceOffset, initPos.y, initPos.z); } //x foreach (var item in distanseX) { var initPos = item.initPosition; item.go.transform.position = new Vector3(initPos.x + distX - distanceOffset, initPos.y, initPos.z); } //y foreach (var item in distanseY) { var initPos = item.initPosition; item.go.transform.position = new Vector3(initPos.x - distY + distanceOffset, initPos.y, initPos.z); } if (distance < distanceOffset) { win = true; } } // Update is called once per frame private void Update() { if (win) { timer += Time.deltaTime; if (timer > 1f) { Debug.Log("WIN"); GameManager.instance.NextLevel(); } } } }
using Unity.Entities; using Unity.Mathematics; using Unity.Rendering; using Unity.Transforms; using UnityEngine; using Water; namespace Fire { [RequiresEntityConversion] public class FireAuthoring : UnityEngine.MonoBehaviour, IConvertGameObjectToEntity { public UnityEngine.Color UnlitColor = UnityEngine.Color.green; public UnityEngine.Color LitLowColor = UnityEngine.Color.yellow; public UnityEngine.Color LitHighColor = UnityEngine.Color.red; public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { dstManager.AddComponentData(entity, new TemperatureComponent { Value = 0f, Velocity = 0f, StartVelocity = 0f, IgnitionVariance = 0f, GridIndex = 0 }); dstManager.AddComponentData(entity, new StartHeight { Value = 0f }); dstManager.AddComponentData(entity, new BoundsComponent { SizeXZ = transform.localScale.x, SizeY = transform.localScale.y }); // Add fire color dstManager.AddComponentData(entity, new FireColor { Value = new float4(UnlitColor.r, UnlitColor.g, UnlitColor.b, 1) }); dstManager.AddComponentData(entity, new FireColorPalette { UnlitColor = new float4(UnlitColor.r, UnlitColor.g, UnlitColor.b, 1), LitLowColor = new float4(LitLowColor.r, LitLowColor.g, LitLowColor.b, 1), LitHighColor = new float4(LitHighColor.r, LitHighColor.g, LitHighColor.b, 1) }); } } [MaterialProperty("_BaseColor", MaterialPropertyFormat.Float4)] public struct FireColor : IComponentData { public float4 Value; } public struct FireColorPalette : IComponentData { public float4 UnlitColor; public float4 LitLowColor; public float4 LitHighColor; } public struct StartHeight : IComponentData { public float Value; public float Variance; } public struct TemperatureComponent : IComponentData { public float Value; public float Velocity; public float StartVelocity; public float IgnitionVariance; public int GridIndex; } // TODO make bounds readonly once initialized public struct BoundsComponent : IComponentData { public float SizeXZ; public float SizeY; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; using System.IO; using System.Text; using System.Data.Entity; using System.Net; using System.Web.Mvc; using SistemaFacturacionWeb.Models; using CrystalDecisions.CrystalReports.Engine; namespace SistemaFacturacionWeb { public partial class AgregarProveedor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text == ("") || TextBox2.Text == ("") || TextBox3.Text == ("") || TextBox4.Text == ("") || TextBox5.Text == ("") || TextBox6.Text == ("")) { Label7.Text = ("Debe llenar todos los campos Vacios"); } else { SqlConnection cn = new SqlConnection("Data Source=DESKTOP-KH2KFO1;initial catalog=facturacion;integrated security=True"); cn.Open(); SqlCommand cmd = new SqlCommand("INSERT INTO proveedor(RazonSocialProveedor,RifProveedor,TelefonoProveedor,DireccionProveedor,DetallesProveedor,NombreContactoProveedor,SitioWebProveedor) VALUES('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "')", cn); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); cmd.Parameters.AddWithValue("RazonSocialProveedor", TextBox1.Text); cmd.Parameters.AddWithValue("RifProveedor", TextBox2.Text); cmd.Parameters.AddWithValue("TelefonoProveedor", TextBox3.Text); cmd.Parameters.AddWithValue("DireccionProveedor", TextBox4.Text); cmd.Parameters.AddWithValue("DetallesProveedor", TextBox5.Text); cmd.Parameters.AddWithValue("NombreContactoProveedor", TextBox6.Text); cmd.Parameters.AddWithValue("SitioWebProveedor", TextBox7.Text); cmd.ExecuteNonQuery(); cn.Close(); TextBox1.Text = (""); TextBox2.Text = (""); TextBox3.Text = (""); TextBox4.Text = (""); TextBox5.Text = (""); TextBox6.Text = (""); TextBox7.Text = (""); Label7.Text = ("Datos Ingresados Correptamente"); } } } }
namespace Sentry.Extensibility; /// <summary> /// Form based request extractor. /// </summary> public class FormRequestPayloadExtractor : BaseRequestPayloadExtractor { private const string SupportedContentType = "application/x-www-form-urlencoded"; /// <summary> /// Supports <see cref="IHttpRequest"/> with content type application/x-www-form-urlencoded. /// </summary> protected override bool IsSupported(IHttpRequest request) => SupportedContentType .Equals(request.ContentType, StringComparison.InvariantCulture); /// <summary> /// Extracts the request form data as a dictionary. /// </summary> protected override object? DoExtractPayLoad(IHttpRequest request) => request.Form?.ToDictionary(k => k.Key, v => v.Value); }
using System; using System.Collections.Generic; using System.Text; namespace WebScrapingRobot.Model { public class Opportunity { public int Id { get; set; } public string Name { get; set; } public string SolicitationNumber { get; set; } public string Category { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace huffman { public class Huffman { public Dictionary<char, float> numbers = new Dictionary<char, float>(); public Dictionary<char, float> prob = new Dictionary<char, float>(); public Dictionary<char, int> sortedProb = new Dictionary<char, int>(); public Dictionary<char, string> codes = new Dictionary<char, string>(); public Dictionary<char, int> bits = new Dictionary<char, int>(); public List<Node> tree = new List<Node>(); public List<Node> secondTree = new List<Node>(); public List<double> PartEntropyList = new List<Double>(); public List<double> PartAvgWorldValueList = new List<Double>(); public double Entropy { get; set; } public double AvgWordValue { get; set; } public Dictionary<char, float> getNumbers(string input) { var x = 0; var len = input.Length; while(x < len) { char chr = input[x]; if(numbers.ContainsKey(chr)) { numbers[chr] = numbers[chr]+1; } else { numbers.Add(chr, 1); } x++; } return numbers; } public Dictionary<char, float> getProbabilities(string input) { int len = input.Length; numbers = getNumbers(input); foreach(var elem in numbers) { prob[elem.Key] = elem.Value / len; } return prob; } public Dictionary<char, string> getCodes() { var sortedProb = from entry in prob orderby entry.Value ascending select entry; foreach (var elem in sortedProb) { tree.Add(new Node { Prob = elem.Value, Value = elem.Key}); } while(tree.Count + secondTree.Count > 1) { Node left = getNext(); Node right = getNext(); Node newNode = new Node(); newNode.Left = left; newNode.Right = right; newNode.Prob = left.Prob + right.Prob; newNode.Left.Parent = newNode; newNode.Right.Parent = newNode; secondTree.Add(newNode); } Node currentNode = secondTree[0]; string code = " "; while (!(currentNode is null)) { if (currentNode.Value != default(char)) { codes[currentNode.Value] = code; code = code.Substring(0, code.Length-1); currentNode.Visited = true; currentNode = currentNode.Parent; }else if (!currentNode.Left.Visited) { currentNode = currentNode.Left; code += "0"; }else if (!currentNode.Right.Visited) { currentNode = currentNode.Right; code += "1"; } else { currentNode.Visited = true; currentNode = currentNode.Parent; code = code.Substring(0, code.Length-1); } } return codes; } public List<EncodedText> compressHuffman(string input) { EncodedText encodedText; List <EncodedText> encodedTextsList = new List<EncodedText>(); for(var i=0; i<input.Length; i++) { encodedText = new EncodedText(); encodedText.Sign = input[i]; encodedText.Code = codes[input[i]]; encodedTextsList.Add(encodedText); } return encodedTextsList; } public double getEntropy() { foreach(var p in prob) { Entropy += p.Value * Math.Log(1 / p.Value,2); PartEntropyList.Add(Entropy); } return Math.Round(Entropy, 5); } public Dictionary<char, int> getBits() { foreach(var p in codes) { bits[p.Key] = p.Value.Length; } return bits; } public double getAvgWordValue() { foreach (var p in codes) { AvgWordValue += (prob[p.Key] * p.Value.Length); PartAvgWorldValueList.Add(AvgWordValue); } return Math.Round(AvgWordValue, 5)-1; } public Node getNext() { if(tree.Count > 0 && secondTree.Count > 0 && (tree[0].Prob < secondTree[0].Prob)) { return shiftArray(tree); } if(tree.Count > 0 && secondTree.Count > 0 && (tree[0].Prob > secondTree[0].Prob)) { return shiftArray(secondTree); } if (tree.Count > 0) return shiftArray(tree); return shiftArray(secondTree); } public List<Node> push(List<Node> _tree, Node elem) { var tempList = _tree.ToList(); tempList.Add(elem); return tempList; } public Node shiftArray(List<Node> _array) { var shifted = _array[_array.Count - 1]; var t = _array.First(); _array.RemoveAt(0); Console.WriteLine("shifted: " + t.Value); return t; } } }
using System; using System.Collections.Generic; using System.Text; namespace FrameOS.Systems.Script { public static class NeonSharp { /* NeonSharp documentation lol * * echoLine() == terminal.writeline() * echo() == terminal.write() * text = readInput() == ? Still need to figure out how to store variables, maybe with a dictionary<string, string> where the key is the variable name and the value becomes the read line * if else endif * text += text * echoLine("text" + variable) */ public static Dictionary<string, string> variables = new Dictionary<string, string>(); /// <summary> /// Executes the code given. /// </summary> /// <param name="scriptLines">Code seperated in lines to execute.</param> public static void Exec(string[] scriptLines) { int line = 0; try{ for (int i = 0; i < scriptLines.Length; i++) { line = i; ReadLine(scriptLines[i]); } }catch(Exception e) { Cosmos.HAL.Terminal.WriteLine($"Neon Sharp Exception on line: {line+1}\n{e.Message}"); } } private static void ReadLine(string line) { if (line.StartsWith("echoLine(") && line.EndsWith(")")) { string text = line.Remove(0, 9).Remove(line.Length-1, 1); string arguments = NeonArguments.getTotalString(text); if (arguments != "") { Cosmos.HAL.Terminal.WriteLine(arguments); } } } public static string TryGetVariable(string name) { if (variables.ContainsKey(name)) { return variables[name]; } throw new Exception("Variable: " + name + " doesn't exist!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using System.IO; namespace CommandsStart { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e) { } private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if(ofd.ShowDialog() == true) { string path = ofd.FileName; text.Text = File.ReadAllText(path); } } private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e) { SaveFileDialog ofd = new SaveFileDialog(); if (ofd.ShowDialog() == true) { string path = ofd.FileName; File.WriteAllText(path, text.Text); } } private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e) { this.Close(); } private void ResetCommand_Executed(object sender, ExecutedRoutedEventArgs e) { text.Clear(); } private void HelpCommand_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("HURRAY, MAN!"); } } }
namespace dotLua { static internal class LuaConstant { public const int MultiReturn = -1; } }
 using NUnit.Framework; namespace LAB09 { [TestFixture] public class MyMathTests { [TestCase] public void CompareAdd01Asserts() { var actual = new MyMath (); var expected = 2; Assert.AreEqual(expected, actual.Add(1,1)); } [TestCase] public void CompareAdd02Asserts() { var actual = new MyMath(); var expected = 4; Assert.AreEqual(expected, actual.Add(2, 2)); } public void TrueAdd03Asserts() { var actual = new MyMath(); Assert.IsTrue(actual.Add(2, 2)==4); } [TestCase] public void CompareSub01Asserts() { var actual = new MyMath(); Assert.AreEqual(0, actual.Sub(1, 1)); } [TestCase] public void CompareSub02Asserts() { var actual = new MyMath(); Assert.AreEqual(0, actual.Sub(2, 2)); } public void CompareSub03Asserts() { var actual = new MyMath(); Assert.IsTrue(actual.Sub(2, 2) == 0); } public void CompareMul01Asserts() { var actual = new MyMath(); Assert.AreEqual(0, actual.Mul(1, 1)); } [TestCase] public void NotNullMul02Asserts() { var actual = new MyMath(); Assert.IsNotNull(actual.Mul(2, 2)); } public void CompareIntDiv01Asserts() { var actual = new MyMath(); Assert.AreEqual(0, actual.Div(1, 1)); } [TestCase] public void CompareDiv01Asserts() { var actual = new MyMath(); Assert.AreEqual(1, actual.Div(0.1, 0.1)); } } }
using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.system; using gView.Framework.Web; using gView.Framework.XML; using gView.GraphicsEngine.Abstraction; using gView.MapServer; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Xml; namespace gView.Interoperability.ArcXML.Dataset { public class ArcIMSClass : IWebServiceClass { internal event EventHandler ModifyResponseOuput = null; private string _name; private ArcIMSDataset _dataset; private GraphicsEngine.Abstraction.IBitmap _legend = null; private GeorefBitmap _image = null; private List<IWebServiceTheme> _clonedThemes = null; public ArcIMSClass(ArcIMSDataset dataset) { _dataset = dataset; if (_dataset != null) { _name = _dataset._name; } } #region IWebServiceClass Member public event AfterMapRequestEventHandler AfterMapRequest = null; async public Task<bool> MapRequest(gView.Framework.Carto.IDisplay display) { if (_dataset == null) { return false; } List<IWebServiceTheme> themes = Themes; if (themes == null) { return false; } #region Check for visible Layers bool visFound = false; foreach (IWebServiceTheme theme in themes) { if (!theme.Visible) { continue; } if (theme.MinimumScale > 1 && theme.MinimumScale > display.mapScale) { continue; } if (theme.MaximumScale > 1 && theme.MaximumScale < display.mapScale) { continue; } visFound = true; break; } if (!visFound) { if (_image != null) { _image.Dispose(); _image = null; } return true; } #endregion string server = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "server"); string service = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "service"); string user = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "user"); string pwd = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "pwd"); IServiceRequestContext context = display.Map as IServiceRequestContext; //if ((user == "#" || user == "$") && // context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null) //{ // string roles = String.Empty; // if (user == "#" && context.ServiceRequest.Identity.UserRoles != null) // { // foreach (string role in context.ServiceRequest.Identity.UserRoles) // { // if (String.IsNullOrEmpty(role)) continue; // roles += "|" + role; // } // } // user = context.ServiceRequest.Identity.UserName + roles; // pwd = context.ServiceRequest.Identity.HashedPassword; //} dotNETConnector connector = new dotNETConnector(); if (!String.IsNullOrEmpty(user) || !String.IsNullOrEmpty(pwd)) { connector.setAuthentification(user, pwd); } if (_dataset.State != DatasetState.opened) { if (!await _dataset.Open(context)) { return false; } } ISpatialReference sRef = (display.SpatialReference != null) ? display.SpatialReference.Clone() as ISpatialReference : null; int iWidth = display.iWidth; int iHeight = display.iHeight; try { StringBuilder sb = new StringBuilder(); sb.Append("<?xml version='1.0' encoding='utf-8'?>"); sb.Append("<ARCXML version='1.1'>"); sb.Append("<REQUEST>"); sb.Append("<GET_IMAGE>"); sb.Append("<PROPERTIES>"); IEnvelope bounds = display.DisplayTransformation.TransformedBounds(display); if (display.DisplayTransformation.UseTransformation == true) { iWidth = (int)(bounds.Width * display.dpm / display.mapScale); iHeight = (int)(bounds.Height * display.dpm / display.mapScale); } sb.Append("<ENVELOPE minx='" + bounds.minx.ToString() + "' miny='" + bounds.miny.ToString() + "' maxx='" + bounds.maxx.ToString() + "' maxy='" + bounds.maxy.ToString() + "' />"); sb.Append("<IMAGESIZE width='" + iWidth + "' height='" + iHeight + "' />"); sb.Append("<BACKGROUND color='" + Color2AXL(display.BackgroundColor) + "' transcolor='" + Color2AXL(display.TransparentColor) + "' />"); string propertyString = _dataset._properties.PropertyString; if (propertyString != String.Empty) { sb.Append(_dataset._properties.PropertyString); } else { if (sRef != null) { //if (this.SpatialReference != null && !display.SpatialReference.Equals(this.SpatialReference)) { string wkt = gView.Framework.Geometry.SpatialReference.ToESRIWKT(sRef); string geotranwkt = gView.Framework.Geometry.SpatialReference.ToESRIGeotransWKT(sRef); if (wkt != null) { //wkt = "PROJCS[\"MGI_M31\",GEOGCS[\"GCS_MGI\",DATUM[\"D_MGI\",SPHEROID[\"Bessel_1841\",6377397.155,0]],PRIMEM[\"Greenwich\",0.0],UNIT[\"degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",450000],PARAMETER[\"False_Northing\",-5000000],PARAMETER[\"Central_Meridian\",13.3333333333333],PARAMETER[\"Scale_Factor\",1],PARAMETER[\"latitude_of_origin\",0],UNIT[\"Meter\",1]]"; //wkt = "PROJCS[\"MGI_M31\",GEOGCS[\"GCS_MGI\",DATUM[\"D_MGI\",SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",450000.0],PARAMETER[\"False_Northing\",-5000000.0],PARAMETER[\"Central_Meridian\",13.33333333333333],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"; //geotranwkt = "GEOGTRAN[\"MGISTMK_To_WGS_1984\",GEOGCS[\"MGISTMK\",DATUM[\"Militar_Geographische_Institute_STMK\",SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],METHOD[\"Position_Vector\"],PARAMETER[\"X_Axis_Translation\",577.326],PARAMETER[\"Y_Axis_Translation\",90.129],PARAMETER[\"Z_Axis_Translation\",463.919],PARAMETER[\"X_Axis_Rotation\",5.1365988],PARAMETER[\"Y_Axis_Rotation\",1.4742],PARAMETER[\"Z_Axis_Rotation\",5.2970436],PARAMETER[\"Scale_Difference\",2.4232]]"; wkt = wkt.Replace("\"", "&quot;"); geotranwkt = geotranwkt.Replace("\"", "&quot;"); if (!String.IsNullOrEmpty(geotranwkt)) { sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" datumtransformstring=\"" + geotranwkt + "\" />"); sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" datumtransformstring=\"" + geotranwkt + "\" />"); } else { sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" />"); sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" />"); } //sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" datumtransformid=\"8415\" />"); //sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" datumtransformid=\"8415\" />"); } } } } sb.Append("<LAYERLIST>"); foreach (IWebServiceTheme theme in themes) { sb.Append("<LAYERDEF id='" + theme.LayerID + "' visible='" + (theme.Visible && !theme.Locked).ToString() + "'"); XmlNode xmlnode; if (LayerRenderer.TryGetValue(theme.LayerID, out xmlnode)) { sb.Append(">\n" + xmlnode.OuterXml + "\n</LAYERDEF>"); } else if (theme.FeatureRenderer != null) { string renderer = ObjectFromAXLFactory.ConvertToAXL(theme.FeatureRenderer); sb.Append(">\n" + renderer + "\n</LAYERDEF>"); } else { sb.Append("/>"); } } sb.Append("</LAYERLIST>"); sb.Append("</PROPERTIES>"); foreach (XmlNode additional in this.AppendedLayers) { if (additional != null) { sb.Append(additional.OuterXml); } } sb.Append("</GET_IMAGE>"); sb.Append("</REQUEST>"); sb.Append("</ARCXML>"); #if(DEBUG) gView.Framework.system.Logger.LogDebug("Start ArcXML SendRequest"); #endif await ArcIMSClass.LogAsync(display as IServiceRequestContext, "GetImage Request", server, service, sb); string resp = connector.SendRequest(sb, server, service); await ArcIMSClass.LogAsync(display as IServiceRequestContext, "GetImage Response", server, service, resp); #if(DEBUG) gView.Framework.system.Logger.LogDebug("ArcXML SendRequest Finished"); #endif XmlDocument doc = new XmlDocument(); doc.LoadXml(resp); XmlNode outputNode = doc.SelectSingleNode("//IMAGE/OUTPUT"); XmlNode envelopeNode = doc.SelectSingleNode("//IMAGE/ENVELOPE"); if (ModifyResponseOuput != null) { ModifyResponseOuput(this, new ModifyOutputEventArgs(outputNode)); } if (_image != null) { _image.Dispose(); _image = null; } #if(DEBUG) //gView.Framework.system.Logger.LogDebug("Start ArcXML DownloadImage"); #endif IBitmap bitmap = null; if (outputNode != null) { #if(DEBUG) gView.Framework.system.Logger.LogDebug("Start ArcXML DownloadImage"); #endif bitmap = WebFunctions.DownloadImage(outputNode/*_dataset._connector.Proxy*/); #if(DEBUG) gView.Framework.system.Logger.LogDebug("ArcXML DownloadImage Finished"); #endif } else { bitmap = null; } #if(DEBUG) //gView.Framework.system.Logger.LogDebug("ArcXML DownloadImage Finished"); #endif if (bitmap != null) { _image = new GeorefBitmap(bitmap); //_image.MakeTransparent(display.TransparentColor); if (envelopeNode != null && envelopeNode.Attributes["minx"] != null && envelopeNode.Attributes["miny"] != null && envelopeNode.Attributes["maxx"] != null && envelopeNode.Attributes["maxy"] != null) { _image.Envelope = new Envelope( Convert.ToDouble(envelopeNode.Attributes["minx"].Value.Replace(".", ",")), Convert.ToDouble(envelopeNode.Attributes["miny"].Value.Replace(".", ",")), Convert.ToDouble(envelopeNode.Attributes["maxx"].Value.Replace(".", ",")), Convert.ToDouble(envelopeNode.Attributes["maxy"].Value.Replace(".", ","))); } _image.SpatialReference = display.SpatialReference; if (AfterMapRequest != null) { AfterMapRequest(this, display, _image); } } return _image != null; } catch (Exception ex) { await ArcIMSClass.ErrorLog(context, "MapRequest", server, service, ex); return false; } } async public Task<bool> LegendRequest(gView.Framework.Carto.IDisplay display) { if (_dataset == null) { return false; } List<IWebServiceTheme> themes = Themes; if (themes == null) { return false; } #region Check for visible Layers bool visFound = false; foreach (IWebServiceTheme theme in themes) { if (!theme.Visible) { continue; } if (theme.MinimumScale > 1 && theme.MinimumScale > display.mapScale) { continue; } if (theme.MaximumScale > 1 && theme.MaximumScale < display.mapScale) { continue; } visFound = true; break; } if (!visFound) { if (_legend != null) { _legend.Dispose(); _legend = null; } return true; } #endregion string server = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "server"); string service = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "service"); string user = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "user"); string pwd = ConfigTextStream.ExtractValue(_dataset.ConnectionString, "pwd"); IServiceRequestContext context = display.Map as IServiceRequestContext; //if ((user == "#" || user == "$") && // context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null) //{ // string roles = String.Empty; // if (user == "#" && context.ServiceRequest.Identity.UserRoles != null) // { // foreach (string role in context.ServiceRequest.Identity.UserRoles) // { // if (String.IsNullOrEmpty(role)) continue; // roles += "|" + role; // } // } // user = context.ServiceRequest.Identity.UserName + roles; // pwd = context.ServiceRequest.Identity.HashedPassword; //} dotNETConnector connector = new dotNETConnector(); if (!String.IsNullOrEmpty(user) || !String.IsNullOrEmpty(pwd)) { connector.setAuthentification(user, pwd); } if (_dataset.State != DatasetState.opened) { if (!await _dataset.Open(context)) { return false; } } try { StringBuilder sb = new StringBuilder(); sb.Append("<?xml version='1.0' encoding='utf-8'?>"); sb.Append("<ARCXML version='1.1'>"); sb.Append("<REQUEST>"); sb.Append("<GET_IMAGE>"); sb.Append("<PROPERTIES>"); sb.Append("<ENVELOPE minx='" + display.Envelope.minx.ToString() + "' miny='" + display.Envelope.miny.ToString() + "' maxx='" + display.Envelope.maxx.ToString() + "' maxy='" + display.Envelope.maxy.ToString() + "' />"); sb.Append("<IMAGESIZE width='" + display.iWidth + "' height='" + display.iHeight + "' />"); sb.Append("<BACKGROUND color='255,255,255' transcolor='255,255,255' />"); sb.Append(_dataset._properties.PropertyString); sb.Append("<LAYERLIST>"); foreach (IWebServiceTheme theme in themes) { sb.Append("<LAYERDEF id='" + theme.LayerID + "' visible='" + (theme.Visible && !theme.Locked).ToString() + "'"); XmlNode xmlnode; if (LayerRenderer.TryGetValue(theme.LayerID, out xmlnode)) { sb.Append(">\n" + xmlnode.OuterXml + "\n</LAYERDEF>"); } else if (theme.FeatureRenderer != null) { string renderer = ObjectFromAXLFactory.ConvertToAXL(theme.FeatureRenderer); sb.Append(">\n" + renderer + "\n</LAYERDEF>"); } else { sb.Append("/>"); } } sb.Append("</LAYERLIST>"); sb.Append("<DRAW map=\"false\" />"); sb.Append("<LEGEND font=\"Arial\" autoextend=\"true\" columns=\"1\" width=\"165\" height=\"170\" backgroundcolor=\"255,255,255\" layerfontsize=\"11\" valuefontsize=\"10\">"); sb.Append("<LAYERS />"); sb.Append("</LEGEND>"); sb.Append("</PROPERTIES>"); foreach (XmlNode additional in this.AppendedLayers) { sb.Append(additional.OuterXml); } sb.Append("</GET_IMAGE>"); sb.Append("</REQUEST>"); sb.Append("</ARCXML>"); await ArcIMSClass.LogAsync(display as IServiceRequestContext, "GetLegend Request", server, service, sb); string resp = connector.SendRequest(sb, server, service); await ArcIMSClass.LogAsync(display as IServiceRequestContext, "GetLegend Response", server, service, resp); XmlDocument doc = new XmlDocument(); doc.LoadXml(resp); XmlNode output = doc.SelectSingleNode("//LEGEND"); if (ModifyResponseOuput != null) { ModifyResponseOuput(this, new ModifyOutputEventArgs(output)); } if (_legend != null) { _legend.Dispose(); } _legend = WebFunctions.DownloadImage(output); return true; } catch (Exception ex) { await ArcIMSClass.ErrorLog(context, "LegendRequest", server, service, ex); return false; } } GeorefBitmap IWebServiceClass.Image { get { return _image; } } GraphicsEngine.Abstraction.IBitmap IWebServiceClass.Legend { get { return _legend; } } public IEnvelope Envelope { get; private set; } public List<IWebServiceTheme> Themes { get { if (_clonedThemes != null) { return _clonedThemes; } if (_dataset != null) { return _dataset._themes; } return new List<IWebServiceTheme>(); } } internal ISpatialReference _sptatialReference; public ISpatialReference SpatialReference { get { return _sptatialReference; } set { _sptatialReference = value; if (_dataset != null) { _dataset.SetSpatialReference(value); } } } #endregion #region IClass Member public string Name { get { return _name; } } public string Aliasname { get { return _name; } } public IDataset Dataset { get { return _dataset; } } #endregion #region IClone Member public object Clone() { ArcIMSClass clone = new ArcIMSClass(_dataset); clone._clonedThemes = new List<IWebServiceTheme>(); var themes = (_clonedThemes != null) ? _clonedThemes : (_dataset?._themes ?? new List<IWebServiceTheme>()); foreach (IWebServiceTheme theme in themes) { if (theme == null || theme.Class == null) { continue; } clone._clonedThemes.Add(LayerFactory.Create(theme.Class, theme, clone) as IWebServiceTheme); } clone.AfterMapRequest = AfterMapRequest; clone.ModifyResponseOuput = ModifyResponseOuput; return clone; } #endregion private string Color2AXL(GraphicsEngine.ArgbColor col) { return col.R + "," + col.G + "," + col.B; } private List<XmlNode> _appendedLayers = new List<XmlNode>(); internal List<XmlNode> AppendedLayers { get { return _appendedLayers; } } private Dictionary<string, XmlNode> _layerRenderer = new Dictionary<string, XmlNode>(); internal Dictionary<string, XmlNode> LayerRenderer { get { return _layerRenderer; } } async public static Task LogAsync(IServiceRequestContext context, string header, string server, string service, string axl) { if (context == null || context.MapServer == null || context.MapServer.LoggingEnabled(loggingMethod.request_detail_pro) == false) { return; } StringBuilder sb = new StringBuilder(); sb.Append("\n"); sb.Append(header); sb.Append("\n"); sb.Append("Server: " + server + " Service: " + service); sb.Append("\n"); sb.Append(axl); await context.MapServer.LogAsync(context, "gView.Interoperability.ArcXML", loggingMethod.request_detail_pro, sb.ToString()); } async public static Task LogAsync(IServiceRequestContext context, string header, string server, string service, StringBuilder axl) { if (context == null || context.MapServer == null || context.MapServer.LoggingEnabled(loggingMethod.request_detail_pro) == false) { return; } await LogAsync(context, header, server, service, axl.ToString()); } async public static Task ErrorLog(IServiceRequestContext context, string header, string server, string service, Exception ex) { if (context == null || context.MapServer == null || context.MapServer.LoggingEnabled(loggingMethod.error) == false) { return; } StringBuilder msg = new StringBuilder(); if (ex != null) { msg.Append(ex.Message + "\n"); Exception inner = ex; while ((inner = inner.InnerException) != null) { msg.Append(inner.Message + "\n"); } } await context.MapServer.LogAsync(context, server + "-" + service + ": " + header, loggingMethod.error, msg.ToString() + ex.Source + "\n" + ex.StackTrace + "\n"); } } internal class ModifyOutputEventArgs : EventArgs { public XmlNode OutputNode = null; public ModifyOutputEventArgs(XmlNode outputNode) { OutputNode = outputNode; } } }
using System; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Sunnie.Models; using Sunnie.Repositories; // Responsible for handling HTTP requests from clients // Gets data and saves data namespace Sunnie.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] public class ProductController : BaseController { public ProductController( IProductRepository productRepository, IUserProfileRepository userProfileRepository ) { _productRepository = productRepository; _userProfileRepository = userProfileRepository; } [HttpGet] public IActionResult Get() { return Ok(_productRepository.GetAllProducts()); } [HttpGet("GetByUser")] public IActionResult GetByUser(int userId) { var userProducts = _productRepository.GetProductByUser(userId); if (userProducts == null) { return NotFound(); } return Ok(userProducts); } [HttpPost("add")] public IActionResult Post(Product product) { var user = GetCurrentUser(); if (user == null) return NotFound(); _productRepository.Add(product); return NoContent(); } [HttpDelete("delete/{productId}")] public IActionResult Delete(int productId) { _productRepository.Delete(productId); return NoContent(); } [HttpPut("update/{id}")] public IActionResult Put(int id, Product product) { if (id != product.Id) { return BadRequest(); } _productRepository.Update(product); return NoContent(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Threading; using IRAP.Client.Global; using IRAP.Global; using IRAP.Client.User; using IRAP.Client.SubSystem; namespace IRAP.Client.Global.GUI { public partial class frmCustomFuncBase : frmCustomBase { private static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private ucOptions barOptions = null; private bool refreshGUIOptions = false; protected string caption = ""; public frmCustomFuncBase() { InitializeComponent(); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") caption = "System information"; else caption = "系统信息"; } [Browsable(true), Description("界面激活后,是否需要刷新“选项一”和“选项二”")] public bool RefreshGUIOptions { get { return refreshGUIOptions; } set { refreshGUIOptions = value; } } public ucOptions Options { get { return barOptions; } set { barOptions = value; } } private void frmCustomFuncBase_Shown(object sender, EventArgs e) { lblFuncName.Text = Text; } private void frmCustomFuncBase_FormClosed(object sender, FormClosedEventArgs e) { if (barOptions != null) { barOptions.Visible = false; barOptions.ShowSwitchButton(); } } private void frmCustomFuncBase_Activated(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { if (barOptions != null) { barOptions.Visible = false; barOptions.ShowSwitchButton(); if (IRAPUser.Instance.RefreshGUIOptions) barOptions.RefreshOptions(); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } finally { WindowState = FormWindowState.Maximized; WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } }
using YourContacts.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YourContacts.Contracts { public interface IDataStore { List<Contact> FetchAll(); Contact Find(int ID); bool Create(Contact contactDetails); bool Update(Contact contactDetails); bool Delete(int ID); } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using AutoMapper; using Lottery.Cache; using Lottery.Controller; using Lottery.Entities; using Lottery.Enums; using Lottery.Interfaces; using Lottery.Interfaces.Analyzer; using Lottery.Interfaces.BonusCalculator; using Lottery.Interfaces.Controller; using Lottery.Interfaces.Services; using Lottery.Interfaces.Views; using Lottery.Repository.Context; using Lottery.Repository.Entities; using Lottery.Service; using Lottery.Service.Analyzer; using Lottery.Service.AutoMapper; using Lottery.Service.BonusCalculator; using Lottery.Service.Web; using Lottery.View; using Microsoft.Extensions.DependencyInjection; namespace StartUp { internal static class Program { private static IServiceProvider ServiceProvider { get; set; } /// <summary> /// 應用程式的主要進入點。 /// </summary> [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var services = new ServiceCollection(); services.AddScoped<IWebCralwer, WebCralwer>(); services.AddScoped<ICreateRecordService, CreateRecordService>(); services.AddScoped<ILotteryForm, LotteryFrom>(); services.AddScoped<ILotteryFormController, LotteryFormController>(); services.AddScoped<IExpectValueCalculator, ExpectValueCalculator>(); services.AddScoped<AnalyzerResolver>(resolver => analyzeType => { switch (analyzeType) { case AnalyzeType.AverageOfRecent: return new AverageAnalyzer(); case AnalyzeType.SpecialNumberRelated: return new SpecialRelatedAnalyzer(); case AnalyzeType.Random: return new RandomAnalyzer(); case AnalyzeType.FixedFirstSixth: return new FixedFirstSixthAnalyzer(); case AnalyzeType.MarkovChain: return new MarkovChainAnalyzer(); case AnalyzeType.DTMC: return new DTMCAnalyzer(); case AnalyzeType.Distance: return new DistanceAnalyzer(); case AnalyzeType.Fourier: return new FourierAnalyzer(); case AnalyzeType.Egg: return new EggAnalyzer(); case AnalyzeType.Count: return new CountAnalyzer(); case AnalyzeType.Wavelet: return new WaveletAnalyzer(); case AnalyzeType.SequenceOrder: return new SequenceOrderAnalyzer(); case AnalyzeType.DateNumber: return new DateNumberAnalyzer(); case AnalyzeType.Frequency: return new FrequencyAnalyzer(); case AnalyzeType.SequenceFirst: return new SequenceFirstAnalyzer(); case AnalyzeType.AverageDiffLog: return new AverageDiffLogAnalyzer(); case AnalyzeType.AverageDiffMul: return new AverageDiffMulAnalyzer(); case AnalyzeType.AverageDiff: return new AverageDiffAnalyzer(); default: throw new ArgumentOutOfRangeException(nameof(analyzeType), analyzeType, null); } }); services.AddScoped<BonusCalculatorResolver>(resolver => analyzeType => { switch (analyzeType) { case LottoType.PowerLottery: case LottoType.PowerLotterySequence: return new PowerLotteryCalculator(); case LottoType.BigLotto: case LottoType.Simulate: case LottoType.BigLottoSequence: return new BigLotteryBonusCalculator(); case LottoType.FivThreeNine: default: throw new ArgumentOutOfRangeException(nameof(analyzeType), analyzeType, null); } }); services.AddScoped<BigLotteryContext>(); services.AddScoped<BigLotterySequenceContext>(); services.AddScoped<PowerLotteryContext>(); services.AddScoped<PowerLotterySequenceContext>(); services.AddScoped<FiveThreeNineLotteryContext>(); services.AddScoped<SimulateLotteryContext>(); var configuration = new MapperConfiguration(cfg => { cfg.AddProfile<RecordProfile>(); }); var mapper = new Mapper(configuration); services.AddSingleton<IMapper>(mapper); var inMemory = new InMemory { BigLotteryRecords = mapper.Map<List<LotteryRecord>>(new BigLotteryContext().GetAll().ToList()), PowerLotteryRecords = mapper.Map<List<LotteryRecord>>(new PowerLotteryContext().GetAll().ToList()), PowerLotterySequenceRecords = mapper.Map<List<LotteryRecord>>(new PowerLotterySequenceContext().GetAll().ToList()), BigLotterySequenceRecords = mapper.Map<List<LotteryRecord>>(new BigLotterySequenceContext().GetAll().ToList()), FivThreeNineLotteryRecords = mapper.Map<List<LotteryRecord>>(new FiveThreeNineLotteryContext().GetAll().ToList()), SimulateLotteryRecords = mapper.Map<List<LotteryRecord>>(new SimulateLotteryContext().GetAll().ToList()) }; services.AddSingleton<IInMemory>(inMemory); ServiceProvider = services.BuildServiceProvider(); Application.Run((Form)ServiceProvider.GetService(typeof(ILotteryForm))); } } }
using DevanshAssociate_API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DevanshAssociate_API.Services { interface ICustomerDataService { List<CustomerData> getAllCustomerData(CustomerData request); List<CustomerData> getAllWithoutProcessStep(); CustomerData getCustomerDataById(CustomerData id); List<CustomerData> getCustomerReferenceDataById(CustomerData id); string postCustomerData(CustomerData request); string postCustomerReferenceData(CustomerData request); string updateCustormerProcessStepData(CustomerData request); } }
using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using HotelBooking.ViewModels; using HotelBooking.Models; using HotelBooking.ModelBuilders.Abstract; namespace HotelBooking.ModelBuilders.Concrete { public class RoomSearchBuilder : IRoomSearchBuilder { private readonly WdaContext wdaContext; public RoomSearchBuilder(WdaContext wdaContext) { this.wdaContext = wdaContext; } public IEnumerable<Room> Build(RoomSearchModel roomSearchModel) { IEnumerable<Room> results; if (roomSearchModel != null) { results = wdaContext.Room.Include(room => room.RoomType).AsQueryable(); results = results.Where(room => room.City.Equals(roomSearchModel.City)); results = results.Where(room => room.RoomTypeId.Equals(roomSearchModel.RoomType)); var bookings = wdaContext.Bookings.Where(booking => booking.CheckInDate.CompareTo(roomSearchModel.CheckOutDate) <= 0 && roomSearchModel.CheckInDate.CompareTo(booking.CheckOutDate) <= 0); results = results.Where(r => !bookings.Any(b => b.RoomId.Equals(r.RoomId))); if (roomSearchModel.GuestsCount != null) { results = results.Where(room => room.CountOfGuests >= roomSearchModel.GuestsCount); } if (roomSearchModel.PriceMin != null && roomSearchModel.PriceMin != 0) { results = results.Where(room => room.Price >= roomSearchModel.PriceMin); } if (roomSearchModel.PriceMax != null && roomSearchModel.PriceMax != 5000) { results = results.Where(room => room.Price <= roomSearchModel.PriceMax); } } else { results = wdaContext.Room; } results = results.OrderBy(room => room.Price); return results; } } }
namespace Models.ViewModels.Statistics { public class _BarChart { public int[] SumStartingBids { get; set; } public int[] SumMaxBids { get; set; } public int[] Difference { get; set; } public string[] XLabels { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abstraction.AbstractClass { public class Herbivora : Hewan { public override void Jenis() { Console.WriteLine("Hewan pemakan tumbuh tumbuhan."); Console.WriteLine("Hewan yang jinak ataupun juga ada yg ganas."); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Text; namespace testMonogame { class GameOverScreen { Texture2D texture; SpriteFont header; SpriteFont font; Rectangle blackBackground = new Rectangle(0, 0, 256, 175); Rectangle destRect = new Rectangle(130, 0, 256 * 2, 175 * 2); public GameOverScreen(Texture2D intexture, SpriteFont smallFont, SpriteFont bigFont) { texture = intexture; font = smallFont; header = bigFont; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, destRect, blackBackground, Color.Black); spriteBatch.DrawString(header, "Game Over", new Vector2(200, 0), Color.White); spriteBatch.DrawString(font, "Press any button to continue", new Vector2(300, 100), Color.White); } public void Update(GameManager game) { //NA } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using CyberSoldierServer.Data; using CyberSoldierServer.Dtos.EjectDtos; using CyberSoldierServer.Dtos.InsertDtos; using CyberSoldierServer.Models.Auth; using CyberSoldierServer.Models.PlayerModels; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CyberSoldierServer.Controllers { [Route("api/[controller]")] public class PlayerController : AuthApiController { private readonly CyberSoldierContext _dbContext; private readonly UserManager<AppUser> _userManager; private readonly IMapper _mapper; public PlayerController(CyberSoldierContext dbContext, IMapper mapper, UserManager<AppUser> userManager) { _dbContext = dbContext; _mapper = mapper; _userManager = userManager; } [HttpPost("AddGems/{gemId}")] public async Task<IActionResult> AddGem(int gemId) { var gemPack = await _dbContext.GemPacks.FirstOrDefaultAsync(g => g.Id == gemId); if (gemPack == null) return NotFound("Gem packs with this id not found"); var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); player.Gem += gemPack.Value; await _dbContext.SaveChangesAsync(); return Ok(); } [HttpPost("AddGemsUnLimit/{value}")] public async Task<IActionResult> AddGemUnLimit(int value) { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); player.Gem += value; await _dbContext.SaveChangesAsync(); return Ok(); } [HttpPost("AddTokenUnLimit/{value}")] public async Task<IActionResult> AddTokenUnLimit(int value) { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); player.Token += value; await _dbContext.SaveChangesAsync(); return Ok(); } [HttpGet("GetGems")] public async Task<IActionResult> GetGem() { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); var gem = player.Gem; return Ok(new {gem}); } [HttpPost("AddTokens/{tokenId}")] public async Task<IActionResult> AddToken(int tokenId) { var tokenPack = await _dbContext.TokenPacks.FirstOrDefaultAsync(t => t.Id == tokenId); if (tokenPack == null) return NotFound("Gem packs with this id not found"); var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); player.Token += tokenPack.Value; await _dbContext.SaveChangesAsync(); return Ok(); } [HttpGet("GetTokens")] public async Task<IActionResult> GetToken() { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); var token = player.Token; return Ok(new {token}); } [HttpPost("RemoveToken/{value}")] public async Task<IActionResult> RemoveToken(int value) { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); if (player.Token < value) return BadRequest("player does not have has that amount of token"); player.Token -= value; await _dbContext.SaveChangesAsync(); return Ok(new {player.Token}); } [HttpPost("RemoveGem/{value}")] public async Task<IActionResult> RemoveGem(int value) { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player == null) return NotFound("Player not found"); if (player.Gem < value) return BadRequest("player does not have has that amount of Gem"); player.Gem -= value; await _dbContext.SaveChangesAsync(); return Ok(new {player.Gem}); } [HttpPost("MakePlayerOffline")] public async Task<IActionResult> MakePlayerOffline() { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (!player.IsOnline) return BadRequest("User is already offline"); player.IsOnline = false; _dbContext.Players.Update(player); await _dbContext.SaveChangesAsync(); return Ok(); } [HttpPost("MakePlayerOnline")] public async Task<IActionResult> MakePlayerOnline() { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); if (player.IsOnline) return BadRequest("User is already online"); player.IsOnline = true; _dbContext.Players.Update(player); await _dbContext.SaveChangesAsync(); return Ok(); } [HttpGet("FindOpponent")] public async Task<ActionResult<PlayerDto>> FindOpponent() { var player = await _dbContext.Players.FirstOrDefaultAsync(p => p.UserId == UserId); var opponents = _dbContext.Players.Where(p => p.UserId != UserId && p.Level == player.Level) .Include(p => p.User) .Include(p => p.Camp) .ThenInclude(c => c.Dungeons) .ThenInclude(d => d.Slots) .ThenInclude(s => s.DefenceItem) .Include(p => p.Camp) .ThenInclude(c => c.Server) .Include(p => p.Camp) .ThenInclude(c => c.Cpus) .ThenInclude(c => c.Cpu) .Include(p => p.Weapons) .Include(p => p.Shields) .ToList(); if (opponents.Count == 0) return NotFound("There is no opponent"); Player opponent = null; if (opponents.Count > 1) { opponent = opponents.OrderBy(o => Guid.NewGuid()).First(); } else if (opponents.Count == 1) { opponent = opponents.First(); } var dto = _mapper.Map<PlayerDto>(opponent); return Ok(dto); } [HttpPost("AddAttacker")] public async Task<IActionResult> AddAttacker([FromBody] AttackerInsertDto dto) { var victim = await _dbContext.Players.FirstOrDefaultAsync(p => p.Id == dto.VictimId); if (victim == null) { return NotFound("Victim not found"); } var player = await _dbContext.Players.Where(p => p.UserId == UserId).Include(p=>p.Camp).FirstOrDefaultAsync(); if (dto.CpuId.HasValue) { var cpu = await _dbContext.ServerCpus.FirstOrDefaultAsync(c => c.Id == dto.CpuId); cpu.CampId = player.Camp.Id; } var attacker = new Attacker { PlayerId = victim.Id, AttackerPlayerId = player.Id, CpuId = dto.CpuId, DungeonCount = dto.DungeonCount }; await _dbContext.Attackers.AddAsync(attacker); await _dbContext.SaveChangesAsync(); return Ok(); } [HttpGet("GetAttackers")] public async Task<ActionResult<List<AttackerDto>>> GetAttackers() { var player = await _dbContext.Players.Where(p => p.UserId == UserId) .Include(p=>p.Attackers) .ThenInclude(a=>a.Cpu) .FirstOrDefaultAsync(); if (player.Attackers.Count == 0) return NotFound("There is no attacker"); var dtos = new List<AttackerDto>(player.Attackers.Count); foreach (var attacker in player.Attackers) { var ap = await _dbContext.Players.Where(p => p.Id == attacker.AttackerPlayerId) .Include(p=>p.User) .FirstOrDefaultAsync(); var ad = new AttackerDto { Cpu = _mapper.Map<CampCpuDto>(attacker.Cpu), AttackerId = ap.Id, Level = ap.Level, UserName = ap.User.UserName, DungeonCount = attacker.DungeonCount }; dtos.Add(ad); } return Ok(dtos); } [HttpPost("Attack/{id}")] public async Task<ActionResult<PlayerDto>> Attack(int id) { var victim = await _dbContext.Players.FirstOrDefaultAsync(p => p.Id == id); if (victim == null) return NotFound("Player not found"); var dto = _mapper.Map<PlayerDto>(victim); return Ok(dto); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class gift : MonoBehaviour { [SerializeField] public float screenX; public float screenY; private int count = 0; private GameObject[] gifts; // Use this for initialization void Start () { this.randomLocation (); /* this.gifts = new GameObject[3]; foreach (Transform i in this.transform) { this.gifts [this.count] = i.gameObject; this.count++; }*/ } void randomLocation(){ var tempx = Random.Range (-5, 5) + Random.value; var tempy = Random.Range (-3, 3) + Random.value; this.transform.position = new Vector3(tempx, tempy,0f); } void OnCollisionEnter2D(){ Debug.Log ("destroy"); Destroy (this.gameObject); } // Update is called once per frame void Update () { } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using senai.inlock.webApi_.Domains; using senai.inlock.webApi_.Interfaces; using senai.inlock.webApi_.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace senai.inlock.webApi_.Controllers { [Produces("application/json")] [Route("api/[controller]")] [ApiController] public class EstudiosController : ControllerBase { private IEstudioRepository _estudioRepository { get; set; } public EstudiosController() { _estudioRepository = new EstudioRepository(); } /// <summary> /// Lista Estudio /// </summary> /// <returns>Uma lista de estudios</returns> [HttpGet] public IActionResult Get() { List<EstudioDomain> listaEstudio = _estudioRepository.ListarTodos(); return Ok(listaEstudio); } /// <summary> /// Cadastra um novo estudio /// </summary> /// <param name="novoEstudio">Objeto com os dados do novo estudio</param> /// <returns>Um status code 201</returns> [HttpPost] public IActionResult Post(EstudioDomain novoEstudio) { _estudioRepository.Cadastrar(novoEstudio); return StatusCode(201); } /// <summary> /// Atualiza um estudio pelo id /// </summary> /// <param name="estudioAtuali">Objeto do estudio atualizado</param> /// <returns>Um status code</returns> [HttpPut] public IActionResult PutIdBody(EstudioDomain estudioAtuali) { EstudioDomain estudioBuscado = _estudioRepository.BuscarPorId(estudioAtuali.idEstudio); if (estudioBuscado != null) { try { _estudioRepository.AtualizarIdCorpo(estudioAtuali); return NoContent(); } catch (Exception erro) { return BadRequest(erro); } } return NotFound(new { mensagem = "Estudio nao encontrado!", }); } /// <summary> /// Deleta um estudio que existe /// </summary> /// <param name="id">id do estudio deletado</param> /// <returns>status code </returns> [HttpDelete("{id}")] public IActionResult Delete(int id) { _estudioRepository.Deletar(id); return StatusCode(204); } } }
using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Dominio.Interfaces.Servicos { public interface IServicoNomes: IServicoBase<Nomes> { List<Nomes> ObterNomesPorIdAto(int IdAto); List<Nomes> ObterNomesPorNome(string nome); List<Nomes> ObterNomesPorIdProcuracao(int IdProcuracao); List<Nomes> ObterNomesPorIdTestamento(int IdTestamento); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_IssPrefeitura.Dominio.Entities { public class ApuracaoIss { public int ApuracaoIssId { get; set; } public DateTime DataFechamento { get; set; } public int Mes { get; set; } public string NomeMes { get; set; } public int Ano { get; set; } public string Periodo { get; set; } public int Livro { get; set; } public int Folha { get; set; } public string Recibo { get; set; } public int Serie { get; set; } public int Numero { get; set; } public string Cancelado { get; set; } public decimal Faturamento { get; set; } public decimal FundosEspeciais { get; set; } public decimal BaseCalculo { get; set; } public float Aliquota { get; set; } public decimal ValorIssRecolhido { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIShipRecharge : MonoBehaviour { [SerializeField] private float TransparencyWhenUsed = 0.2f; [SerializeField] private List<Image> FullRechargesObj = new List<Image>(); private int CurrentNumRecharges = 0; private Color DefaultColor = new Color(); private Color UsedColor = new Color(); void Start() { if (!ShipUnit.Instance) { Debug.LogError("No Ship Instance found in " + this + "UIShipPropulsion"); Destroy(this); return; } if (FullRechargesObj.Count > 1) { DefaultColor = FullRechargesObj[0].color; } UsedColor = DefaultColor; UsedColor.a = TransparencyWhenUsed; UpdateRechargesVisibility(); } private void Update() { if (!ShipUnit.Instance) { enabled = false; return; } if (CurrentNumRecharges != ShipUnit.Instance.ChargerComp.CurrentNumRecharge) { UpdateRechargesVisibility(); } } void UpdateRechargesVisibility() { CurrentNumRecharges = ShipUnit.Instance.ChargerComp.CurrentNumRecharge; for (int r = 0; r < FullRechargesObj.Count; ++r) { FullRechargesObj[r].color = (r < CurrentNumRecharges) ? DefaultColor : UsedColor; } } }
namespace AI2048.AI.Searchers.Models { using System.Collections.Generic; using System.Globalization; using System.Text; using AI2048.Game; public class SearchResult { public LogarithmicGrid RootGrid { get; set; } public Move BestMove { get; set; } public double BestMoveEvaluation { get; set; } public IDictionary<Move, double> MoveEvaluations { get; set; } public string SearcherName { get; set; } public SearchStatistics SearchStatistics { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine(this.RootGrid.ToString()); sb.AppendLine($"Search result for searcher {this.SearcherName}:"); sb.AppendLine($"Best move: {this.BestMove}"); sb.AppendLine($"Best move score: {this.BestMoveEvaluation}"); sb.Append(EvaluationToString(this.MoveEvaluations)); sb.Append(this.SearchStatistics); return sb.ToString(); } private static string EvaluationToString(IDictionary<Move, double> evaluationDictionary) { var sb = new StringBuilder(); sb.AppendLine("Evalution results:"); sb.AppendFormat( "Left: {0}", evaluationDictionary.ContainsKey(Move.Left) ? evaluationDictionary[Move.Left].ToString(CultureInfo.InvariantCulture) : "null").AppendLine(); sb.AppendFormat( "Right: {0}", evaluationDictionary.ContainsKey(Move.Right) ? evaluationDictionary[Move.Right].ToString(CultureInfo.InvariantCulture) : "null").AppendLine(); sb.AppendFormat( "Up: {0}", evaluationDictionary.ContainsKey(Move.Up) ? evaluationDictionary[Move.Up].ToString(CultureInfo.InvariantCulture) : "null").AppendLine(); sb.AppendFormat( "Down: {0}", evaluationDictionary.ContainsKey(Move.Down) ? evaluationDictionary[Move.Down].ToString(CultureInfo.InvariantCulture) : "null").AppendLine(); return sb.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Trap : MonoBehaviour { public float damagePerTick; public int ticks; public int duration; public LayerMask enemies; private float tickTimer; private float nextTickTime; private bool activated; private float timeLeft; private void Start() { activated = false; nextTickTime = duration / ticks; tickTimer = nextTickTime; timeLeft = 0; if (ticks == 1 && duration > 1) duration = 1; } private void Update() { if (!activated) { RaycastHit[] BoxCastHit = Physics.BoxCastAll(transform.position, transform.localScale, transform.up, transform.localRotation, 4, enemies, QueryTriggerInteraction.Collide); if (BoxCastHit.Length > 0) activated = true; } if (activated && ticks > 0) { timeLeft += Time.deltaTime; if (timeLeft >= tickTimer) { DamageEnemies(); } } if (ticks <= 0) Destroy(gameObject); } private void DamageEnemies() { RaycastHit[] BoxCastHit = Physics.BoxCastAll(transform.position, transform.localScale, transform.up, transform.localRotation, 4, enemies, QueryTriggerInteraction.Collide); foreach (RaycastHit enemyHit in BoxCastHit) { enemyHit.transform.GetComponent<Health>().AddDamage((int)damagePerTick); } ticks--; tickTimer += nextTickTime; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Globalization; using System.Collections.Specialized; using System.IO; using System.Xml; namespace WindowsFA { public partial class FormFA : Form { protected String formTitle = ""; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); TVM tvm = new TVM(); Boolean xmlHasChanged = false; string xmlFilename = ""; string xmloutput=""; NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; public FormFA() { InitializeComponent(); this.Text = formTitle; } private void FormFA_Load(object sender, EventArgs e) { // toolTip.IsBalloon = true; } public void setformTitle(String s){ this.formTitle=s; } private void ShowNewForm_TVM(object sender, EventArgs e) { tVMToolStripMenuItem_Click(sender, e); } private void ShowNewForm_CFLO(object sender, EventArgs e) { cFLOToolStripMenuItem_Click(sender, e); } private void ShowNewForm_TVMMortgage(object sender, EventArgs e) { tVMMortgageToolStripMenuItem_Click(sender, e); } public virtual void SaveXml(bool confirm) { if (xmlHasChanged) { if (confirm) { if (MessageBox.Show("Do you want to save the changes you made to your worksheet?", "Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes) { return; } } if (xmlFilename == "") { mainSaveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); mainSaveFileDialog.Filter = "TVM Files (*.tvm)|*.tvm|CFLO Files (*.cfo)|*.cfo|All Files (*.*)|*.*"; if (mainSaveFileDialog.ShowDialog() == DialogResult.OK) { xmlFilename = mainSaveFileDialog.FileName; } else { return; } } using (StreamWriter sw = new StreamWriter(xmlFilename, false, Encoding.Unicode)) { StringBuilder stringb = new StringBuilder(); XmlWriterSettingsLibrary settings = new XmlWriterSettingsLibrary(); using (XmlWriter writer = XmlWriter.Create(stringb, settings.maindocxmlsettings)) { /* * Sample document * <?xml version="1.0" encoding="utf-16"?> <FA> <TVM> <N isYear="true">30.00</N> <PV>$600,000.00</PV> <PMT>($3,597.30)</PMT> <FV>$0.00</FV> <I>6.00</I> <P isEnd="true">12</P> </TVM> </FA> */ // Write XML data. //beginning of TVM specific code /* writer.WriteStartElement("FA"); writer.WriteStartElement("TVM"); writer.WriteStartElement("N"); string isYearstring = isYear ? "true" : "false"; writer.WriteAttributeString("isYear", isYearstring); writer.WriteString(textBoxN.Text); writer.WriteEndElement(); writer.WriteStartElement("PV"); writer.WriteString(textBoxPV.Text); writer.WriteEndElement(); writer.WriteStartElement("PMT"); writer.WriteString(textBoxPMT.Text); writer.WriteEndElement(); writer.WriteStartElement("FV"); writer.WriteString(textBoxFV.Text); writer.WriteEndElement(); writer.WriteStartElement("I"); writer.WriteString(textBoxI.Text); writer.WriteEndElement(); writer.WriteStartElement("P"); string isEndstring = isEnd ? "true" : "false"; writer.WriteAttributeString("isEnd", isEndstring); writer.WriteString(textBoxP.Text); writer.WriteEndElement(); writer.WriteEndElement(); //TVM writer.WriteEndElement(); //FA writer.Flush(); */ //end of TVM specific code } xmloutput = stringb.ToString(); sw.WriteLine(xmloutput); } this.Text = formTitle + " - " + xmlFilename; xmlHasChanged = false; } } public virtual void OpenFile(object sender, EventArgs e) { SaveXml(true); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); openFileDialog.Filter = "TVM Files (*.tvm)|*.tvm|CFLO Files (*.cfo)|*.cfo|All Files (*.*)|*.*"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { try { xmlFilename = openFileDialog.FileName; xmlHasChanged = true; doc.Load(xmlFilename); XmlNode root = doc.DocumentElement; //beginning of TVM specific code /* XmlNodeList fa_tvm_n = doc.GetElementsByTagName("N"); XmlNodeList fa_tvm_pv = doc.GetElementsByTagName("PV"); XmlNodeList fa_tvm_pmt = doc.GetElementsByTagName("PMT"); XmlNodeList fa_tvm_fv = doc.GetElementsByTagName("FV"); XmlNodeList fa_tvm_i = doc.GetElementsByTagName("I"); XmlNodeList fa_tvm_p = doc.GetElementsByTagName("P"); textBoxN.Text = fa_tvm_n[0].InnerText; XmlAttribute isYearatt = doc.GetElementsByTagName("N")[0].Attributes[0]; if (isYearatt.InnerText == "true") { radioButtonYears.Checked = true; radioButtonPeriods.Checked = false; } else { radioButtonPeriods.Checked = true; radioButtonYears.Checked = false; } textBoxPV.Text = fa_tvm_pv[0].InnerText; textBoxPMT.Text = fa_tvm_pmt[0].InnerText; textBoxFV.Text = fa_tvm_fv[0].InnerText; textBoxI.Text = fa_tvm_i[0].InnerText; textBoxP.Text = fa_tvm_p[0].InnerText; XmlAttribute isEndatt = doc.GetElementsByTagName("P")[0].Attributes[0]; if (isEndatt.InnerText == "true") { radioButtonEnd.Checked = true; radioButtonBegin.Checked = false; } else { radioButtonBegin.Checked = true; radioButtonEnd.Checked = false; } tvm.setCalculating(TVMObjects.OPEN); recalc(TVMObjects.OPEN); /* * Sample tvm file for loading * <?xml version="1.0" encoding="utf-16"?> <FA> <TVM> <N isYear="true">30.00</N> <PV>$300,000.00</PV> <PMT>($1,798.65)</PMT> <FV>$0.00</FV> <I>6.00</I> <P isEnd="true">12</P> </TVM> </FA> * */ //end of TVM specific code this.Text = formTitle + " - " + xmlFilename; xmlHasChanged = false; } catch (XmlException) { MessageBox.Show("Invalid file.\nThe file you have opened is not valid for this application.", "Invalid file"); } } } public virtual void saveToolStripMenuItem_Click(object sender, EventArgs e) { SaveXml(false); } public virtual void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { xmlFilename = ""; xmlHasChanged = true; SaveXml(false); } public virtual void ExitToolsStripMenuItem_Click(object sender, EventArgs e) { if (xmlHasChanged) { SaveXml(true); } Application.Exit(); } void undoToolStripMenuItem_Click(object sender, System.EventArgs e) { throw new System.Exception("The method or operation is not implemented."); } void redoToolStripMenuItem_Click(object sender, System.EventArgs e) { throw new System.Exception("The method or operation is not implemented."); } private void CutToolStripMenuItem_Click(object sender, EventArgs e) { // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard Clipboard.Clear(); Clipboard.SetText(this.ActiveControl.Text); this.ActiveControl.Text = ""; } private void CopyToolStripMenuItem_Click(object sender, EventArgs e) { // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard Clipboard.Clear(); Clipboard.SetText(this.ActiveControl.Text); } private void PasteToolStripMenuItem_Click(object sender, EventArgs e) { // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard. this.ActiveControl.Text = Clipboard.GetText(); } private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e) { toolStrip.Visible = toolBarToolStripMenuItem.Checked; } private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e) { statusStrip.Visible = statusBarToolStripMenuItem.Checked; } private void CascadeToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.Cascade); } private void TileVerticleToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.TileVertical); } private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.TileHorizontal); } private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.ArrangeIcons); } private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e) { foreach (Form childForm in MdiChildren) { childForm.Close(); } } private void tVMToolStripMenuItem_Click(object sender, EventArgs e) { // Create a new instance of the child form. Form childForm = new FormTVM(); // Make it a child of this MDI form before showing it. // childForm.MdiParent = this; // childForm.Text = "Time Value of Money " + childFormNumber++; childForm.Show(); } private void cFLOToolStripMenuItem_Click(object sender, EventArgs e) { // Create a new instance of the child form. Form childForm = new FormCFLO(); // Make it a child of this MDI form before showing it. // childForm.MdiParent = this; // childForm.Text = "Cash Flow " + childFormNumber++; childForm.Show(); } private void tVMMortgageToolStripMenuItem_Click(object sender, EventArgs e) { // Create a new instance of the child form. Form childForm = new FormTVMMortgage(); // Make it a child of this MDI form before showing it. // childForm.MdiParent = this; // childForm.Text = "Mortgage Payment Calculator " + childFormNumber++; childForm.Show(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { Form aboutForm = new AboutBox1(); aboutForm.Show(); } private void changeOpacityToolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem menuItem = (ToolStripMenuItem)sender; double opacity = Convert.ToDouble(menuItem.Tag.ToString()); this.Opacity = opacity; // The Opacity settings are exclusive of each other. Ensure only the current // setting is checked. ToolStripMenuItem menuChangeOpacity = (ToolStripMenuItem)viewMenu.DropDownItems[2]; foreach (ToolStripMenuItem item in menuChangeOpacity.DropDownItems) { item.Checked = false; } menuItem.Checked = true; } public virtual void saveToolStripButton_Click(object sender, EventArgs e) { SaveXml(false); } } }
using System.ComponentModel.DataAnnotations.Schema; namespace eMAM.Data.Models { public class Attachment { public int Id { get; set; } public string FileName { get; set; } public double FileSizeInMb { get; set; } public int EmailId { get; set; } public Email Email { get; set; } } }
using UnityEngine.Audio; using UnityEngine; using System; using System.Collections; public class AudioManager : MonoBehaviour { public AudioMixerGroup audioMixer; public Sound[] sounds; private Sound currentTheme ; public static AudioManager instance; void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); } DontDestroyOnLoad(gameObject); foreach (Sound s in sounds) { s.source = gameObject.AddComponent<AudioSource>(); s.source.clip = s.clip; s.source.volume = s.volume; s.source.pitch = s.pitch; s.source.loop = s.loop; s.source.outputAudioMixerGroup = audioMixer; } } private void Start() { } public void FadeOutTheme() { if (currentTheme != null) { float startVolume = currentTheme.source.volume; StartCoroutine(FadeOut(startVolume)); } } IEnumerator FadeOut(float startVolume) { while (currentTheme.source.volume > 0) { currentTheme.source.volume -= startVolume * Time.deltaTime ; yield return null; } currentTheme.source.Stop(); currentTheme.source.volume = startVolume; } public void PlayTheme(string themeName) { Sound s = Array.Find(sounds, sound => sound.SoundName == themeName); if (s == null) { Debug.LogWarning("Sound: " + themeName + " not found"); } StartCoroutine(DelayTheme(s, themeName)); } private IEnumerator DelayTheme(Sound theme, string themeName) { //Debug.Log("delay theme"); yield return null ; currentTheme = theme; Play(themeName); } public void PlayTownTheme() { if (StoryManager.instance.GetLevel() == 0) { PlayTheme("TownTheme1"); } else { PlayTheme("TownTheme2"); } } public void Play(string name) { Sound s = Array.Find(sounds, sound => sound.SoundName == name); if (s == null) { Debug.LogWarning("Sound: " + name + " not found"); } if (s != null) { s.source.Play(); } } public void PauseTheme() { currentTheme.source.Pause(); } public void UnPauseTheme() { currentTheme.source.UnPause(); } public void Pause(string name) { Sound s = Array.Find(sounds, sound => sound.SoundName == name); if (s == null) { Debug.LogWarning("Sound: " + name + " not found"); } s.source.Pause(); } public void UnPause(string name) { Sound s = Array.Find(sounds, sound => sound.SoundName == name); if (s == null) { Debug.LogWarning("Sound: " + name + " not found"); } s.source.UnPause(); } }
using TMPro; using UnityEngine; using UnityEngine.UI; using System.IO.Ports; using System; using UnityEngine.SceneManagement; public class CanvasScript : MonoBehaviour { [SerializeField] TMP_Dropdown comportDropdown, baudRateDropdown; [SerializeField] string[] comportNames; [SerializeField] Button connect, startGame; [SerializeField] GameObject portPanel; [SerializeField] TextMeshProUGUI portPanelText; Color textColor; void Start() { portPanelText = portPanel.GetComponentInChildren<TextMeshProUGUI>(); textColor = portPanelText.color; portPanel.SetActive(false); comportNames = SerialPort.GetPortNames(); comportDropdown = GetComponentInChildren<TMP_Dropdown>(); foreach (string comportName in comportNames) { comportDropdown.options.Add(new TMP_Dropdown.OptionData(comportName)); } connect.gameObject.SetActive(false); startGame.gameObject.SetActive(false); baudRateDropdown.gameObject.SetActive(false); EventManager.Instance.onPortOpenResult.AddListener(ConnectionResult); comportDropdown.onValueChanged.AddListener(PortSelected); baudRateDropdown.onValueChanged.AddListener(BrSelected); connect.onClick.AddListener(ConnectPort); startGame.onClick.AddListener(StartGame); } private void StartGame() { SceneManager.LoadScene("Game"); } private void ConnectionResult(GameObject sender, CustomEventArgs args) { if(args.Successful) { portPanelText.color = textColor; print("Connection sucess!"); portPanelText.text = "Port Successfully Connected!"; portPanel.SetActive(true); startGame.gameObject.SetActive(true); } else { portPanelText.color = Color.red; print("Port Already Open, Try a different one"); portPanelText.text = "It looks like the port is already Open, Try a different one"; portPanel.SetActive(true); } } private void BrSelected(int arg) { portPanel.SetActive(false); if (arg != 0) { connect.gameObject.SetActive(true); } else { connect.gameObject.SetActive(false); } } private void ConnectPort() { string portName = comportDropdown.options[comportDropdown.value].text; int baudRate = int.Parse(baudRateDropdown.options[baudRateDropdown.value].text); print(portName); print(baudRate); EventManager.Instance.onPortTryOpen.Invoke(gameObject, new CustomEventArgs(portName, baudRate)); } // Update is called once per frame void Update() { } private void PortSelected(int arg) { portPanel.SetActive(false); if (arg != 0) { baudRateDropdown.gameObject.SetActive(true); } else { baudRateDropdown.gameObject.SetActive(false); connect.gameObject.SetActive(false); } } }
using DevExpress.XtraEditors; using DevExpress.XtraTab; using Galeri.Business.Abstract; using Galeri.Business.Ninject; using Galeri.Entities.Concrete; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Galeri.DesktopUI.Formlar { public partial class MainForm : Form { IMarkaService markaServis; IModelService modelServis; ITasitService aracServis; IKategoriService kategoriServis; IHasarKayitService hasarKayitServis; IFotografService fotografServis; IYorumService yorumServis; int id; string p1, p2, p3, p4, p11, p22, p33, p44; public MainForm() { InitializeComponent(); markaServis = InstanceFactory.GetInstance<IMarkaService>(); modelServis = InstanceFactory.GetInstance<IModelService>(); aracServis = InstanceFactory.GetInstance<ITasitService>(); kategoriServis = InstanceFactory.GetInstance<IKategoriService>(); hasarKayitServis = InstanceFactory.GetInstance<IHasarKayitService>(); fotografServis = InstanceFactory.GetInstance<IFotografService>(); yorumServis = InstanceFactory.GetInstance<IYorumService>(); } private void aracPageClick(object sender, EventArgs e) { SayfalamaControl.SelectedTabPage = aracPage; } private void MarkaPageLoad() { SayfalamaControl.SelectedTabPage = markaPage; markaGridControl.DataSource = from x in markaServis.GetEntities(null) select new { x.Id, x.MarkaAdi }; id = -1; markaAdiTxt.Text = ""; } private void ModelPageLoad() { SayfalamaControl.SelectedTabPage = modelPage; modelGridControl.DataSource = from x in modelServis.GetEntities(null) select new { x.Id, x.ModelAdi, x.Yil, x.KasaTipi, x.MotorGucu, x.MotorHacmi, x.Cekis, x.AzamiSurat, x.BagajKapasitesi, x.Vites, x.Yakit, x.MarkaId }; markaLookUp.Properties.DataSource = from x in markaServis.GetEntities(null) select new { MarkaId = x.Id, MarkaAdi = x.MarkaAdi }; id = -1; vitesTxt.Text = ""; yilTxt.Text = ""; kasaTipiTxt.Text = ""; motorGucuTxt.Text = ""; motorHacmiTxt.Text = ""; cekisTxt.Text = ""; azamiSuratTxt.Text = ""; bagajKapasitesiTxt.Text = ""; markaLookUp.Text = ""; yakitTxt.Text = ""; modelAdiTxt.Text = ""; } private void PageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e) { XtraTabControl pageControl = (XtraTabControl)sender; if (pageControl.SelectedTabPage != null) { switch (pageControl.SelectedTabPage.Name) { case "markaPage": MarkaPageLoad(); break; case "modelPage": ModelPageLoad(); break; case "kategoriPage": KategoriPageLoad(); break; case "aracPage": AracPageLoad(); break; case "hasarKayitPage": HasarKayitPageLoad(); break; case "yorumPage": YorumPageLoad(); break; case "cikisPage": DialogResult result = MessageBox.Show("Sistemden çıkmak istediğinize emin misiniz?", "Bilgilendirme", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if(result == DialogResult.Yes) { Application.Exit(); } else { SayfalamaControl.SelectedTabPage = null; } break; case "fotografPage": FotografPageLoad(); break; } } } private void MainForm_Load(object sender, EventArgs e) { SayfalamaControl.SelectedTabPage = null; } private void MarkaGrid_Click(object sender, EventArgs e) { id = int.Parse(gridView1.GetFocusedRowCellValue("Id").ToString()); markaAdiTxt.Text = gridView1.GetFocusedRowCellValue("MarkaAdi").ToString(); } private void MarkaPageVtBtns_Click(object sender, EventArgs e) { SimpleButton buton = (SimpleButton) sender; switch (buton.Text.ToString()) { case "Ekle": try { markaServis.Add(new Marka { MarkaAdi = markaAdiTxt.Text.ToString() }); MessageBox.Show("Marka başarıyla eklendi.","Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); MarkaPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Güncelle": try { markaServis.Update(new Marka { Id = id, MarkaAdi = markaAdiTxt.Text.ToString() }); MessageBox.Show("Marka başarıyla güncellendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); MarkaPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Sil": try { markaServis.Delete(new Marka { Id = id }); MessageBox.Show("Marka başarıyla silindi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); MarkaPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } private void ModelVtButtons_Click(object sender, EventArgs e) { SimpleButton btn = (SimpleButton)sender; switch (btn.Text) { case "Ekle": try { modelServis.Add(new Model { Yil = short.Parse(yilTxt.Text.ToString()), KasaTipi = kasaTipiTxt.Text.ToString(), MotorGucu = short.Parse(motorGucuTxt.Text.ToString()), MotorHacmi = short.Parse(motorHacmiTxt.Text.ToString()), Cekis = cekisTxt.Text.ToString(), AzamiSurat = short.Parse(azamiSuratTxt.Text.ToString()), BagajKapasitesi = short.Parse(bagajKapasitesiTxt.Text.ToString()), Yakit = yakitTxt.Text.ToString(), ModelAdi = modelAdiTxt.Text.ToString(), MarkaId = int.Parse(markaLookUp.EditValue.ToString()), Vites = vitesTxt.Text.ToString() }); MessageBox.Show("Model başarıyla eklendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); ModelPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Güncelle": try { modelServis.Update(new Model { Id = id, Yil = short.Parse(yilTxt.Text.ToString()), KasaTipi = kasaTipiTxt.Text.ToString(), MotorGucu = short.Parse(motorGucuTxt.Text.ToString()), MotorHacmi = short.Parse(motorHacmiTxt.Text.ToString()), Cekis = cekisTxt.Text.ToString(), AzamiSurat = short.Parse(azamiSuratTxt.Text.ToString()), BagajKapasitesi = short.Parse(bagajKapasitesiTxt.Text.ToString()), Yakit = yakitTxt.Text.ToString(), ModelAdi = modelAdiTxt.Text.ToString(), MarkaId = int.Parse(markaLookUp.EditValue.ToString()), Vites = vitesTxt.Text.ToString() }); MessageBox.Show("Model başarıyla güncellendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); ModelPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Sil": try { modelServis.Delete(new Model { Id = id }); MessageBox.Show("Model başarıyla silindi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); ModelPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } private void ModelGridClick(object sender, EventArgs e) { int markaId = Convert.ToInt32(gridView2.GetFocusedRowCellValue("MarkaId").ToString()); id = int.Parse(gridView2.GetFocusedRowCellValue("Id").ToString()); yilTxt.Text = gridView2.GetFocusedRowCellValue("Yil").ToString(); kasaTipiTxt.Text = gridView2.GetFocusedRowCellValue("KasaTipi").ToString(); motorGucuTxt.Text = gridView2.GetFocusedRowCellValue("MotorGucu").ToString(); cekisTxt.Text = gridView2.GetFocusedRowCellValue("Cekis").ToString(); azamiSuratTxt.Text = gridView2.GetFocusedRowCellValue("AzamiSurat").ToString(); bagajKapasitesiTxt.Text = gridView2.GetFocusedRowCellValue("BagajKapasitesi").ToString(); markaLookUp.Text = markaServis.GetEntity(c => c.Id == markaId).MarkaAdi; yakitTxt.Text = gridView2.GetFocusedRowCellValue("Yakit").ToString(); modelAdiTxt.Text = gridView2.GetFocusedRowCellValue("ModelAdi").ToString(); vitesTxt.Text = gridView2.GetFocusedRowCellValue("Vites").ToString(); motorHacmiTxt.Text = gridView2.GetFocusedRowCellValue("MotorHacmi").ToString(); } private void KategoriVtBtns_Click(object sender, EventArgs e) { SimpleButton buton = (SimpleButton)sender; switch (buton.Text.ToString()) { case "Ekle": try { kategoriServis.Add(new Kategori { KategoriAdi = kategoriAdTxt.Text.ToString() }); MessageBox.Show("Kategori başarıyla eklendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); KategoriPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Güncelle": try { kategoriServis.Update(new Kategori { Id = id, KategoriAdi = kategoriAdTxt.Text.ToString() }); MessageBox.Show("Kategori başarıyla güncellendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); KategoriPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Sil": try { kategoriServis.Delete(new Kategori { Id = id }); MessageBox.Show("Kategori başarıyla silindi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); KategoriPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } private void KategoriGrid_Click(object sender, EventArgs e) { id = int.Parse(gridView3.GetFocusedRowCellValue("Id").ToString()); kategoriAdTxt.Text = gridView3.GetFocusedRowCellValue("KategoriAdi").ToString(); } private void KategoriPageLoad() { SayfalamaControl.SelectedTabPage = kategoriPage; kategoriGridControl.DataSource = from x in kategoriServis.GetEntities(null) select new { x.Id, x.KategoriAdi }; id = -1; kategoriAdTxt.Text = ""; } private void AracPageLoad() { SayfalamaControl.SelectedTabPage = aracPage; tasitGridControl.DataSource = from x in aracServis.GetEntities(null) select new { x.Id, x.Fiyat, x.Garanti, x.Takas, x.Durum, x.Renk, x.Plaka, x.Aciklama, x.ModelId, x.KategoriId, x.TasitBaslik, x.Kilometre }; modelLook.Properties.DataSource = from x in modelServis.GetEntities(null) select new { ModelId = x.Id, ModelAdi = x.ModelAdi }; kategoriLook.Properties.DataSource = from x in kategoriServis.GetEntities(null) select new { KategoriAdi = x.KategoriAdi, KategoriId = x.Id }; id = -1; fiyatTxt.Text = ""; garantiRdGrup.Properties.Items[0].Value = 0; garantiRdGrup.Properties.Items[1].Value = 0; takasRdGrup.Properties.Items[0].Value = 0; takasRdGrup.Properties.Items[1].Value = 0; durumTxt.Text = ""; renkTxt.Text = ""; plakaTxt.Text = ""; aciklamaZoople.DocumentHTML = ""; modelLook.Text = ""; kategoriLook.Text = ""; baslikTxt.Text = ""; kilometreTxt.Text = ""; } private void AracVtBtns_Click(object sender, EventArgs e) { SimpleButton buton = (SimpleButton)sender; switch (buton.Text.ToString()) { case "Ekle": try { aracServis.Add(new Tasit { Fiyat = decimal.Parse(fiyatTxt.Text.ToString()), Garanti = garantiRdGrup.Properties.Items[0].Value.ToString() == "false" ? false : true, Takas = takasRdGrup.Properties.Items[0].Value.ToString() == "false" ? false : true, Durum = durumTxt.Text.ToString(), Renk = renkTxt.Text.ToString(), Plaka = plakaTxt.Text.ToString(), Aciklama = aciklamaZoople.DocumentHTML.ToString(), ModelId = int.Parse(modelLook.EditValue.ToString()), KategoriId = int.Parse(kategoriLook.EditValue.ToString()), TasitBaslik = baslikTxt.Text.ToString(), Kilometre = int.Parse(kilometreTxt.Text.ToString()) }); MessageBox.Show("Araç başarıyla eklendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); AracPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Güncelle": try { aracServis.Update(new Tasit { Id = id, Fiyat = decimal.Parse(fiyatTxt.Text.ToString()), Garanti = garantiRdGrup.Properties.Items[0].Value.ToString() == "false" ? false : true, Takas = takasRdGrup.Properties.Items[0].Value.ToString() == "false" ? false : true, Durum = durumTxt.Text.ToString(), Renk = renkTxt.Text.ToString(), Plaka = plakaTxt.Text.ToString(), Aciklama = aciklamaZoople.DocumentHTML.ToString(), ModelId = int.Parse(modelLook.EditValue.ToString()), KategoriId = int.Parse(kategoriLook.EditValue.ToString()), TasitBaslik = baslikTxt.Text.ToString(), Kilometre = int.Parse(kilometreTxt.Text.ToString()) }); MessageBox.Show("Araç başarıyla güncellendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); AracPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Sil": try { aracServis.Delete(new Tasit { Id = id }); MessageBox.Show("Araç başarıyla silindi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); AracPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } private void tasitGrid_Click(object sender, EventArgs e) { id = int.Parse(gridView4.GetFocusedRowCellValue("Id").ToString()); int kategoriId = int.Parse(gridView4.GetFocusedRowCellValue("KategoriId").ToString()); int modelId = int.Parse(gridView4.GetFocusedRowCellValue("ModelId").ToString()); if ((gridView4.GetFocusedRowCellValue("Garanti").ToString()) == "False") { garantiRdGrup.SelectedIndex = 1; } else { garantiRdGrup.SelectedIndex = 0; } if ((gridView4.GetFocusedRowCellValue("Takas").ToString()) == "False") { takasRdGrup.SelectedIndex = 1; } else { takasRdGrup.SelectedIndex = 0; } fiyatTxt.Text = gridView4.GetFocusedRowCellValue("Fiyat").ToString(); durumTxt.Text = gridView4.GetFocusedRowCellValue("Durum").ToString(); renkTxt.Text = gridView4.GetFocusedRowCellValue("Renk").ToString(); plakaTxt.Text = gridView4.GetFocusedRowCellValue("Plaka").ToString(); aciklamaZoople.DocumentHTML = gridView4.GetFocusedRowCellValue("Aciklama").ToString(); modelLook.Text = modelServis.GetEntity(c => c.Id == modelId).ModelAdi; kategoriLook.Text = kategoriServis.GetEntity(c => c.Id == kategoriId).KategoriAdi; baslikTxt.Text = gridView4.GetFocusedRowCellValue("TasitBaslik").ToString(); kilometreTxt.Text = gridView4.GetFocusedRowCellValue("Kilometre").ToString(); } private void HasarKayitPageLoad() { hasarGridControl.DataSource = from x in hasarKayitServis.GetEntities(null) select new { x.Id, x.Tarih, x.Parca, x.Masraf, x.Aciklama, x.TasitId }; tasitLookUpEd.Properties.DataSource = from x in aracServis.GetEntities(null) select new { TasitId = x.Id, TasitPlaka = x.Plaka }; id = -1; tarihTxt.Text = ""; masrafTxt.Text = ""; hasarParcasiTxt.Text = ""; hasarAciklamaTxt.Text = ""; tasitLookUpEd.Text = ""; } private void HasarVt_Click(object sender, EventArgs e) { SimpleButton buton = (SimpleButton)sender; switch (buton.Text) { case "Ekle": try { hasarKayitServis.Add(new HasarKayit { Tarih = DateTime.Parse(tarihTxt.Text.ToString()), Masraf = decimal.Parse(masrafTxt.Text.ToString()), Parca = hasarParcasiTxt.Text.ToString(), Aciklama = hasarAciklamaTxt.Text.ToString(), TasitId = int.Parse(tasitLookUpEd.EditValue.ToString()) }); MessageBox.Show("Hasar kaydı başarıyla oluşturuldu.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); HasarKayitPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Güncelle": try { hasarKayitServis.Update(new HasarKayit { Id = id, Tarih = DateTime.Parse(tarihTxt.Text.ToString()), Masraf = decimal.Parse(masrafTxt.Text.ToString()), Parca = hasarParcasiTxt.Text.ToString(), Aciklama = hasarAciklamaTxt.Text.ToString(), TasitId = int.Parse(tasitLookUpEd.EditValue.ToString()) }); MessageBox.Show("Hasar kaydı başarıyla güncellendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); HasarKayitPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Sil": try { hasarKayitServis.Delete(new HasarKayit { Id = id }); MessageBox.Show("Hasar kaydı başarıyla silindi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); HasarKayitPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } private void HasarKayitGrid_Click(object sender, EventArgs e) { int tasitId = int.Parse(gridView5.GetFocusedRowCellValue("TasitId").ToString()); id = int.Parse(gridView5.GetFocusedRowCellValue("Id").ToString()); tarihTxt.Text = gridView5.GetFocusedRowCellValue("Tarih").ToString(); masrafTxt.Text = gridView5.GetFocusedRowCellValue("Masraf").ToString(); hasarParcasiTxt.Text = gridView5.GetFocusedRowCellValue("Parca").ToString(); hasarAciklamaTxt.Text = gridView5.GetFocusedRowCellValue("Aciklama").ToString(); tasitLookUpEd.Text = aracServis.GetEntity(c => c.Id == tasitId).Plaka; } private void YorumGrid_Click(object sender, EventArgs e) { int tasitId = int.Parse(gridView6.GetFocusedRowCellValue("TasitId").ToString()); id = int.Parse(gridView6.GetFocusedRowCellValue("Id").ToString()); yorumAdTxt.Text = gridView6.GetFocusedRowCellValue("Ad").ToString(); yorumSoyadTxt.Text = gridView6.GetFocusedRowCellValue("Soyad").ToString(); yorumMailTxt.Text = gridView6.GetFocusedRowCellValue("Mail").ToString(); yorumIcerikTxt.Text = gridView6.GetFocusedRowCellValue("Icerik").ToString(); yorumAracLook.Text = aracServis.GetEntity(c => c.Id == tasitId).TasitBaslik; } private void YorumVtBtns_Click(object sender, EventArgs e) { SimpleButton buton = (SimpleButton)sender; switch (buton.Text) { case "Ekle": try { yorumServis.Add(new Yorum { Ad = yorumAdTxt.Text.ToString(), Soyad = yorumSoyadTxt.Text.ToString(), Mail = yorumMailTxt.Text.ToString(), Icerik = yorumIcerikTxt.Text.ToString(), TasitId = int.Parse(yorumAracLook.EditValue.ToString()) }); MessageBox.Show("Yorum başarıyla eklendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); YorumPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Güncelle": try { yorumServis.Update(new Yorum { Id = id, Ad = yorumAdTxt.Text.ToString(), Soyad = yorumSoyadTxt.Text.ToString(), Mail = yorumMailTxt.Text.ToString(), Icerik = yorumIcerikTxt.Text.ToString(), TasitId = int.Parse(yorumAracLook.EditValue.ToString()) }); MessageBox.Show("Yorum başarıyla güncellendi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); YorumPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case "Sil": try { yorumServis.Delete(new Yorum { Id = id }); MessageBox.Show("Yorum başarıyla silindi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); YorumPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } private void fotoKaydetBtn_Click(object sender, EventArgs e) { try { string yol = Path.GetDirectoryName(Application.ExecutablePath) + @"\..\..\..\"; DirectoryInfo dir = new DirectoryInfo(yol); //string fullPath = dir.FullName + @"Galeri.WebUI\Content\Img\"; string fullPath = @"E:\derscalismalarim\GitHub Ornek Gelistirme Klasoru\Galeri\Galeri.WebUI\Content\Img\"; var p = new DirectoryInfo(@"C:\Users\Acer\Desktop\fotolar").GetFiles("*.*"); foreach (FileInfo dosya in p) { dosya.CopyTo(fullPath + dosya.Name); } fotografServis.Add(new Fotograf { FotografAdi = p11, TasitId = int.Parse(fotoTasitLookUp.EditValue.ToString()) }); fotografServis.Add(new Fotograf { FotografAdi = p22, TasitId = int.Parse(fotoTasitLookUp.EditValue.ToString()) }); fotografServis.Add(new Fotograf { FotografAdi = p33, TasitId = int.Parse(fotoTasitLookUp.EditValue.ToString()) }); fotografServis.Add(new Fotograf { FotografAdi = p44, TasitId = int.Parse(fotoTasitLookUp.EditValue.ToString()) }); MessageBox.Show("Fotoğraflar başarıyla kaydedildi.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information); YorumPageLoad(); } catch (Exception ex) { MessageBox.Show("Hata meydana geldi. " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void YorumPageLoad() { yorumGridControl.DataSource = from x in yorumServis.GetEntities(null) select new { x.Id, x.Ad, x.Soyad, x.Mail, x.Icerik, x.TasitId }; yorumAracLook.Properties.DataSource = from x in aracServis.GetEntities(null) select new { TasitId = x.Id, TasitBaslik = x.TasitBaslik }; id = -1; yorumAdTxt.Text = ""; yorumSoyadTxt.Text = ""; yorumMailTxt.Text = ""; yorumIcerikTxt.Text = ""; tasitLookUpEd.Text = ""; } private void FotografPageLoad() { fotoTasitLookUp.Properties.DataSource = from x in aracServis.GetEntities(null) select new { TasitPlaka = x.Plaka, TasitId = x.Id }; id = -1; } private void FotoBtns_Click(object sender, EventArgs e) { SimpleButton buton = (SimpleButton)sender; switch (buton.Name) { case "foto1Btn": if(openFileDialog1.ShowDialog() == DialogResult.OK) { p1 = openFileDialog1.FileName; p1Plc.Text = p1; p11 = Path.GetFileName(p1); } break; case "foto2Btn": if (openFileDialog2.ShowDialog() == DialogResult.OK) { p2 = openFileDialog1.FileName; p2Plc.Text = p2; p22 = Path.GetFileName(p2); } break; case "foto3Btn": if (openFileDialog3.ShowDialog() == DialogResult.OK) { p3 = openFileDialog3.FileName; p3Plc.Text = p3; p33 = Path.GetFileName(p3); } break; case "foto4Btn": if (openFileDialog4.ShowDialog() == DialogResult.OK) { p4 = openFileDialog4.FileName; p4Plc.Text = p4; p44 = Path.GetFileName(p4); } break; } } } }
namespace ProjetctTiGr13.Domain.FicheComponent { public class DeathRollManager { public int SuccessRoll { get; set; } public int FailRoll { get; set; } public DeathRollManager() { SuccessRoll = 0; FailRoll = 0; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; [CreateAssetMenu(fileName = "NewAudioAsset", menuName = "Scriptable Objects/Systems/Audio/Audio Asset")] public class AudioAsset : ScriptableObject { public AudioClip Clip; public Vector3 Position; public AudioMixerGroup MixerGroup; public bool BypassEffects; public bool BypassReverbZone; public bool Loop; [Range(0, 256)] public int Priority = 128; [Range(0, 1)] public float Volume = 1; [Range(-3, 3)] public float Pitch = 1; [Range(-1, 1)] public float StereoPan = 0; [Range(0, 1)] public float SpatialBlend = 0; [Range(0, 1.1f)] public float ReverbZoneMix; [Space] [Range(0, 5)] public float DopplerLevel = 1; [Range(0, 360)] public int Spread = 0; public AudioRolloffMode VolumeRolloff = AudioRolloffMode.Logarithmic; public float MinDistance = 10; public float MaxDitance = 500; }
using System; namespace iSukces.Code.Db { public class AutoNavigationAttribute : Attribute { public AutoNavigationAttribute(string name, Type type, string inverse = null) { Name = name; Type = type; Inverse = inverse; } public AutoNavigationAttribute(Type type, string inverse = null) { Type = type; Inverse = inverse; } public string Name { get; } public Type Type { get; } public string Inverse { get; } public InverseKind GenerateInverse { get; set; } public string NavigationPropertyDescription { get; set; } } public enum InverseKind { None, Single, Collection } }
using System; using UnityEngine.Events; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// None generic Unity Event of type `Collision2D`. Inherits from `UnityEvent&lt;Collision2D&gt;`. /// </summary> [Serializable] public sealed class Collision2DUnityEvent : UnityEvent<Collision2D> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RRExpress.ApiClient { public class ApiClientOption { /// <summary> /// Api 的基地址(http://xxx/{controller}/{action} , 基地址即为 http://xxx) /// </summary> public string BaseUri { get; } public ApiClientOption(string baseUri) { this.BaseUri = baseUri; } } }
using System; using System.Collections; namespace CustomIterator { // IEnumerable needs System.Collections namespace public class CustomEnumerablePeople : IEnumerable { // People is a collection of person private Person[] _personArray; public CustomEnumerablePeople(Person[] personArray) { _personArray = new Person[personArray.Length]; for (int i = 0; i < personArray.Length; i++) { _personArray[i] = personArray[i]; } } // Work manually with IEnumerator IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } private PeopleEnumerator GetEnumerator() { return new PeopleEnumerator(_personArray); } } public class PeopleEnumerator : IEnumerator { public Person[] _person; // Enumerators are positioned before the first element // until the first MoveNext() call. int Position = -1; public PeopleEnumerator(Person[] personArray) { _person = personArray; } public Person Current { get { return _person[Position]; } } #region IEnumerator Implementation // object Current // { // get // { // return Current; // } // } // Get the current item (read-only property). object IEnumerator.Current { get { return Current; } } // Advance the internal position of the cursor. public bool MoveNext() { Position++; return (Position < _person.Length); } // Reset the cursor before the first member. public void Reset() { Position = -1; } #endregion } public class Demo4 { public static void Run() { Person[] actress = new Person[5] { new Person("Yui", "Aragaki"), new Person("Haruka", "Ayase"), new Person("Haruna", "kawaguchi"), new Person("Mikako", "Tabe"), new Person("Ishihara", "Satomi") }; CustomEnumerablePeople peopleList = new CustomEnumerablePeople(actress); // this code will not throw an Error! // 'CustomEnumerablePeople' implements IEnumerable interface foreach (Person p in peopleList) { Console.WriteLine("{0} {1}", p.firstName, p.lastName); } } } }
using System.Linq; namespace TechEval.Core { public interface IODataDispatcher { IQueryable<T> Dispatch<T>() where T : class; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using Core.DAL; using System.ComponentModel.DataAnnotations; namespace Core.BIZ { public class CongNoNXB { public CongNoNXB() { } public CongNoNXB(CONGNONXB congno) { MaSoSach = congno.masosach; MaSoNXB = congno.masonxb; SoLuong = congno.soluong; DonGia = congno.dongia; Thang = congno.thang; } public CongNoNXB(CONGNONXB congno, NXB nxb) :this(congno) { NXB = new NhaXuatBan(nxb); } public CongNoNXB(CONGNONXB congno, SACH sach) : this(congno) { Sach = new Sach(sach); } public CongNoNXB(CONGNONXB congno, NXB nxb, SACH sach) :this(congno,nxb) { Sach = new Sach(sach); } #region Private Properties private Sach _sach; private NhaXuatBan _nxb; private static List<string> _searchKeys; #endregion #region Public Properties [Required] [DisplayName(CongNoNXBManager.Properties.MaSoSach)] public int MaSoSach { get; set; } [DisplayName(CongNoNXBManager.Properties.Sach)] public Sach Sach { get { if (_sach == null) { _sach = SachManager.find(this.MaSoSach); } return _sach; } set { _sach = value; } } [Required] [DisplayName(CongNoNXBManager.Properties.MaSoNXB)] public int MaSoNXB { get; set; } [DisplayName(CongNoNXBManager.Properties.NXB)] public NhaXuatBan NXB { get { if (_nxb == null) { _nxb = NhaXuatBanManager.find(this.MaSoNXB); } return _nxb; } set { _nxb = value; } } [Required] [DisplayName(CongNoNXBManager.Properties.SoLuong)] public decimal SoLuong { get; set; } [Required] [DisplayName(CongNoNXBManager.Properties.DonGia)] public decimal DonGia { get; set; } [DisplayName(CongNoNXBManager.Properties.ThanhTien)] public decimal ThanhTien { get { return this.SoLuong * this.DonGia; } } [Required] [DisplayName(CongNoNXBManager.Properties.Thang)] public DateTime Thang { get; set; } #endregion #region Services public static List<string> searchKeys() { if (_searchKeys == null) { _searchKeys = new List<string>(); _searchKeys.Add(nameof(CongNoNXBManager.Properties.MaSoSach)); _searchKeys.Add(nameof(CongNoNXBManager.Properties.MaSoNXB)); _searchKeys.Add(nameof(CongNoNXBManager.Properties.SoLuong)); _searchKeys.Add(nameof(CongNoNXBManager.Properties.DonGia)); _searchKeys.Add(nameof(CongNoNXBManager.Properties.Thang)); _searchKeys.Add(nameof(CongNoNXBManager.Properties.ThanhTien)); _searchKeys.Add(nameof(NhaXuatBanManager.Properties.TenNXB)); _searchKeys.Add(nameof(SachManager.Properties.TenSach)); _searchKeys.Add(nameof(SachManager.Properties.TenTacGia)); } return _searchKeys; } #endregion #region Override Methods public override string ToString() { return this.Thang.ToString(); } #endregion } }
using AutoMapper; using University.Data; using University.Data.CustomEntities; using University.UI.Areas.Admin.Models; using University.UI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace University.UI.App_Start { public class MapperConfg : Profile { public MapperConfg() { CreateMap<CategoryMaster, CategoryViewModel>(); CreateMap<CategoryViewModel, CategoryMaster>(); CreateMap<SubCategoryMaster, SubCategoryViewModel>(); CreateMap<SubCategoryViewModel, SubCategoryMaster>(); CreateMap<ProductEntity, ProductViewModel>(); CreateMap<ProductViewModel, ProductEntity>(); CreateMap<ProductUserGuide, ProductUserGuideViewModel>(); CreateMap<ProductUserGuideViewModel, ProductUserGuide>(); CreateMap<SubCategoryMaster, DropDownViewModel>().ForMember(des => des.Value, src => src.MapFrom(y => y.Id)); CreateMap<ProductVideos, ProductVideoViewModel>(); CreateMap<ProductVideoViewModel, ProductVideos>(); CreateMap<ProductSpec, ProductSpecViewModel>(); CreateMap<ProductSpecViewModel, ProductSpec>(); CreateMap<ProductFAQs, ProductFaqViewModel>(); CreateMap<FAQ, FAQViewModel>(); CreateMap<ProductFaqViewModel, ProductFAQs>(); CreateMap<ProductFAQVideoViewModel, ProductFAQVideos>(); CreateMap<ProductFAQVideos, ProductFAQVideoViewModel>(); CreateMap<ProductDocumentViewModel, ProductDocuments>(); CreateMap<ProductDocuments, ProductDocumentViewModel>(); CreateMap<ProductFeedback, ProductFeedbackViewModel>(); CreateMap<ProductFeedbackViewModel, ProductFeedback>(); CreateMap<HomeSlider, HomeSliderViewModel>(); CreateMap<HomeSliderViewModel, HomeSlider>(); CreateMap<ProductEntity, ProductDropdownListViewModel>(); CreateMap<ProductDropdownListViewModel, ProductEntity>(); } } }
using UnityEngine; using System.Collections.Generic; namespace Ardunity { [AddComponentMenu("ARDUnity/Reactor/Transform/RotationAxisReactor")] [HelpURL("https://sites.google.com/site/ardunitydoc/references/reactor/rotationaxisreactor")] public class RotationAxisReactor : ArdunityReactor { public Axis upAxis; public Axis forwardAxis; public bool invert = false; private Quaternion _initRot; private Quaternion _dragRot; private IWireInput<float> _analogInput; private IWireOutput<float> _analogOutput; private IWireInput<DragData> _dragInput; protected override void Awake() { base.Awake(); _initRot = transform.localRotation; _dragRot = Quaternion.identity; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(_analogInput != null || _analogOutput != null || _dragInput != null) { Quaternion startRot = _initRot * _dragRot; Vector3 up = Vector3.zero; if(upAxis == Axis.X) up = Vector3.right; else if(upAxis == Axis.Y) up = Vector3.up; else if(upAxis == Axis.Z) up = Vector3.forward; if(invert) up = -up; Vector3 forward = Vector3.zero; if(forwardAxis == Axis.X) forward = Vector3.right; else if(forwardAxis == Axis.Y) forward = Vector3.up; else if(forwardAxis == Axis.Z) forward = Vector3.forward; Vector3 to = Vector3.ProjectOnPlane(transform.localRotation * forward, startRot * up); float angle = Vector3.Angle(startRot * forward, to); if(Vector3.Dot(startRot * up, Vector3.Cross(startRot * forward, to)) < 0f) angle = -angle; if(_analogOutput != null) _analogOutput.output = angle; if(_analogInput != null) { float value = _analogInput.input; if(value > 180f) value -= 360f; else if(value < -180f) value += 360f; transform.Rotate(up, value - angle, Space.Self); } if(_dragInput != null) { DragData dragData = _dragInput.input; if(dragData.isDrag) { Quaternion delta = Quaternion.AngleAxis(dragData.delta, up); transform.localRotation *= delta; _dragRot *= delta; } } } } protected override void AddNode(List<Node> nodes) { base.AddNode(nodes); nodes.Add(new Node("setAngle", "Set Angle", typeof(IWireInput<float>), NodeType.WireFrom, "Input<float>")); nodes.Add(new Node("getAngle", "Get Angle", typeof(IWireOutput<float>), NodeType.WireFrom, "Output<float>")); nodes.Add(new Node("rotateDrag", "Rotate by drag", typeof(IWireInput<DragData>), NodeType.WireFrom, "Input<DragData>")); } protected override void UpdateNode(Node node) { if(node.name.Equals("setAngle")) { node.updated = true; if(node.objectTarget == null && _analogInput == null) return; if(node.objectTarget != null) { if(node.objectTarget.Equals(_analogInput)) return; } _analogInput = node.objectTarget as IWireInput<float>; if(_analogInput == null) node.objectTarget = null; return; } else if(node.name.Equals("getAngle")) { node.updated = true; if(node.objectTarget == null && _analogOutput == null) return; if(node.objectTarget != null) { if(node.objectTarget.Equals(_analogOutput)) return; } _analogOutput = node.objectTarget as IWireOutput<float>; if(_analogOutput == null) node.objectTarget = null; return; } else if(node.name.Equals("rotateDrag")) { node.updated = true; if(node.objectTarget == null && _dragInput == null) return; if(node.objectTarget != null) { if(node.objectTarget.Equals(_dragInput)) return; } _dragInput = node.objectTarget as IWireInput<DragData>; if(_dragInput == null) node.objectTarget = null; return; } base.UpdateNode(node); } } }
using Hahn.ApplicatonProcess.December2020.Data.Entities; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace Hahn.ApplicatonProcess.December2020.Data { public class ApplicationDbContext : DbContext { public DbSet<Applicant> Applicants { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context) : base(context) { } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class DuckUI : MonoBehaviour { /// <summary> /// The width of the max health bar. /// </summary> public float maxHealthBarWidth = 165; /// <summary> /// The max health. /// </summary> public int maxHealth = 100; /// <summary> /// The health bar background. /// </summary> public RectTransform healthBarBackground; /// <summary> /// The health bar text. /// </summary> public GameObject healthBarText; /// <summary> /// The health text prefix. /// </summary> public string healthPrefix = "Health: "; int health; void Start () { AddHealth (0); } void Update () { //testings /* if (Input.GetKey (KeyCode.U)) { AddHealth (5); } if(Input.GetKey(KeyCode.I)) { AddHealth (-5); }*/ } /// <summary> /// Adds some health. /// </summary> /// <param name="amount">Amount to add.</param> void AddHealth (int amount) { SetHealth (health + amount); } /// <summary> /// Sets the health. /// </summary> /// <param name="amount">new health.</param> public void SetHealth(int amount) { health = Mathf.Clamp (amount, 0, maxHealth); UpdateVisuals (); } /// <summary> /// Updates the UI. /// </summary> void UpdateVisuals() { Vector3 newScale = healthBarBackground.sizeDelta; newScale.x = Mathf.Clamp(maxHealthBarWidth/maxHealth*health, 0, maxHealthBarWidth); healthBarBackground.sizeDelta = newScale; healthBarText.GetComponent<Text>().text = healthPrefix + health.ToString (); healthBarBackground.GetComponent<Image> ().color = new Color (1 - ((float)(health)/maxHealth), ((float)(health)/maxHealth), 0, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Collections.ObjectModel; namespace Page500GoFishStore { class Game : INotifyPropertyChanged { private List<Player> players; private Dictionary<Values, Player> books; private Deck stock; private int round = 1; public bool GameInProgress { get; private set; } public bool GameNotStarted => !GameInProgress; public string PlayerName { get; set; } public ObservableCollection<string> Hand { get; private set; } public string Books => DescribeBooks(); public string GameProgress { get; private set; } public event PropertyChangedEventHandler PropertyChanged; public Game() { PlayerName = "Enter your name"; Hand = new ObservableCollection<string>(); ResetGame(); } public void StartGame() { ClearProgress(); GameInProgress = true; OnPropertyChanged("GameInProgress"); OnPropertyChanged("GameNotStarted"); Random random = new Random(); players = new List<Player>(); players.Add(new Player(PlayerName, random, this)); players.Add(new Player("Andrea", random, this)); players.Add(new Player("Matt", random, this)); Deal(); players[0].SortHand(); UpdateHand(); } private void UpdateHand() { Hand.Clear(); foreach (string cardName in GetPlayerCardNames()) { Hand.Add(cardName); } if (GameInProgress) { AddProgress(DescribePlayerHands()); } OnPropertyChanged("Books"); OnPropertyChanged("Cards"); } private void ResetGame() { GameInProgress = false; OnPropertyChanged("GameInProgress"); OnPropertyChanged("GameNotStarted"); books = new Dictionary<Values, Player>(); stock = new Deck(); Hand.Clear(); } public void AddProgress(string line) { /* this puts the first log entries first but the scrolling doesn't work automagically so TODO * if (string.IsNullOrEmpty(GameProgress)) { GameProgress = line; } else { GameProgress = GameProgress + Environment.NewLine + line; }*/ GameProgress = line + Environment.NewLine + GameProgress; OnPropertyChanged("GameProgress"); } public void ClearProgress() { GameProgress = string.Empty; OnPropertyChanged("GameProgress"); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void Deal() { stock.Shuffle(); for (int i = 0; i < 5; i++) { for (int j = 0; j < players.Count; j++) { players[j].TakeCard(stock.Deal()); } } } public void PlayOneRound(int selectedPlayerCard) { // go through all of the players and call // each one's AskForACard() methods, starting with the human player (who's // at index zero in the Players list—make sure he asks for the selected // card's value). Then call PullOutBooks()—if it returns true, then the // player ran out of cards and needs to draw a new hand. After all the players // have gone, sort the human player's hand (so it looks nice in the form). // Then check the stock to see if it's out of cards. If it is, reset the // TextBox on the form to say, "The stock is out of cards. Game over!" and return // true. Otherwise, the game isn't over yet, so return false. Card selectedCard = players[0].Peek(selectedPlayerCard); Values selectedValue = selectedCard.Value; int drawCount = 0; for (int i = 0; i < players.Count; i++) { // edge case, if the player lost their last card to another player they will have to draw to play if (players[i].CardCount == 0) { players[i].TakeCard(stock.Deal()); AddProgress($"{players[i].Name} draws a card to keep playing."); } // 0 is the human player so the method is called with their selected card, otherwise the AI method is called which is the same but generates a random value if (i == 0) { players[i].AskForACard(players, i, stock, selectedValue); } else { players[i].AskForACard(players, i, stock); } // TODO should we end the for loop here to avoid extra processing? // // the card exchange is done so now we have to pull out books and draw cards // // don't check for books if there aren't at least 4 cards in hand if (players[i].CardCount > 3) { // executes method, which returns true if the player is out of cards as a result of pulling out books if (PullOutBooks(players[i])) { for (int j = 0; j < 5 && stock.Count > 0; j++) { players[i].TakeCard(stock.Deal()); drawCount++; } if (drawCount == 1) { AddProgress($"{players[i].Name} draws the last card."); } else { AddProgress($"{players[i].Name} draws {drawCount} cards."); } } // books may or may not have been pulled out by here and the player should have cards } players[0].SortHand(); if (stock.Count == 0) { AddProgress($"The stock is out of cards, game over!"); AddProgress(GetWinnerName()); ResetGame(); return; } } UpdateHand(); AddProgress($"--------------- End of round {round} ---------------"); round++; } public bool PullOutBooks(Player player) { // Pull out a player's books. Return true if the player ran out of cards, otherwise // return false. Each book is added to the Books dictionary. A player runs out of // cards when he’'s used all of his cards to make books—and he wins the game IEnumerable<Values> pulledBook = player.PullOutBooks(); // is a foreach loop for a Dictionary of one a target for improvement? would have to extract the value otherwise foreach (Values value in pulledBook) { books.Add(value, player); AddProgress($"{player.Name} scored a book of {Card.Plural(value)}"); } if (player.CardCount == 0) { return true; } return false; } public string DescribeBooks() { // Return a long string that describes everyone's books by looking at the Books // dictionary: "Joe has a book of sixes. (line break) Ed has a book of Aces." string bookString = ""; foreach (Values value in books.Keys) { bookString += $"{books[value].Name} has a book of {Card.Plural(value)}.{Environment.NewLine}"; } return bookString; } public string GetWinnerName() { // This method is called at the end of the game. It uses its own dictionary // (Dictionary<string, int> winners) to keep track of how many books each player // ended up with in the books dictionary. First it uses a foreach loop // on books.Keys—foreach (Values value in books.Keys)—to populate // its winners dictionary with the number of books each player ended up with. // Then it loops through that dictionary to find the largest number of books // any winner has. And finally it makes one last pass through winners to come // up with a list of winners in a string ("Joe and Ed"). If there's one winner, // it returns a string like this: "Ed with 3 books". Otherwise, it returns a // string like this: "A tie between Joe and Bob with 2 books." Dictionary<string, int> winners = new Dictionary<string, int>(); int theMostBooks = 0; string winnerString = ""; foreach (Values value in books.Keys) { // initialize the key because it's throwing exceptions otherwise! if (!winners.ContainsKey(books[value].Name)) { winners.Add(books[value].Name, 0); } // read Name property from player value in the key // assign existing value on winner key to int count // reassign the value after incrementing it string name = books[value].Name; winners[name]++; } foreach (string name in winners.Keys) { if (winners[name] > theMostBooks) { theMostBooks = winners[name]; } } foreach (string name in winners.Keys) { if (winners[name] == theMostBooks) { if (string.IsNullOrEmpty(winnerString)) { winnerString = name; } else { winnerString += $" and {name}"; } } } return $"{winnerString} won, with {theMostBooks} books."; } public IEnumerable<string> GetPlayerCardNames() { return players[0].GetCardNames(); } internal string DescribePlayerHands() { string description = ""; for (int i = 0; i < players.Count; i++) { description += $"{players[i].Name} has {players[i].CardCount}"; if (players[i].CardCount == 1) { description += $" card.{Environment.NewLine}"; } else { description += $" cards.{Environment.NewLine}"; } } description += $"The stock has {stock.Count} cards left."; return description; } } }
namespace Vlc.DotNet.Core.Interops.Signatures { public enum VideoAdjustOptions { Enable = 0, Contrast, Brightness, Hue, Saturation, Gamma } }
using NUnit.Framework; using ProjectCore.EFCore; using ProjectCore.Model.EntityModel; using ProjectCore.Model.Parameter; using ProjectCore.Service.System; namespace ProjectCore.UnitTesting { public class Tests { [Test] public void TestInsert() { ApplicationDbContext dbContext = new ApplicationDbContext(); SystemConfigService systemConfigService = new SystemConfigService(dbContext); for(int i = 0; i < 100; i++) { SystemConfig systemConfig = new SystemConfig(); systemConfig.Key = "KeyTest" + i; systemConfig.Value = "Value" + i; systemConfig.Description = "Description"+i; systemConfigService.AddAsync(systemConfig); } Assert.Pass(); } [Test] public void TestUpdate() { //ApplicationDbContext dbContext = new ApplicationDbContext(); //SystemConfigService systemConfigService = new SystemConfigService(dbContext); //SystemConfig systemConfig = new SystemConfig(); //systemConfig.Id = 2; //systemConfig.Key = "KeyTest2"; //systemConfig.Value = "Value2Edited"; //systemConfig.Description = "Description2"; //systemConfigService.Update(systemConfig); //Assert.Pass(); } [Test] public void TestPaging() { //ApplicationDbContext dbContext = new ApplicationDbContext(); //SystemConfigService systemConfigService = new SystemConfigService(dbContext); //BasePagingParam basePagingParam = new BasePagingParam() { PageIndex = 0,Keyword = "1", PageSize = 1 }; //BasePagingParam basePagingParam2 = new BasePagingParam() { PageIndex = 1,Keyword = "", PageSize = 1 }; //int totalRow1 = 0; //int totalRow2 = 0; //var xxx = systemConfigService.GetListPaging(basePagingParam,ref totalRow1); //var xxy = systemConfigService.GetListPaging(basePagingParam2, ref totalRow2); Assert.Pass(); } } }
using System; using System.Collections.Generic; using TexturePacker.Editor.Repository; using UnityEngine; namespace TexturePacker.Editor { public static class TransformationModificators { //Add modificator method here private static readonly List<Action<SpriteDescription>> Modificators = new List<Action<SpriteDescription>>() { ModificateCharacters, }; public static void Modificate(SpriteDescription spriteDescription) { Modificators.ForEach(x=>x(spriteDescription)); } //Write modificator methods below private static void ModificateCharacters(SpriteDescription spriteDescription) { if (spriteDescription.FileName.Contains("Characters/")) { spriteDescription.Pivot = new Vector2(.5f, 0); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Client.Map; using Welic.Dominio.Patterns.Service.Pattern; namespace Welic.Dominio.Models.Client.Service { public interface IServicePessoa: IService<PessoaMap> { } }
using UnityEngine; public class FindExtremePoints : MonoBehaviour { private float Xr; private float Yt; private float Yb; public float XRight { get { return Xr; } } public float YTop { get { return Yt; } } public float YBot { get { return Yb; } } private void Start() { RectTransform _changeTransform = transform as RectTransform; Xr = _changeTransform.position.x + _changeTransform.sizeDelta.x / 2;// Yt = _changeTransform.position.y + _changeTransform.sizeDelta.y / 2;// Yb = _changeTransform.position.y - _changeTransform.sizeDelta.y / 2;//получение крайних точек прямоугольника } // Update is called once per frame void Update() { } }
using VehicleInventory.Services.Contracts; using VehicleInventory.Services.DTOs; using CodingExercise.Data.Models; using System.Collections.Generic; using CodingExercise.Data; using System.Linq; using AutoMapper; using System; namespace VehicleInventory.Services { public class VehicleInventoryService : IVehicleInventoryService { private readonly IMapper _mapper; private readonly VehicleInventoryContext _dbContext; public VehicleInventoryService(IVehicleInventoryContext dbContext, IMapper mapper) { _mapper = mapper; _dbContext = dbContext as VehicleInventoryContext; } public int AddVehicleInStock(AddVehicleInStockDTO vehicle) { var toAdd = _mapper.Map<VehicleInStock>(vehicle); _dbContext.VehiclesInStock.Add(toAdd); return _dbContext.SaveChanges(); } public List<VehicleInStockDTO> GetAllVehiclesInStockFlat() { var result = _dbContext.VehiclesInStock.Where(vs => vs.IsDeleted == false).ToList(); var resDto = _mapper.Map<List<VehicleInStockDTO>>(result); return resDto; } public VehicleInStockDTO GetVehicleInStockByIdFlat(int vehicleId) { var result = _dbContext.VehiclesInStock.Where(v => v.IsDeleted == false).FirstOrDefault(v => v.Id == vehicleId); var resDto = _mapper.Map<VehicleInStockDTO>(result); return resDto; } public int RemoveVehicleInStock(int vehicleId) { var toDelete = _dbContext.VehiclesInStock.Where(v => v.IsDeleted == false).FirstOrDefault(vs => vs.Id == vehicleId); if(toDelete == null) { return 0; } toDelete.IsDeleted = true; return _dbContext.SaveChanges(); } } }
namespace Whathecode.System.Algorithm { /// <summary> /// Option which specifies how a split operation should be handled. /// </summary> public enum SplitOption { /// <summary> /// The location where is split is excluded from both results. /// </summary> None, /// <summary> /// The location where is split is included in both results. /// </summary> Both, /// <summary> /// The location where is split is only included in the left result set. /// </summary> Left, /// <summary> /// The location where is split is only included in the right result set. /// </summary> Right } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using TMPro; using UnityEngine.Networking; using System.Text; namespace Michsky.UI.ModernUIPack { public class LoginInfo { public int code; public string admin; public string name; } public class MainMenu : MonoBehaviour { public TMP_InputField _email; public TMP_InputField _password; public TMP_Text _warningText; public string scene; public string displayName; private string key = "NexusConnects"; string url = "http://the-nexus.herokuapp.com/authenticate_with_unity"; //string url = "http://127.0.0.1:5000/authenticate_with_uniy"; //private void Start() //{ // _warningText.text = ""; //} IEnumerator Post(string url, string bodyJsonString) { var request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); Debug.Log("Status Code: " + request.responseCode); yield return request.responseCode; } public void Login() { StartCoroutine(SendPostCoroutine()); } IEnumerator SendPostCoroutine() { //StartGame(); //Debug.Log("login activated with " + _email.text + _password.text); //string jsonString = "{\"email\":\"" + _email.text + "\",\"password\":\"" + _password.text + "\",\"key\":\"" + key + "\"}"; //Debug.Log(jsonString); ////CoroutineWithData cd = new CoroutineWithData(this, Post("http://127.0.0.1:5000/authenticate_with_unity", jsonString)); ////yield return cd.coroutine; ////StartCoroutine(Post("http://127.0.0.1:5000/authenticate_with_unity", jsonString)); ////Debug.Log("result is " + cd.result); // 'success' or 'fail' /// WWWForm form = new WWWForm(); form.AddField("email", _email.text); form.AddField("password", _password.text); form.AddField("key", key); Debug.Log(_email.text); Debug.Log(_password.text); _warningText.text = "Loading..."; using (UnityWebRequest www = UnityWebRequest.Post(url, form)) { yield return www.SendWebRequest(); if (www.isNetworkError) { Debug.Log(www.error); _warningText.text = "There seems to be a network error"; } else { Debug.Log("POST successful!"); StringBuilder sb = new StringBuilder(); foreach (System.Collections.Generic.KeyValuePair<string, string> dict in www.GetResponseHeaders()) { sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n"); } // Print Headers Debug.Log(sb.ToString()); // Print Body Debug.Log(www.downloadHandler.text); LoginInfo info = JsonUtility.FromJson<LoginInfo>(www.downloadHandler.text); Debug.Log(info.code.GetType()); Debug.Log(info.code); if(info.code == 0) { Debug.Log("Success!"); Debug.Log(info.name); Debug.Log(info.admin); StartGame(info.name, info.admin); } else if (info.code == 403) { Debug.Log("wrong pass"); _warningText.text = "Are you sure you put in the right password? Check the website."; } else if(info.code == 404) { Debug.Log("not found"); _warningText.text = "User not found, make sure you put in the right email"; } } } } public void StartGame(string name, string isAdmin) { Debug.Log("StartGame() Called!"); PlayerPrefs.SetString("playerName", name); PlayerPrefs.SetString("isAdmin", isAdmin); AvatarCreator.sceneString = scene; SceneManager.LoadScene("Avatar Creator"); } } public class CoroutineWithData { public Coroutine coroutine { get; private set; } public object result; private IEnumerator target; public CoroutineWithData(MonoBehaviour owner, IEnumerator target) { this.target = target; this.coroutine = owner.StartCoroutine(Run()); } private IEnumerator Run() { while (target.MoveNext()) { result = target.Current; yield return result; } } } }
using System; namespace Admin.Helpers { public class TimeConverterResult { public TimeConverterResult(int Days, int Hours, int Minutes, int Seconds) { this.Days = Days; this.Hours = Hours; this.Minutes = Minutes; this.Seconds = Seconds; } public int Days {get;set;} public int Hours {get;set;} public int Minutes {get;set;} public int Seconds {get;set;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RandomGenerator { /// <summary> /// Provides a unified interface for accessing details of styles and features. /// Combines and simplifies interfaces provided in RunConfig, DocFeatures and Defaults classes. /// </summary> public class ConfigFacade { private RunConfig runConfig; private DocFeatures docFeatures; private Defaults defaultConfig; public ConfigFacade(RunConfig runConfig, DocFeatures docFeatures, Defaults defaults) { this.runConfig = runConfig; this.docFeatures = docFeatures; this.defaultConfig = defaults; } public IEnumerable<StyleInfo> GetStyles(String featurePath) { IEnumerable<StyleInfo> tmp = runConfig.GetStyles(featurePath); ; return FillTypes(tmp); } public IEnumerable<StyleInfo> GetStylesPartial(String featurePath) { IEnumerable<StyleInfo> tmp = runConfig.GetStylesPartial(featurePath); ; return FillTypes(tmp); } private IEnumerable<StyleInfo> GetStyleList() { IEnumerable<StyleInfo> tmp = runConfig.GetStyleList(); return FillTypes(tmp); } public IEnumerable<StyleInfo> GetStyleList(String parentFeature) { var allStyles = GetStyleList(); List<StyleInfo> tmp = new List<StyleInfo>(); foreach (var style in allStyles) { if (docFeatures.IsStyleSupported(parentFeature, style.Name)) { tmp.Add(style); } } return tmp.AsEnumerable(); } public int GetMaxNestingDepth(String feature) { return runConfig.GetMaxNestedDepth(feature); } public Range GetSubFeatureCount(String parent, String feature) { Range featureCount = runConfig.GetElementCount(parent, feature); if (featureCount == null) { featureCount = defaultConfig.GetDefualtElementCount(parent, feature); } return featureCount; } public IEnumerable<String> GetAllChildFeatures(String parent) { var allFeatures = runConfig.GetFeatureList(); List<String> tmp = new List<String>(); foreach (var feature in allFeatures) { if (docFeatures.IsChildfeature(parent, feature)) { tmp.Add(feature); } } return tmp.AsEnumerable(); } /// <summary> /// Combines information on styles from docFeatures and runConfig /// </summary> /// <param name="styleInfoList"></param> /// <returns></returns> private IEnumerable<StyleInfo> FillTypes(IEnumerable<StyleInfo> styleInfoList) { List<StyleInfo> resultList = new List<StyleInfo>(); foreach (var styleInfo in styleInfoList) { IEnumerable<String> features = docFeatures.GetParentFeatures(styleInfo.Name); foreach (var feature in features) { StyleInfo tmp = (StyleInfo)styleInfo.Clone(); tmp.Feature = feature; tmp.Type = docFeatures.GetStyleType(styleInfo.Name, feature); tmp.PossibleValues = docFeatures.GetPossibleValues(styleInfo.Name, feature); resultList.Add(tmp); } } return resultList.AsEnumerable(); } } }
using JhinBot.DiscordObjects; using JhinBot.Enums; using JhinBot.Interface; using System; using System.Linq; namespace JhinBot.Convo.Validators { public class ListChoiceValidator : IValidator { private string _errorMessage; private GuildConfig _guildConfig; private ConversationType _type; public ListChoiceValidator(GuildConfig guildConfig, string errorMsg, ConversationType type) { _errorMessage = errorMsg; _guildConfig = guildConfig; _type = type; } (bool success, string errorMsg) IValidator.Validate(string input) { switch (_type) { case ConversationType.Command: var command = _guildConfig.ServerCommands.FirstOrDefault(c => c.Name == input); return (command != null, String.Format(_errorMessage, _type.ToString())); case ConversationType.Event: var eventEntity = _guildConfig.ServerEvents.FirstOrDefault(c => c.Name == input); return (eventEntity != null, String.Format(_errorMessage, _type.ToString())); default: return (false, $"Something really fucked up here... {ToString()}"); } } } }
using Democlass; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using TechTalk.SpecFlow; namespace APITests.Features { [Binding] public class CreateUserSteps { private const string BASE_URL = "https://reqres.in/"; private readonly CeateUserDTO ceateUserDTO; public CreateUserSteps(CeateUserDTO ceateUserDTO) { this.ceateUserDTO = ceateUserDTO; } [Given(@"I input UserName as ""(.*)""")] public void GivenIInputUserNameAs(string username) { ceateUserDTO.name = username; } [Given(@"I input role as ""(.*)""")] public void GivenIInputRoleAs(string role) { ceateUserDTO.job = role; } [When(@"I send CreateUser Requst")] public void WhenISendCreateUserRequst() { var UserResObj = new Helpers<CeateUserDTO>(); var payload = HandleContent.ParseJson<CeateUserRequestDTO>("TestData\\CreateUserReq.json"); var userRespReceived = UserResObj.CreateUsers("api/users", payload); } [Then(@"validate the user is created")] public void ThenValidateTheUserIsCreated() { Assert.AreEqual(payload.name, userRespReceived.name); } } }
using UnityEngine; using System.Collections; public class EnemyScriptCS : MonoBehaviour { // PLACE THIS ON ANY ITEM THAT CAN INCREASE THE HORROR METER }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameOver : MonoBehaviour { public Text first, second, third; void Start() { first.text = "1st: " + SaveSettings.winners[0]; second.text = "2nd: " + SaveSettings.winners[1]; third.text = "3rd: " + SaveSettings.winners[2]; } public void BackButton(string sceneName) { SceneManager.LoadScene(sceneName); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PAL_properties_; using System.Data; using BAL_DataAcessLayer_; using System.Threading; namespace MyOwnWebsite { public partial class LoginPage : System.Web.UI.Page { PAL properties = new PAL(); BAL BAl_Intercoonection = new BAL(); DataSet ds = new DataSet(); protected void Page_Load(object sender, EventArgs e) { } protected void Unnamed_Click(object sender, EventArgs e) { properties.StaffNumber = txtname.Text.Trim(); Session["txtname"] = txtname.Text.Trim(); properties.Password = txtpwd.Text.Trim(); ds = BAl_Intercoonection.Login_InterConnection(properties); if (ds != null) { if (ds.Tables[0].Rows.Count > 0) { Session["Name"] = ds.Tables[0].Rows[0]["Name"].ToString(); Response.Redirect("~/Forms/Home.aspx", true); } if (ds.Tables[0].Rows.Count == 0) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clentscript", "alert('Invalid UserName / Password!. Plase Check.')",true); return; } } } } }
using Microsoft.Xna.Framework; using Project371.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project371.Core { /// <summary> /// Base class for a scene (a game level) /// </summary> abstract class Scene { /// <summary> /// The scene states /// </summary> public enum LevelStates { WELCOME, PLAYING, WIN, LOSE, OUTRO } /// <summary> /// The current state of the scene /// </summary> private LevelStates currentState; public LevelStates CurrentState { get { return this.currentState; } set { if (this.currentState != value) { this.currentState = value; LevelStateChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Invoked when LevelState is changed. /// </summary> public event EventHandler<EventArgs> LevelStateChanged; public virtual void OnLevelStateChanged(object sender, EventArgs e) { } /// <summary> /// The scene name /// </summary> public string Name { get; private set; } /// <summary> /// Specified if the scene is ready for update/rendering /// </summary> public bool IsReady { get; set; } /// <summary> /// The scene skybox (optional) /// </summary> public Skybox skybox { get; protected set; } /// <summary> /// The entities in the scene /// </summary> protected List<Entity> allEntities; public Scene(string sceneName) { Name = sceneName; allEntities = new List<Entity>(); IsReady = false; } /// <summary> /// Load scene assets /// </summary> public abstract void LoadScene(); /// <summary> /// Unload scene assets /// </summary> public abstract void UnloadScene(); /// <summary> /// Update entities /// </summary> /// <param name="gameTime"></param> public virtual void UpdateScene(GameTime gameTime) { allEntities.RemoveAll(e => e.ToBeDestroyed); foreach (Entity e in allEntities) { if (e.Active) e.Update(); } } public void AddEntity(Entity e) { // Don't add the same obj twice Entity found = allEntities.Find( ent => ent == e); if (found == null) { // Console.WriteLine("Added to scene " + e.Name); allEntities.Add(e); } foreach (Entity child in e.Children) AddEntity(child); } public void RemoveEntity(Entity e) { allEntities.Remove(e); } } }
namespace gView.Framework.system { static public class NumberConverter { static public double ToDouble(this string value) { if (SystemInfo.IsWindows) { return double.Parse(value.Replace(",", "."), SystemInfo.Nhi); } return double.Parse(value.Replace(",", SystemInfo.Cnf.NumberDecimalSeparator)); } static public float ToFloat(this string value) { if (SystemInfo.IsWindows) { return float.Parse(value.Replace(",", "."), SystemInfo.Nhi); } return float.Parse(value.Replace(",", SystemInfo.Cnf.NumberDecimalSeparator)); } static public string ToDoubleString(this double d) { return d.ToString(Numbers.Nhi); } } }
using System.Threading.Tasks; using RestSharp; using ZendeskSell.Models; namespace ZendeskSell.Products { public class ProductActions : IProductActions { private RestClient _client; public ProductActions(RestClient client) { _client = client; } public async Task<ZendeskSellCollectionResponse<ProductResponse>> GetAsync(int pageNumber, int numPerPage) { var request = new RestRequest("products") .AddParameter("page", pageNumber) .AddParameter("per_page", numPerPage); return (await _client.ExecuteGetTaskAsync<ZendeskSellCollectionResponse<ProductResponse>>(request)).Data; } /// <summary> /// Creates a product associate with the object passed withit. /// </summary> /// <param name="product"></param> /// <returns></returns> public async Task<ZendeskSellObjectResponse<ProductResponse>> CreateAsync(ProductRequest product) { var request = new RestRequest("products") { RequestFormat = DataFormat.Json }; request.JsonSerializer = new RestSharpJsonNetSerializer(); request.AddJsonBody(product); return (await _client.ExecutePostTaskAsync<ZendeskSellObjectResponse<ProductResponse>>(request)).Data; } } }
// <copyright file="Packet.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2019 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /** * @author Alireza Ghodrati */ using System; using System.Text; using FiroozehGameService.Models.Enums; using FiroozehGameService.Utils.Serializer.Utils.IO; namespace FiroozehGameService.Models.GSLive.RT { [Serializable] internal class Packet : APacket { private int _payloadLen; internal int Action; internal long ClientReceiveTime; internal long ClientSendTime; internal long Hash; internal byte[] Payload; internal GProtocolSendType SendType; public Packet(byte[] buffer) { Deserialize(buffer); } public Packet(long hash, int action, GProtocolSendType sendType = GProtocolSendType.UnReliable, byte[] payload = null) { Hash = hash; Action = action; Payload = payload; SendType = sendType; } internal override byte[] Serialize(string key, bool isCommand) { byte havePayload = 0x0, haveSendTime = 0x0; short prefixLen = 4 * sizeof(byte) + sizeof(ulong); if (Payload != null) { havePayload = 0x1; _payloadLen = Payload.Length; prefixLen += sizeof(ushort); } if (ClientSendTime != 0L) { haveSendTime = 0x1; prefixLen += sizeof(long); } var packetBuffer = BufferPool.GetBuffer(BufferSize(prefixLen)); using (var packetWriter = ByteArrayReaderWriter.Get(packetBuffer)) { // header Segment packetWriter.Write((byte) Action); packetWriter.Write(haveSendTime); packetWriter.Write(havePayload); if (havePayload == 0x1) packetWriter.Write((ushort) _payloadLen); // data Segment packetWriter.Write((byte) SendType); packetWriter.Write((ulong) Hash); if (havePayload == 0x1) packetWriter.Write(Payload); if (haveSendTime == 0x1) packetWriter.Write(ClientSendTime); } return packetBuffer; } internal sealed override void Deserialize(byte[] buffer) { using (var packetWriter = ByteArrayReaderWriter.Get(buffer)) { Action = packetWriter.ReadByte(); var haveSendTime = packetWriter.ReadByte(); var havePayload = packetWriter.ReadByte(); if (havePayload == 0x1) _payloadLen = packetWriter.ReadUInt16(); SendType = (GProtocolSendType) packetWriter.ReadByte(); Hash = (long) packetWriter.ReadUInt64(); if (havePayload == 0x1) Payload = packetWriter.ReadBytes(_payloadLen); if (haveSendTime == 0x1) ClientSendTime = packetWriter.ReadInt64(); } } internal override int BufferSize(short prefixLen) { return prefixLen + _payloadLen; } internal override void Encrypt(string key, bool isCommand) { } public override string ToString() { return "Packet{" + "Hash='" + Hash + '\'' + ", Action=" + Action + '\'' + ", type = " + SendType + '\'' + ", payload = " + Encoding.UTF8.GetString(Payload ?? new byte[0]) + '\'' + ", SendTime = " + ClientSendTime + '\'' + '}'; } } }
using CitizenFX.Core; namespace Fivem_Tests_Server.net { public class Main : BaseScript { public Main() { ConfigManager.Intialize(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FallstudieSem5.Models.Repository; using FallstudieSem5.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging.Abstractions; namespace FallstudieSem5.Controllers { [Route("api/title")] public class TitleController : ControllerBase { private readonly IDataRepository<Title> _dataRepository; public TitleController(IDataRepository<Title> dataRepository) { _dataRepository = dataRepository; } [HttpGet("{id}", Name = "GetTitle")] public IActionResult Get(long id) { Title title = _dataRepository.Get(id); if (title == null) { return NotFound("title not found."); } return Ok(title); } [HttpPost] public IActionResult Post([FromBody] Title title) { if (title == null) { return BadRequest("title is null"); } _dataRepository.Add(title); return CreatedAtRoute( "Get", new { Id = title.TitleId }, title); } [HttpPut("{id}")] public IActionResult Put(long id, [FromBody] Title title) { if (title == null) { return BadRequest("Object is null."); } Title titleToUpdate = _dataRepository.Get(id); if (titleToUpdate == null) { return NotFound("address not found"); } _dataRepository.Update(titleToUpdate, title); return NoContent(); } [HttpDelete("{id}")] public IActionResult Delete(long id) { Title title = _dataRepository.Get(id); if (title == null) { return NotFound("title not found"); } _dataRepository.Delete(title); return NoContent(); } } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; namespace StarlightRiver.Dusts { public class JungleEnergy : ModDust { public override void OnSpawn(Dust dust) { dust.noGravity = true; dust.noLight = false; dust.color.R = 180; dust.color.G = 255; dust.color.B = 80; } public override Color? GetAlpha(Dust dust, Color lightColor) { return dust.color; } public override bool Update(Dust dust) { dust.position += dust.velocity; dust.rotation += 0.05f; dust.color.R --; dust.scale *= 0.992f; if (dust.scale < 0.3f) { dust.active = false; } return false; } } }
using SFML.Graphics; using SFML.Window; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IcyMazeRunner.Klassen { class Credits : GameStates { Texture creditsTex; Sprite credits; bool isPressed = false; public void initialize() { credits = new Sprite(creditsTex); credits.Position = new Vector2f(0, 0); } public void loadContent() { creditsTex = new Texture("Texturen/Menü+Anzeigen/creditscreen.png"); } public EGameStates update(GameTime time) { isPressed = false; credits.Texture = creditsTex; if (Keyboard.IsKeyPressed(Keyboard.Key.Space)) { return EGameStates.credits; isPressed = true; } if (Keyboard.IsKeyPressed(Keyboard.Key.Escape)) { return EGameStates.mainMenu; isPressed = true; } return EGameStates.credits; } public void draw(RenderWindow win) { win.Draw(credits); } } }
namespace Uintra.Features.Permissions.Models { public class PermissionViewModel { public int IntranetMemberGroupId { get; set; } public int ActionId { get; set; } public string ActionName { get; set; } public int? ParentActionId { get; set; } public int ResourceTypeId { get; set; } public string ResourceTypeName { get; set; } public bool Allowed { get; set; } public bool Enabled { get; set; } } }
using System.Linq; using Cradiator.Model; namespace Cradiator.Audio { public interface ISpeechTextParser { string Parse(string sentence, ProjectStatus projectStatus); } public class SpeechTextParser : ISpeechTextParser { readonly IBuildBuster _buildBuster; public SpeechTextParser([InjectBuildBusterFullNameDecorator] IBuildBuster buildBuster) { _buildBuster = buildBuster; } public string Parse(string sentence, ProjectStatus projectStatus) { var reservedWords = from word in sentence.Split(new[] {' ', ',', '.'}) where word.StartsWith("$") where word.EndsWith("$") select word; if (reservedWords.Any()) { foreach (var word in reservedWords) { if (word == "$ProjectName$") sentence = sentence.Replace(word, projectStatus.Name); if (word == "$Breaker$") sentence = sentence.Replace(word, _buildBuster.FindBreaker(projectStatus.CurrentMessage)); } } else { sentence = string.Format("{0}, {1}", projectStatus.Name, sentence); } return sentence; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Text; using System.Threading.Tasks; namespace Sample.Aspects { public class RequireAdminUserAttribute : HandlerAspectAttribute { public override void BeforeHandle(object command) { var currentUser = command as ICurrentUser; if (currentUser != null && currentUser.CurrentUser != "admin") { throw new SecurityException("Must be admin"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using HospitalSystem.Models; namespace HospitalSystem.Business { public class Examine { private teamworkContext db = new teamworkContext(); public List<string> SearchExamine(string examineName) { var examineSearch = db.examine_product.Where(m => m.ProductName.Contains(examineName)); return examineSearch.Select(examine => examine.ProductName).ToList(); } public examine_product GetExamineProductByName(string examineName) { return db.examine_product.FirstOrDefault(m => m.ProductName.Equals(examineName)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BackendApi.DB.DataModel { public class INNER_ORDER_BASIC_SEAL_MST { public string ORDER_NO { get; set; } public string BUMP_ID { get; set; } public string BUMP_TYPE { get; set; } public string BUMP_SERIAL_NO { get; set; } public int NUMBER { get; set; } public int WORKING_PRESSURE { get; set; } public int TEST_PRESSURE { get; set; } public int SUPPRESS_PRESSURE { get; set; } public string FLANGE_STANDARD { get; set; } public int FLOW { get; set; } public int LIFT { get; set; } public int NPSH { get; set; } public int BUMP_SPEED { get; set; } public string STATION { get; set; } public string MEDIA { get; set; } public int TEMPERATURE { get; set; } public int VISCOSITY { get; set; } public int INLET_PRESSURE { get; set; } public string PARTICULATES { get; set; } public string SEAL_TYPE { get; set; } public string SEAL_MODEL { get; set; } public string SEAL_MATERIAL { get; set; } public string OTHER_SEAL_PROVIDER { get; set; } public string OTHER_SEAL_INFO { get; set; } public string OTHER_SEAL_MODEL { get; set; } public string NEED_SEAL_COOLER_FLG { get; set; } public string SEAL_COOLER_MODEL { get; set; } public string BEARING_BRAND { get; set; } public string BEARING_OTHER_INFO { get; set; } public string INSTALL_DIRECTION { get; set; } public string ABD_SEAL_INFO { get; set; } } }
using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace AKCore.Models { public class HireModel { [Display(Name = "Namn")] [Required] public string Name { get; set; } [Display(Name = "Epost")] [Required] public string Email { get; set; } [Display(Name = "Telefonnummer")] public string Tel { get; set; } [Display(Name = "Var och när vill ni boka oss")] public string Other { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace FACTEURS_PREMIERS { class Program { public static int lire() { int x; do { Console.WriteLine("Donnez un entier compris entre 2 et 100"); Console.Write(" n = "); x = int.Parse(Console.ReadLine()); } while (x < 2 || x > 300); return x; } public static void decomposer(int x,List<int> produits) { int r, q, d; d = 2; do { r = x % d; q = x / d; if (r == 0) { produits.Add(d); x = q; } else { d++; } } while (x != 1); } public static void afficher(int n, List<int> produits) { Console.Write($"{n} = "); if(produits.Count!= 1) { string resutlt = produits.Select(x => x.ToString()).Aggregate((a, b) => a + " * " + b); Console.Write(resutlt); } else { Console.WriteLine(produits.FirstOrDefault()); } Console.WriteLine("\n"); } static void Main(string[] args) { int n; List<int> produits = new List<int>(); n= lire(); decomposer(n, produits); afficher(n ,produits); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using DevExpress.XtraEditors; using System.Data.SqlClient; using System.Xml; namespace AsimcoBatchMNGMT { public partial class PORVForm : DevExpress.XtraEditors.XtraForm { string[] Xml; string[] Retried; string[][] Check; DataTable dt; CurrencyManager cm; public PORVForm() { InitializeComponent(); } public PORVForm(string[] xml,string skuid, string errinfo, string[] retried,DataTable dtmaterial,string[][] check) { InitializeComponent(); Xml = xml; Retried = retried; Check = check; dt = DBhelp.XML2Table(Xml[0]); cm = (CurrencyManager)this.BindingContext[dt]; textEdit1.DataBindings.Add("Text", dt, "AgencyLeaf"); textEdit2.DataBindings.Add("Text", dt, "SysLogID"); textEdit3.DataBindings.Add("Text", dt, "StationID"); textEdit4.DataBindings.Add("Text", dt, "RoleLeaf"); textEdit5.DataBindings.Add("Text", dt, "CommunityID"); textEdit6.DataBindings.Add("Text", dt, "UserCode"); textEdit7.DataBindings.Add("Text", dt, "ExCode"); textEdit8.DataBindings.Add("Text", dt, "UserID"); textEdit9.DataBindings.Add("Text", dt, "PassWord"); textEdit10.DataBindings.Add("Text", dt, "PONumber"); textEdit11.DataBindings.Add("Text", dt, "POLineNumber"); textEdit12.DataBindings.Add("Text", dt, "POReceiptActionType"); textEdit13.DataBindings.Add("Text", dt, "POLineUM"); textEdit14.DataBindings.Add("Text", dt, "ReceiptQuantityMove1"); textEdit15.DataBindings.Add("Text", dt, "Stockroom1"); textEdit16.DataBindings.Add("Text", dt, "Bin1"); textEdit17.DataBindings.Add("Text", dt, "InventoryCategory1"); textEdit18.DataBindings.Add("Text", dt, "POLineType"); textEdit19.DataBindings.Add("Text", dt, "ItemNumber"); textEdit20.DataBindings.Add("Text", dt, "NewLot"); textEdit21.DataBindings.Add("Text", dt, "LotNumberAssignmentPolicy"); textEdit22.DataBindings.Add("Text", dt, "LotNumberDefault"); if (dt.Columns.Contains("VendorLotNumber")) { textEdit23.DataBindings.Add("Text", dt, "VendorLotNumber"); } else { textEdit23.Text = ""; } if (dt.Columns.Contains("FirstReceiptDate")) { textEdit24.DataBindings.Add("Text", dt, "FirstReceiptDate"); } else { textEdit24.Text = ""; } textEdit25.DataBindings.Add("Text", dt, "PromisedDate"); textEdit26.DataBindings.Add("Text", dt, "POReceiptDate"); textEdit27.Text = skuid; cm.Position = 0; // 如 index = 0; if(dtmaterial != null) { textEdit28.DataBindings.Add("Text", dtmaterial, "LotNumber"); textEdit29.DataBindings.Add("Text", dtmaterial, "RecvBatchNo"); textEdit30.DataBindings.Add("Text", dtmaterial, "MaterialTrackID"); textEdit31.DataBindings.Add("Text", dtmaterial, "QtyInStore"); check[0][1] = check[0][2] = dtmaterial.Rows[0]["RecvBatchNo"].ToString(); check[1][1] = check[1][2] = dtmaterial.Rows[0]["QtyInStore"].ToString(); } else { this.checkEdit2.Enabled = false; this.checkEdit3.Enabled = false; } if (errinfo.Trim() != "") { this.textBox1.WordWrap = true; this.textBox1.Text = errinfo; } if (Retried[0] == "True") { this.checkEdit1.Checked = true; this.simpleButton1.Enabled = false; this.btn_delete.Enabled = false; } else { this.checkEdit1.Checked = false; } } private void simpleButton1_Click(object sender, EventArgs e) { cm.EndCurrentEdit();//结束当前编辑操作 if (dt.Rows.Count > 0) { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(Xml[0]); for (int i = 0; i < dt.Columns.Count; i++) { if (xdoc.FirstChild.FirstChild.Attributes[i] != null) { xdoc.FirstChild.FirstChild.Attributes[i].InnerText = dt.Rows[0][i].ToString(); } } Xml[0] = xdoc.InnerXml; if (Check[1][0] == "True") { Check[1][1] = this.textEdit31.Text; if (Check[1][1] == Check[1][2]) { Check[1][0] = "False"; } } if (Check[0][0] == "True") { if (Check[0][1] == Check[0][2]) { Check[0][0] = "False"; } } this.DialogResult = DialogResult.OK; } } private void simpleButton2_Click(object sender, EventArgs e) { DataTable _dt; string sql =""; if (textEdit22.Text.Length == 14) sql = string.Format("select ITEM,ITEM_DESC,BIN,QTY_BY_LOC,LOT from ERP.FSDBMR.dbo.StockDetail where ITEM = '{0}' AND LOT LIKE '{1}%'", textEdit19.Text, textEdit22.Text.Substring(0, textEdit22.Text.Length - 3)); else if (textEdit22.Text.Length== 11) sql = string.Format("select ITEM,ITEM_DESC,BIN,QTY_BY_LOC,LOT from ERP.FSDBMR.dbo.StockDetail where ITEM = '{0}' AND LOT LIKE '{1}%'", textEdit19.Text, textEdit22.Text); _dt = DBhelp.Query(sql).Tables["ds"]; frmMaterialIn4Shift f = new frmMaterialIn4Shift(_dt); f.ShowDialog(); } private void btn_serch_Click(object sender, EventArgs e) { DataTable _dt; string sql = string.Format("select ITEM_DESC,BIN,QTY_BY_LOC from ERP.FSDBMR.dbo.StockDetail where ITEM = '{0}' AND LOT = '{1}'",textEdit19.Text,textEdit22.Text); _dt = DBhelp.Query(sql).Tables["ds"]; textEdit32.DataBindings.Add("Text", _dt, "ITEM_DESC"); textEdit33.DataBindings.Add("Text", _dt, "QTY_BY_LOC"); textEdit34.DataBindings.Add("Text", _dt, "BIN"); if(_dt.Rows.Count<=0) { textEdit32.Text = "无记录"; textEdit33.Text = "无记录"; textEdit34.Text = "无记录"; } this.btn_serch.Enabled = false; } private void btn_delete_Click(object sender, EventArgs e) { if (Retried[0] == "False") { DialogResult result = MessageBox.Show( "您要删除这条信息吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); if (result == DialogResult.OK) { XtraMessageBox.Show( "当前功能正在紧张施工中!", "工程部", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.Abort; } } else { MessageBox.Show("该记录的Retried值为1,无法再删除!"); } } private void checkEdit2_CheckedChanged(object sender, EventArgs e) { if (checkEdit2.Checked == true) { textEdit29.Text = textEdit22.Text; Check[0][1] = textEdit22.Text; Check[0][0] = "True"; } else { textEdit29.Text = Check[0][2]; Check[0][0] = "False"; } } private void checkEdit3_CheckedChanged(object sender, EventArgs e) { if (this.checkEdit3.Checked == true) { Check[1][0] = "True"; this.textEdit31.ReadOnly = false; } else { Check[1][0] = "False"; this.textEdit31.Text = Check[1][2]; this.textEdit31.ReadOnly = true; } } private void textEdit22_EditValueChanged(object sender, EventArgs e) { if (this.checkEdit2.Checked == true) { textEdit29.Text = textEdit22.Text; Check[0][1] = textEdit22.Text; } } private void PORVForm_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.DialogResult = DialogResult.Cancel; } } } }
using UnityEngine; public class PlayerMovement : MonoBehaviour { [SerializeField] float speed; private Rigidbody playerRB; public void Start() { playerRB = this.gameObject.GetComponent<Rigidbody>(); } private void FixedUpdate() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 moveVector = transform.right * horizontal + transform.forward * vertical; // Vector3 moveVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); // playerRB.MovePosition(transform.position + moveVector.normalized * speed * Time.deltaTime); playerRB.MovePosition(transform.position + moveVector * speed * Time.deltaTime); // Vector3 inputVector = new Vector3(horizontal, 0, Input.GetAxisRaw("Vertical")); // playerRB.velocity = (inputVector * speed) + new Vector3(0, playerRB.velocity.y, 0); } }
/* * 2020 Microsoft Corp * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “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 COPYRIGHT OWNER OR 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 System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System.Security.Claims; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.Formatters.Internal; using Hl7.Fhir.Model; using Hl7.Fhir.Serialization; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; namespace FHIRProxy { public static class SecureLink { public static string _bearerToken; private static object _lock = new object(); private static string[] allowedresources = { "Patient", "Practitioner", "RelatedPerson" }; private static string[] validcmds = { "link", "unlink", "list" }; [FHIRProxyAuthorization] [FunctionName("SecureLink")] public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "manage/{cmd}/{res}/{id}/{name}")] HttpRequest req, ILogger log, ClaimsPrincipal principal, string cmd, string res, string id,string name) { log.LogInformation("SecureLink Function Invoked"); //Is the principal authenticated if (!Utils.isServerAccessAuthorized(req)) { return new ContentResult() { Content = "User is not Authenticated", StatusCode = (int)System.Net.HttpStatusCode.Unauthorized }; } if (!Utils.inServerAccessRole(req,"A")) { return new ContentResult() { Content = "User does not have suffiecient rights (Administrator required)", StatusCode = (int)System.Net.HttpStatusCode.Unauthorized }; } if (string.IsNullOrEmpty(cmd) || !validcmds.Any(cmd.Contains)) { return new BadRequestObjectResult("Invalid Command....Valid commands are link, unlink and list"); } //Are we linking the correct resource type if (string.IsNullOrEmpty(res) || !allowedresources.Any(res.Contains)) { return new BadRequestObjectResult("Resource must be Patient,Practitioner or RelatedPerson"); } ClaimsIdentity ci = (ClaimsIdentity)principal.Identity; string aadten = (string.IsNullOrEmpty(ci.Tenant()) ? "Unknown" : ci.Tenant()); FhirJsonParser _parser = new FhirJsonParser(); _parser.Settings.AcceptUnknownMembers = true; _parser.Settings.AllowUnrecognizedEnums = true; //Get a FHIR Client so we can talk to the FHIR Server log.LogInformation($"Instanciating FHIR Client Proxy"); FHIRClient fhirClient = FHIRClientFactory.getClient(log); int i_link_days = 0; int.TryParse(System.Environment.GetEnvironmentVariable("LINK_DAYS"), out i_link_days); if (i_link_days == 0) i_link_days = 365; //Load the resource to Link var fhirresp = fhirClient.LoadResource(res + "/" + id, null, false, req.Headers); var lres = _parser.Parse<Resource>((string)fhirresp.Content); if (lres.ResourceType == Hl7.Fhir.Model.ResourceType.OperationOutcome) { return new BadRequestObjectResult(lres.ToString()); } CloudTable table = Utils.getTable(); switch (cmd) { case "link": LinkEntity linkentity = new LinkEntity(res, aadten + "-" + name); linkentity.ValidUntil = DateTime.Now.AddDays(i_link_days); linkentity.LinkedResourceId = id; Utils.setLinkEntity(table, linkentity); return new OkObjectResult($"Identity: {name} in directory {aadten} is now linked to {res}/{id}"); case "unlink": LinkEntity delentity = Utils.getLinkEntity(table, res, aadten + "-" + name); if (delentity==null) return new OkObjectResult($"Resource {res}/{id} has no links to Identity {name} in directory {aadten}"); Utils.deleteLinkEntity(table,delentity); return new OkObjectResult($"Identity: {name} in directory {aadten} has been unlinked from {res}/{id}"); case "list": LinkEntity entity = Utils.getLinkEntity(table, res, aadten + "-" + name); if (entity != null) return new OkObjectResult($"Resource {res}/{id} is linked to Identity: {name} in directory {aadten}"); else return new OkObjectResult($"Resource {res}/{id} has no links to Identity {name} in directory {aadten}"); } return new OkObjectResult($"No action taken Identity: {name}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Z.Framework.Model { /// <summary> /// 用户基本信息 /// </summary> public class Account_Info { public string Account { set; get; } public string Password { set { if(value == string.Empty) { throw new Exception("密码不能为空"); } Md5Password = Common.Utilities.Md5(value); } } public string Md5Password { private set; get; } /// <summary> /// 登录凭证 /// </summary> public string Session { set; get; } /// <summary> /// 凭证过期时间 /// </summary> public DateTime? SessionOffTime { set; get; } public bool LoginState { set; get; } public DateTime? LoginTime { set; get; } public DateTime? LogoutTime { set; get; } } }
using Domain.FixingDomain; using Repositories.Entities; using System; using System.Collections.Generic; using System.Linq; namespace Repositories.Repository { public static class ExchangeTableEnumerableExtensions { public static IEnumerable<Fixing> ConvertToEnumerableDomain(this IEnumerable<ExchangeTable> source) { if (source.Count() == 0) return new List<Fixing>(); return source.First().Rates.Select(c => new Fixing { CurrencyCode = c.Code, Currency = c.Currency, Rate = Convert.ToDecimal(c.Mid) }); } } }
// Copyright (c) Simple Injector Contributors. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for license information. namespace SimpleInjector { using System; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using SimpleInjector.Internals; #if !PUBLISH && (NET40 || NET45) /// <summary>Common Container methods specific for the full .NET version of Simple Injector.</summary> #endif #if NET40 || NET45 public partial class Container { private static readonly LazyEx<ModuleBuilder> LazyBuilder = new LazyEx<ModuleBuilder>(() => AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName("SimpleInjector.Compiled"), AssemblyBuilderAccess.Run) .DefineDynamicModule("SimpleInjector.CompiledModule")); internal static ModuleBuilder ModuleBuilder => LazyBuilder.Value; } #endif }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace IPCamFtpEvt { class Program { private const int THREAD_STACK_SIZE = 0x8000; private static string gHttpTimeServer = "google.com"; private static string gDataDirectory = string.Empty; private static int gFtpListenPort = 21000; private static int gPassiveModeListenPort = 21001; private static byte[] gDummyBuf = new byte [0x100000]; private static long gInternetTimeDelta = 0; static void Main(string[] args) { Console.Title = "FTP Server for IPCAM event reporting"; ParseCmdLnArgs(args); InitTimeBase(); StartDummyFtpPasvServer(); RunFtpServer(); } private static void ApplyUserConfig(string key, string value) { if (key.Equals("FtpPort", StringComparison.OrdinalIgnoreCase)) { gFtpListenPort = (int)ushort.Parse(value); } else if (key.Equals("FtpPassivePort", StringComparison.OrdinalIgnoreCase)) { gPassiveModeListenPort = (int)ushort.Parse(value); } else if (key.Equals("TimeServer", StringComparison.OrdinalIgnoreCase)) { gHttpTimeServer = value; } else if (key.Equals("DataDirectory", StringComparison.OrdinalIgnoreCase)) { gDataDirectory = value; } // } private static void ParseCmdLnArgs(string[] args) { if (args.Length < 1) { return; } var fileName = args[0]; var lines = File.ReadAllLines(fileName); foreach (var line in lines) { var pos = line.IndexOf(' '); if (pos < 0) { continue; } var key = line.Substring(0, pos).Trim(); var value = line.Substring(pos + 1); ApplyUserConfig(key, value); } // } private static void InitTimeBase() { var clock = new HttpGetTime(gHttpTimeServer); for (int i = 0; i < 120; ++i) { clock.GetTimeFromInternet(); if (clock.IsDownloadOK) { break; } Thread.Sleep(1000); } var t1 = clock.LocalTime; var t2 = clock.InternetTime; gInternetTimeDelta = (long)(t2 - t1).TotalSeconds; } private static void StartDummyFtpPasvServer() { var thread = new Thread(ThreadRunDummyFtpPasvServer, THREAD_STACK_SIZE); thread.IsBackground = true; thread.Start(); } private static Socket CreateListenSock(int port) { var listenSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSock.Bind(new IPEndPoint(IPAddress.Any, port)); listenSock.Listen(8); return listenSock; } private static void ThreadRunDummyFtpPasvServer() { var listenSock = CreateListenSock(gPassiveModeListenPort); while (true) { var sock = listenSock.Accept(); if (null == sock) { break; } var handler = new FtpPasvHandler(sock, gDummyBuf); var thread = new Thread(handler.Run, THREAD_STACK_SIZE); thread.IsBackground = true; thread.Start(); } listenSock.Close(); } private static void RunFtpServer() { var listenSock = CreateListenSock(gFtpListenPort); while (true) { var sock = listenSock.Accept(); if (null == sock) { break; } var handler = new FtpHandler(sock); handler.InternetTimeDelta = gInternetTimeDelta; handler.PassiveModeListenPort = gPassiveModeListenPort; handler.DataDirectory = gDataDirectory; var thread = new Thread(handler.Run, THREAD_STACK_SIZE); thread.IsBackground = true; thread.Start(); } listenSock.Close(); } // } }
using Lanches_Mac.Models; using System.Collections.Generic; namespace Lanches_Mac.Repositories { public interface ILancheRepository { IEnumerable<Lanche> Lanches { get; } IEnumerable<Lanche> LanchePreferidos { get; } Lanche GetLancheById(int lancheId); } }
using Common.Data; using Common.Exceptions; using Common.Extensions; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Runtime.Serialization; namespace Entity { [DataContract] public partial class SystemScheduleColumns : IMappable { #region Constructors public SystemScheduleColumns() { } #endregion #region Public Properties /// <summary> /// Gets the name of the table to which this object maps. /// </summary> public string TableName { get { return "System_Schedule_Columns"; } } [DataMember] public Int32? Sched_ID { get; set; } [DataMember] public Int32? Column_ID { get; set; } [DataMember] public Int32? Column_Size { get; set; } [DataMember] public Int32? Sort_Order { get; set; } [DataMember] public string Override_Source { get; set; } [DataMember] public Int32? Override_Source_Is_SQL { get; set; } [DataMember] public string Display_Name { get; set; } [DataMember] public Int32? Hidden { get; set; } [DataMember] public Int32? Locked { get; set; } [DataMember] public DateTime? Effective_Date { get; set; } [DataMember] public DateTime? Inactivated_Date { get; set; } #endregion #region Public Methods public SystemScheduleColumns GetRecord(string connectionString, string sql, SqlParameter[] parameters = null) { SystemScheduleColumns result = null; using (Database database = new Database(connectionString)) { try { CommandType commandType = CommandType.Text; if (parameters != null) commandType = CommandType.StoredProcedure; using (DataTable table = database.ExecuteSelect(sql, commandType, parameters)) { if (table.HasRows()) { Mapper<SystemScheduleColumns> m = new Mapper<SystemScheduleColumns>(); result = m.MapSingleSelect(table); } } } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<SystemScheduleColumns> GetList(string connectionString, string sql, SqlParameter[] parameters = null) { List<SystemScheduleColumns> result = new List<SystemScheduleColumns>(); using (Database database = new Database(connectionString)) { try { CommandType commandType = CommandType.Text; if (parameters != null) commandType = CommandType.StoredProcedure; using (DataTable table = database.ExecuteSelect(sql, commandType, parameters)) { if (table.HasRows()) { Mapper<SystemScheduleColumns> m = new Mapper<SystemScheduleColumns>(); result = m.MapListSelect(table); } } } catch (Exception e) { throw new EntityException(sql, e); } } return result; } #endregion } }