text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class platformMove : MonoBehaviour { public Transform pos1, pos2; public float speed; public Transform startPos; public bool canMove; Vector3 nextPos; // Start is called before the first frame update void Start() { nextPos = startPos.position; } // Update is called once per frame void Update() { if(transform.position == pos1.position && canMove == true) { nextPos = pos2.position; } if (transform.position == pos2.position && canMove == true) { nextPos = pos1.position; } transform.position = Vector3.MoveTowards(transform.position, nextPos, speed * Time.deltaTime); } private void OnDrawGizmos() { Gizmos.DrawLine(pos1.position, pos2.position); } void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Player")) { canMove = true; collision.collider.transform.SetParent(transform); } } void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.CompareTag("Player")) { collision.collider.transform.SetParent(null); } } }
using LuaInterface; using RO; using SLua; using System; public class Lua_RO_HttpWWWSeveralRequests : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { HttpWWWSeveralRequests o = new HttpWWWSeveralRequests(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddOrder(IntPtr l) { int result; try { HttpWWWSeveralRequests httpWWWSeveralRequests = (HttpWWWSeveralRequests)LuaObject.checkSelf(l); HttpWWWRequestOrder order; LuaObject.checkType<HttpWWWRequestOrder>(l, 2, out order); httpWWWSeveralRequests.AddOrder(order); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SetCallBacks(IntPtr l) { int result; try { HttpWWWSeveralRequests httpWWWSeveralRequests = (HttpWWWSeveralRequests)LuaObject.checkSelf(l); Action<HttpWWWResponse> successCall; LuaDelegation.checkDelegate(l, 2, out successCall); Action<HttpWWWRequestOrder> failedCall; LuaDelegation.checkDelegate(l, 3, out failedCall); httpWWWSeveralRequests.SetCallBacks(successCall, failedCall); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StartRequest(IntPtr l) { int result; try { HttpWWWSeveralRequests httpWWWSeveralRequests = (HttpWWWSeveralRequests)LuaObject.checkSelf(l); httpWWWSeveralRequests.StartRequest(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Dispose(IntPtr l) { int result; try { HttpWWWSeveralRequests httpWWWSeveralRequests = (HttpWWWSeveralRequests)LuaObject.checkSelf(l); httpWWWSeveralRequests.Dispose(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.HttpWWWSeveralRequests"); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_HttpWWWSeveralRequests.AddOrder)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_HttpWWWSeveralRequests.SetCallBacks)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_HttpWWWSeveralRequests.StartRequest)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_HttpWWWSeveralRequests.Dispose)); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_HttpWWWSeveralRequests.constructor), typeof(HttpWWWSeveralRequests)); } }
namespace Dealership.Engine.Commands { using System.Collections.Generic; using System.Text; using Common; using Common.Enums; using Contracts; using Contracts.Factories; public class ShowUsers : Command { protected override bool CanExecute(string commandName) { var result = !string.IsNullOrWhiteSpace(commandName) && commandName.ToLower() == Constants.ShowUsersCommandName.ToLower(); return result; } protected override string StartExecute( IList<string> commandAsList, IVehicleFactory vehicleFactory, IDealershipFactory dealershipFactory, ICollection<IUser> users, IUser[] loggedUser) { const string StartLineText = "--USERS--"; if (loggedUser[0].Role != Role.Admin) { return Constants.YouAreNotAnAdmin; } var builder = new StringBuilder(); builder.AppendLine(StartLineText); var counter = 1; foreach (var user in users) { builder.AppendLine(string.Format("{0}. {1}", counter, user.ToString())); counter++; } return builder.ToString().Trim(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ProximaFase : MonoBehaviour { public string proximaFase; public GameObject proximaFaseUI; void Start(){ Time.timeScale = 1; } private void TrocarFase(){ PlayerPrefs.SetInt (proximaFase, 1); proximaFaseUI.SetActive (true); Time.timeScale = 0; } public void OnTriggerEnter2D(Collider2D coll){ if (coll.tag == "Player") TrocarFase (); } }
using Kuli; using Kuli.Configuration; using Kuli.Importing; using Kuli.Rendering; using Markdig; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Core; using Serilog.Events; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; var loggingLevelSwitch = new LoggingLevelSwitch(); var hostBuilder = Host.CreateDefaultBuilder(args) .ConfigureHostConfiguration(config => { config.AddYamlFile("config.yml"); }) .ConfigureLogging(logging => { logging.ClearProviders(); var logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Console() .MinimumLevel.ControlledBy(loggingLevelSwitch) .MinimumLevel.Override("Microsoft", LogEventLevel.Fatal) .CreateLogger(); logging.AddSerilog(logger); }) .ConfigureServices(services => { services.AddSingleton(loggingLevelSwitch); services.AddSingleton<FragmentDiscoveryService>(); services.AddSingleton<RawFragmentImporterService>(); services.AddSingleton<FragmentImportService>(); services.AddSingleton<TemplateImportService>(); services.AddSingleton<SiteRenderingContext>(); services.AddSingleton<FragmentRenderer>(); services.AddSingleton<PublishDirectoryWriter>(); services.AddSingleton<FragmentExportService>(); services.AddSingleton<StaticContentImportService>(); services.AddSingleton<StaticContentExportService>(); services.AddSingleton<KuliImportPipeline>(); services.AddSingleton<KuliExportPipeline>(); services.AddSingleton<PublishDirectoryCleanupService>(); services.AddOptions<LoggingOptions>().BindConfiguration(LoggingOptions.Section); services.AddOptions<DirectoryOptions>().BindConfiguration(DirectoryOptions.Section); services.AddHostedService<KuliExecutionService>(); services.AddSingleton( new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build()); services.AddSingleton(new MarkdownPipelineBuilder().UseAdvancedExtensions().Build()); }); hostBuilder.Build().Run();
using UnityEngine; using System.Collections; using UnityEditor; using System.Collections.Generic; [CustomEditor(typeof(fire_manager))] public class fvEditor : Editor { private bool foldfv = false; public override void OnInspectorGUI() { DrawDefaultInspector(); fire_manager fv = (fire_manager)target; foldfv = EditorGUILayout.Foldout (foldfv, "fire_manager"); if (foldfv) { EditorGUILayout.LabelField ("cnt", fv.fireballs.Count + ""); foreach (KeyValuePair<System.Guid, fireball> kp in fv.fireballs) { EditorGUILayout.ObjectField (kp.Key + "", kp.Value.target, typeof(GameObject)); } } EditorUtility.SetDirty( target ); } }
using Newtonsoft.Json; namespace CustomerManagement.Infrastructure.CrossCuting.Extensions { public static class JsonExtensions { public static string Serialize<T>(T obj) => JsonConvert.SerializeObject(obj, Formatting.Indented); public static T Deserialize<T>(string value) => JsonConvert.DeserializeObject<T>(value); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MediaManager.API.Models; using MediaManager.API.Repository; using MediaManager.DAL.DBEntities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; namespace MediaManager.API.Controllers { /// <summary> /// The API controller to handle tags related calls /// </summary> [Route("api/Tags/{contentId}/{id}")] public class TagController : Controller { TagRepository tagRepository; IUrlHelper urlHelper; /// <summary> /// Constructor of TagController /// </summary> /// <param name="tagRepository">Tag repository</param> /// <param name="urlHelper">URL Helper class to help create links</param> public TagController(TagRepository tagRepository, IUrlHelper urlHelper) { this.urlHelper = urlHelper; this.tagRepository = tagRepository; } /// <summary> /// Retrieves a list of tags for a particular item of a particular content type /// </summary> /// <param name="contentId">contentid denoting the media type </param> /// <param name="id">the id of the item for which tags are to be retrieved</param> /// <response code="200">Tags retrieved</response> /// <response code="400">Tags retrieval parameter has missing/invalid values</response> /// <response code="500">Oops! Can't retrieve tags entry right now</response> [ProducesResponseType(typeof(List<string>), 200)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "Reader")] [EnableCors("default")] [HttpGet(Name ="GetTags")] public async Task<IActionResult> GetTags(int contentId, int id) { if (contentId == 0 || id == 0) { return BadRequest(); } var result =await tagRepository.GetTags(contentId, id); if (result == null) { return new StatusCodeResult(500); } return Ok(result); } /// <summary> /// Creates tags for a particular item of a particular content type /// </summary> /// <param name="contentId">the id of content which dones the type of content</param> /// <param name="id">id</param> /// <param name="tags">List of tags to be added</param> /// <response code="201">Tags created</response> /// <response code="400">Tags creation parameter has missing/invalid values</response> /// <response code="500">Oops! Can't create tags entry right now</response> [ProducesResponseType(typeof(List<string>), 200)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "Writer")] [EnableCors("default")] [HttpPost] public async Task<IActionResult> AddTags(int contentId, int id,[FromBody] TagsInputDTO tags) { if (contentId == 0 || id == 0 || tags == null) { return BadRequest(); } var result = await tagRepository.AddTags(contentId, id, tags.tags); if (result == false) { return new StatusCodeResult(500); } return CreatedAtRoute("GetTags", new { contentId = contentId, id = id }); } /// <summary> /// Deletes tags for a particular item of a particular content type /// </summary> /// <param name="contentId">the id of content which dones the type of content</param> /// <param name="id">id</param> /// <param name="tags">List of tags to be deleted</param> /// <response code="201">Tags deleted</response> /// <response code="400">Tags deletion parameter has missing/invalid values</response> /// <response code="500">Oops! Can't delete tags entry right now</response> [ProducesResponseType(typeof(List<string>), 200)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "Reader")] [EnableCors("default")] [HttpDelete] public async Task<IActionResult> DeleteTags(int contentId, int id, [FromBody] TagsInputDTO tags) { if (contentId == 0 || id == 0 || tags == null) { return BadRequest(); } var result = await tagRepository.DeleteTags(contentId, id, tags.tags); if (result == false) { return new StatusCodeResult(500); } return CreatedAtRoute("GetTags", new { contentId = contentId, id = id }); } /// <summary> /// Creates tags for a particular item of a particulat content type /// </summary> /// <param name="contentId">the id of content which dones the type of content</param> /// <param name="id">id</param> /// <param name="patchDocument">list of json patch documents containing the update informations</param> /// <response code="201">Tags updated</response> /// <response code="400">Tags updation parameter has missing/invalid values</response> /// <response code="500">Oops! Can't update tags entry right now</response> [ProducesResponseType(typeof(List<string>), 200)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(500)] [Authorize(Policy = "Reader")] [EnableCors("default")] [HttpPatch] public async Task<IActionResult> UpdateTags(int contentId, int id, [FromBody] JsonPatchDocument<Tag> patchDocument) { try { if (contentId == 0 || id == 0 || patchDocument == null) { return BadRequest(); } var result = await tagRepository.GetEntity(contentId, id); if (result == null) { return NotFound(); } patchDocument.ApplyTo(result); } catch(Exception) { return new StatusCodeResult(500); } return CreatedAtRoute("GetTags", new { contentId = contentId, id =id }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Viking.AssemblyVersioning { public class MethodOverloadComparer { public MethodOverloadComparer(MethodInfo baseline, MethodInfo candidate) { Baseline = baseline; Candidate = candidate; } public MethodInfo Baseline { get; } public MethodInfo Candidate { get; } public bool ReturnTypeMatch => Baseline.ReturnType.FullName.Equals(Candidate.ReturnType.FullName); public bool AreBothGeneric => Baseline.ContainsGenericParameters == Candidate.ContainsGenericParameters; public bool GenericParametersMatch => EqualityComparer.IEnumerableEquality(Baseline.GetGenericArguments().Select(a => a.FullName), Candidate.GetGenericArguments().Select(a => a.FullName)); public bool ParametersMatch => GenericParametersMatch && EqualityComparer.IEnumerableEquality(Baseline.GetParameters(), Candidate.GetParameters(), FullEquals); public bool ParameterCountMatch => Baseline.GetParameters().Count() == Candidate.GetParameters().Count(); private bool MatchingAttributes(ParameterInfo x, ParameterInfo y) => x.Attributes == y.Attributes; private bool MatchingDefaultValues(ParameterInfo x, ParameterInfo y) => x.HasDefaultValue == y.HasDefaultValue; private bool FullEquals(ParameterInfo x, ParameterInfo y) { return x.Attributes == y.Attributes && x.HasDefaultValue == y.HasDefaultValue && x.Name.Equals(y.Name) && x.ParameterType.FullName.Equals(y.ParameterType.FullName) && x.Position == y.Position; } } }
 using FluentValidation; namespace WebApplication.Web.Models.Validation { public class ItemModelValidator : AbstractValidator<ItemModel> { public ItemModelValidator() { RuleFor(x => x.Name).NotEmpty(); } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("CraftingTray")] public class CraftingTray : MonoBehaviour { public CraftingTray(IntPtr address) : this(address, "CraftingTray") { } public CraftingTray(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public static CraftingTray Get() { return MonoClass.smethod_15<CraftingTray>(TritonHs.MainAssemblyPath, "", "CraftingTray", "Get", Array.Empty<object>()); } public void Hide() { base.method_8("Hide", Array.Empty<object>()); } public bool IsShown() { return base.method_11<bool>("IsShown", Array.Empty<object>()); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnDoneButtonReleased(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnDoneButtonReleased", objArray1); } public void OnMassDisenchantButtonOut(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnMassDisenchantButtonOut", objArray1); } public void OnMassDisenchantButtonOver(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnMassDisenchantButtonOver", objArray1); } public void OnMassDisenchantButtonReleased(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnMassDisenchantButtonReleased", objArray1); } public void SetMassDisenchantAmount() { base.method_8("SetMassDisenchantAmount", Array.Empty<object>()); } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void ToggleShowGolden(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("ToggleShowGolden", objArray1); } public void ToggleShowSoulbound(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("ToggleShowSoulbound", objArray1); } public void UpdateMassDisenchantAmount() { base.method_8("UpdateMassDisenchantAmount", Array.Empty<object>()); } public UIBButton m_doneButton { get { return base.method_3<UIBButton>("m_doneButton"); } } public int m_dustAmount { get { return base.method_2<int>("m_dustAmount"); } } public HighlightState m_highlight { get { return base.method_3<HighlightState>("m_highlight"); } } public PegUIElement m_massDisenchantButton { get { return base.method_3<PegUIElement>("m_massDisenchantButton"); } } public Material m_massDisenchantDisabledMaterial { get { return base.method_3<Material>("m_massDisenchantDisabledMaterial"); } } public Material m_massDisenchantMaterial { get { return base.method_3<Material>("m_massDisenchantMaterial"); } } public GameObject m_massDisenchantMesh { get { return base.method_3<GameObject>("m_massDisenchantMesh"); } } public UberText m_massDisenchantText { get { return base.method_3<UberText>("m_massDisenchantText"); } } public UberText m_potentialDustAmount { get { return base.method_3<UberText>("m_potentialDustAmount"); } } public CheckBox m_showGoldenCheckbox { get { return base.method_3<CheckBox>("m_showGoldenCheckbox"); } } public bool m_shown { get { return base.method_2<bool>("m_shown"); } } public CheckBox m_showSoulboundCheckbox { get { return base.method_3<CheckBox>("m_showSoulboundCheckbox"); } } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; namespace ProducerConsumer { class OrderTask : IComparable<OrderTask> { Random rand = new Random(); public Store store; public int AmountAvailable; public int AmountAttempted; public decimal Quote; public bool Success; public OrderTask(Store @out) { this.store = @out; } void Log(string msg) { Console.WriteLine( $"{store.Name}: {msg}" ); } public async Task GetOffer() { Log( "Getting offer" ); await Task.Delay( rand.Next( 3000 ) ); Quote = rand.Next( 1, 5 ); AmountAvailable = rand.Next( 1, 7 ) * 100; Log( $"Offer received.\t{Quote}\t{AmountAvailable}" ); } public async Task<bool> PlaceOrder(int amount) { AmountAttempted = amount; Log( $"Placing order for {AmountAttempted} @ {Quote}" ); await Task.Delay( rand.Next( 3000 ) ); Log( "Wager placed" ); if (rand.Next( 100 ) >= 50) return Success = true; else return Success = false; } public override string ToString() { return store.Name; } public int CompareTo([AllowNull] OrderTask other) { if (other is null) return 1; if (other.Quote > this.Quote) return 1; else if (other.Quote.Equals( this.Quote )) return 0; else return -1; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed; private Rigidbody2D rb2d; private Animator anim; public float jumpForce=35; public bool isGrounded; public Transform groundCheck; public float checkRadius; public LayerMask whatIsGround; public AudioClip jumpSound; AudioSource audioSource; internal static int moveInput; // void Awake() { rb2d = GetComponent<Rigidbody2D>(); // DontDestroyOnLoad(this.gameObject); } void Start() { // need to set audio source to use singular audio clip audioSource = GetComponent<AudioSource>(); anim = GetComponent<Animator>(); } void FixedUpdate() { //Jump Check isGrounded=Physics2D.OverlapCircle(groundCheck.position,checkRadius,whatIsGround); //Handle Player Movement Move(); } void Update(){ if(Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown("joystick button 0")){ Jump(); } } void Move(){ float moveInput = Input.GetAxis("Horizontal"); rb2d.velocity = new Vector2(moveInput * speed, rb2d.velocity.y); if ((anim.GetBool("facingRight") == false) && (moveInput > 0)) { anim.SetBool("facingRight", true); Flip(); } else if ((anim.GetBool("facingRight") == true) && (moveInput < 0)) { anim.SetBool("facingRight", false); Flip(); } } void Jump(){ if(isGrounded==true){ rb2d.velocity=Vector2.up*jumpForce; audioSource.PlayOneShot(jumpSound, 1F); } } public void Flip() { Vector3 Scaler = transform.localScale; Scaler.x *= -1; transform.localScale = Scaler; } }
using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { namespace Models { [Parallel] [Method(GeneralNames.LogTrace, Direction.ServerToClient)] [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Client")] [GenerateHandlerMethods] [GenerateRequestMethods(typeof(IClientLanguageServer), typeof(ILanguageServer))] public record LogTraceParams : IRequest { /// <summary> /// The message to be logged. /// </summary> public string Message { get; init; } = null!; /// <summary> /// Additional information that can be computed if the `trace` configuration is set to `'verbose'` /// </summary> [Optional] public string? Verbose { get; init; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Problem02BankАccounts.Customers; namespace Problem02BankАccounts.Accounts { class MortageAccount : Account, IDepositable { public MortageAccount(Customer holder, decimal balance, decimal interestRate) : base(holder, balance, interestRate) { } public override decimal CalculateInterest(int months) { if (Holder is CompanyCustomer && months < 13) { return InterestRate * months / 2; } if (Holder is IndividualCustomer && months < 7) { return 0; } return InterestRate * months; } public void Deposit(decimal amount) { Balance += amount; } public override string ToString() { return String.Format("Desposit account\n Holder {0}, Balance {1}, Interest Rate {2}", Holder, Balance, InterestRate); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SmartPower.Data { public class jobOrderResponse { public string machineId { get; set; } public string jobOrderId { get; set; } public string jobOrderNumber { get; set; } public int assemblyQty { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TranslateToCyrillic { public partial class ConvertForm : Form { public ConvertForm() { InitializeComponent(); } private void btnConvert_Click(object sender, EventArgs e) { string inputText = txtBoxInput.Text.Trim(); txtBoxOriginal.Text = txtBoxInput.Text; // Receive text input if (txtBoxInput.Text != "") { // Convert tokens to Cyrillic Letters ConvertString(ref inputText); } else { MessageBox.Show("A hole"); } txtBoxInput.Clear(); txtBoxInput.Focus(); } private void ConvertString(ref string inputText) { Conversion Conversion = new Conversion(); // List to hold the characters string convertedText; List<string> charList = new List<string>(); string letters; // Loop to assign the correct cyrillic text to each letter for (int i = 0; i < inputText.Length; i++) { // Initialize char values to be left alone if no letter corresponding letter is found char ch0 = '0'; char ch; char ch2 = '2'; // index values for other chars int h = i - 1; int j = i + 1; try { ch = inputText[i]; // if there is a letter after i, set ch2 if (j < inputText.Length) { ch2 = inputText[j]; } // If there is a letter before i, set ch0 if (h >= 0) { ch0 = inputText[h]; } // Go do the thing and bring in the cyrillic baby letters = Conversion.Letters(ref ch0, ref ch, ref ch2 ); charList.Add(letters); } catch (Exception ex) { MessageBox.Show(ex.Message); } } // convertedText = string.Join("", charList); // Display converted text txtBoxConverted.Text = convertedText; } ///// <summary> ///// Converts each letter to cyrillic ///// </summary> ///// <param name="ch"></param> ///// <returns></returns> //private string ConvertLetters(ref char ch, ref char ch2, ref char ch0) //{ //} private void btnClose_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.AccessControl; using System.Web; namespace bookingMVC.Models { /// <summary> /// test /// </summary> public class Booking { /// <summary> /// /// </summary> public int Id { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public virtual Order Order { get; set; } public virtual Room Room { get; set; } public virtual ICollection<Option> Options { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DogHueristic : HueristicScript { public override float Hueristic(int x, int y, Vector3 start, Vector3 goal, GridScript gridScript) { /* * Developed by Chris Williams * * DEPTH FRIST SEARCH DOG BUILD * STATS: * DPTH ***** * BRTH * * CUTE ***** * * BUILD OVERVIEW: * * This is a Princess build heavily spec'd in depth first search. * Its hueristic is based on Manhattan distance formula. The Manhattan * distance is a fast-to-compute to exit. * * The Manhattan distance is distance between two points if you were * only allowed to walk on paths that were at 90-degree angles from * each other (similar to walking the streets of Manhattan). * * Manhattan Distance Formula: * Distance = | cellx - exitx | + | celly - exity | * * Build Formula: * Hueristic = (|pos.X - goal.X| + |pos.Y - goal.Y|) ^ 3 * * Why multiply by a power of 3: * To discourage searching other paths and go untilthe goal is found. * A power of 2 does not create enough distance between the current cost * and a potential new cost and a power greater than 3 does not add anything * more to the depth first search calculation. * * Build Strengths: * On maps with costs that are all the sameand have limited obstacles * the early start time compared to other builds will secure you an * easy win. * * Build Weaknesses: * On maps with many obstacles this heavily greedy-based approach will * get you in trouble. */ return Mathf.Pow(Mathf.Abs(x - goal.x) + Mathf.Abs(y - goal.y), 3); } }
using System.Threading; using System.Threading.Tasks; using Dapper; using MediatR; using Npgsql; namespace DDDSouthWest.Domain.Features.Account.Admin.ManageNews.DeleteNews { public class DeleteNews { public class Command : IRequest { public int Id { get; set; } } public class Handler : IRequestHandler<Command> { private readonly ClientConfigurationOptions _options; public Handler(ClientConfigurationOptions options) { _options = options; } public async Task<Unit> Handle(Command message, CancellationToken cancellationToken) { using (var connection = new NpgsqlConnection(_options.Database.ConnectionString)) { await connection.ExecuteAsync("UPDATE news SET IsDeleted=TRUE WHERE Id = @Id", new { Id = message.Id }); } return Unit.Value; } } } }
using System; namespace B1_04_Auto { internal class Test { #region Methods // Objektmethoden private void Run() { // Autos erzeugen Auto auto1 = new Auto("VW","Passat",2011,15000.0); Auto auto2 = new Auto("BMW","X6",2015,28500.0); Auto auto3 = new Auto("Mercedes-Benz","B190",2015,21000.0); // Autos ausgeben Console.WriteLine( auto1.AsString() ); Console.WriteLine( auto2.AsString() ); Console.WriteLine( auto3.AsString() ); // Fahren simulieren für ein Auto Console.WriteLine(); auto1.Anlassen(); auto1.Gasgeben(30); auto1.Bremsen(10); auto1.Lenken(+15); auto1.Lenken(0); auto1.Bremsen(20); auto1.Abschalten(); } private static void Main(string[] args) { new Test().Run(); Console.ReadKey(); } #endregion } }
using System; using System.Collections.Generic; using ApiPomar.Models; namespace ApiPomar.Repositorio { public interface IArvoreRepository { void add(Arvores user); IEnumerable<Arvores> GettAll(); Arvores Find(long id); void Remove(long id); void Update(Arvores user); IEnumerable<Arvores> GetAll(); } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_AvatarTarget : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.AvatarTarget"); LuaObject.addMember(l, 0, "Root"); LuaObject.addMember(l, 1, "Body"); LuaObject.addMember(l, 2, "LeftFoot"); LuaObject.addMember(l, 3, "RightFoot"); LuaObject.addMember(l, 4, "LeftHand"); LuaObject.addMember(l, 5, "RightHand"); LuaDLL.lua_pop(l, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Device { public enum DeviceUseMode { Unknown, Laptop, Tablet } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace IOo { public static class ArchivoTexto { public static bool Guardar (string path, string texto) { StreamWriter sw = new StreamWriter(path, true); sw.WriteLine(texto); sw.Close(); return true; } public static string Leer (string path) { if (!(File.Exists(path))) { throw new FileNotFoundException(); } StreamReader sr = new StreamReader(path); string str = sr.ReadToEnd(); sr.Close(); return str; } } }
using AudioVisualizer; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using TK_Recorder.Capture; using TK_Recorder.Model; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.ExtendedExecution.Foreground; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Graphics.Capture; using Windows.Graphics.DirectX.Direct3D11; using Windows.Media.Audio; using Windows.Media.Capture; using Windows.Media.Devices; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.ApplicationModel; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace TK_Recorder { public sealed partial class MainPage : Page { private IDirect3DDevice screenDevice; private Encoder screenCapture; private GraphicsCaptureItem captureItem = null; private MediaCapture mediaCapture; private LowLagMediaRecording mediaRecording; private AudioGraph audioGraph; private StorageFolder storageFolder = null; private DispatcherTimer _timer = new DispatcherTimer(); private long _timerCount = 0; public MainPage() { InitializeComponent(); if (!GraphicsCaptureSession.IsSupported()) { IsEnabled = false; var dialog = new MessageDialog( "Screen capture is not supported on this device for this release of Windows!", "Screen capture unsupported"); var ignored = dialog.ShowAsync(); return; } // initialize screen recording screenDevice = Direct3D11Helpers.CreateDevice(); // connect to the powerpoint app service App.AppServiceConnected += MainPage_AppServiceConnected; _timer.Interval = new TimeSpan(0, 0, 1); _timer.Tick += _timer_Tick; } private void _timer_Tick(object sender, object e) { _timerCount += 1; TimeSpan time = TimeSpan.FromSeconds(_timerCount); TimerCounter.Text = time.ToString(@"hh\:mm\:ss"); } #region Device initialization private void PopulateVideoDeviceProperties(MediaStreamType streamType, ComboBox comboBox, bool showFrameRate = true) { // query all properties of the specified video stream type IEnumerable<StreamPropertiesHelper> allStreamProperties = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(streamType) .Select(x => new StreamPropertiesHelper(x)); // order them by resolution then frame rate allStreamProperties = allStreamProperties .OrderByDescending(x => x.Height * x.Width) .ThenByDescending(x => x.FrameRate); // populate the combo box with the entries foreach (var property in allStreamProperties) { var comboBoxItem = new ComboBoxItem(); comboBoxItem.Content = property.GetFriendlyName(showFrameRate); comboBoxItem.Tag = property; comboBox.Items.Add(comboBoxItem); } var settings = AppSettingsContainer.GetCachedSettings(); comboBox.SelectedItem = WebcamComboBox.Items.Where(x => (x as ComboBoxItem).Content.ToString() == settings.WebcamQuality).FirstOrDefault(); } private async Task InitAudioMeterAsync() { var result = await AudioGraph.CreateAsync(new AudioGraphSettings(Windows.Media.Render.AudioRenderCategory.Speech)); if (result.Status == AudioGraphCreationStatus.Success) { this.audioGraph = result.Graph; var audioDevice = (AudioDeviceComboBox.SelectedItem as ComboBoxItem); if (audioDevice == null) return; var microphone = await DeviceInformation.CreateFromIdAsync(audioDevice.Tag.ToString()); var inProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); var inputResult = await this.audioGraph.CreateDeviceInputNodeAsync(MediaCategory.Speech, inProfile.Audio, microphone); if (inputResult.Status != AudioDeviceNodeCreationStatus.Success) { var msg = new MessageDialog("Device is not available"); await msg.ShowAsync(); return; } this.audioGraph.Start(); var source = PlaybackSource.CreateFromAudioNode(inputResult.DeviceInputNode); AudioDiscreteVUBar.Source = source.Source; } } private async Task PopulateAudioAndVideoDevicesAsync() { // Finds all video capture devices var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); foreach (var device in videoDevices) { var comboBoxItem = new ComboBoxItem(); comboBoxItem.Content = device.Name; comboBoxItem.Tag = device.Id; WebcamDeviceComboBox.Items.Add(comboBoxItem); } // find all audio devices var audioDevices = await DeviceInformation.FindAllAsync(DeviceClass.AudioCapture); foreach (var device in audioDevices) { var comboBoxItem = new ComboBoxItem(); comboBoxItem.Content = device.Name; comboBoxItem.Tag = device.Id; AudioDeviceComboBox.Items.Add(comboBoxItem); } } private async Task InitWebcamAsync(string videoDeviceId, string audioDeviceId) { if (mediaCapture != null) { await mediaCapture.StopPreviewAsync(); } // create new media capture mediaCapture = new MediaCapture(); mediaCapture.RecordLimitationExceeded += CaptureManager_RecordLimitationExceeded; await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings() { VideoDeviceId = videoDeviceId, AudioDeviceId = audioDeviceId }); WebcamPreview.Source = mediaCapture; await mediaCapture.StartPreviewAsync(); } #endregion #region Settings private async Task LoadSettings() { var settings = AppSettingsContainer.GetCachedSettings(); // load quality settings var names = new List<string> { nameof(VideoEncodingQuality.HD1080p), nameof(VideoEncodingQuality.HD720p), nameof(VideoEncodingQuality.Uhd2160p) }; QualityComboBox.ItemsSource = names; QualityComboBox.SelectedIndex = names.IndexOf(settings.Quality.ToString()); var frameRates = new List<string> { "15fps", "30fps", "60fps" }; FrameRateComboBox.ItemsSource = frameRates; FrameRateComboBox.SelectedIndex = frameRates.IndexOf($"{settings.FrameRate}fps"); UseCaptureItemSizeCheckBox.IsChecked = settings.UseSourceSize; AdaptBitrateCheckBox.IsChecked = settings.AdaptBitrate; // load default storage path if (!string.IsNullOrEmpty(settings.StorageFolder)) { try { storageFolder = await StorageFolder.GetFolderFromPathAsync(settings.StorageFolder); FolderName.Text = settings.StorageFolder; } catch { var dialog = new MessageDialog( "Previous storage directory does not exist anymore. Please select a new directory.", "Directory not found or not enough permissions"); await dialog.ShowAsync(); } } // set first webcam device WebcamDeviceComboBox.SelectedItem = WebcamDeviceComboBox.Items.Where(x => (x as ComboBoxItem).Tag.ToString() == settings.WebcamDeviceId).FirstOrDefault(); AudioDeviceComboBox.SelectedItem = AudioDeviceComboBox.Items.Where(x => (x as ComboBoxItem).Tag.ToString() == settings.AudioDeviceId).FirstOrDefault(); } private AppSettings GetCurrentSettings() { try { var quality = AppSettingsContainer.ParseEnumValue<VideoEncodingQuality>((string)QualityComboBox.SelectedItem); var frameRate = uint.Parse(((string)FrameRateComboBox.SelectedItem).Replace("fps", "")); var useSourceSize = UseCaptureItemSizeCheckBox.IsChecked.Value; var adaptBitrate = AdaptBitrateCheckBox.IsChecked.Value; var webcamQuality = (WebcamComboBox.SelectedItem as ComboBoxItem).Content.ToString(); return new AppSettings { Quality = quality, FrameRate = frameRate, UseSourceSize = useSourceSize, AudioDeviceId = (AudioDeviceComboBox.SelectedItem as ComboBoxItem).Tag.ToString(), WebcamDeviceId = (WebcamDeviceComboBox.SelectedItem as ComboBoxItem).Tag.ToString(), WebcamQuality = webcamQuality, AdaptBitrate = adaptBitrate, StorageFolder = storageFolder.Path, WebcamExposure = (long)ExposureSlider.Value, WebcamWhiteBalance = (uint)WbSlider.Value, WebcamExposureAuto = ExposureAutoCheckBox.IsChecked.HasValue ? ExposureAutoCheckBox.IsChecked.Value : true, WebcamWhiteBalanceAuto = WbAutoCheckBox.IsChecked.HasValue ? WbAutoCheckBox.IsChecked.Value : true }; } catch { return new AppSettings(); } } public void CacheCurrentSettings() { var settings = GetCurrentSettings(); AppSettingsContainer.CacheSettings(settings); } #endregion #region Webcam settings private void SetExposureControls() { // exposure control var exposureControl = mediaCapture.VideoDeviceController.ExposureControl; if (exposureControl.Supported) { ExposureAutoCheckBox.Visibility = Visibility.Visible; ExposureSlider.Visibility = Visibility.Visible; ExposureAutoCheckBox.IsChecked = exposureControl.Auto; ExposureSlider.Minimum = exposureControl.Min.Ticks; ExposureSlider.Maximum = exposureControl.Max.Ticks; ExposureSlider.StepFrequency = exposureControl.Step.Ticks; ExposureSlider.ValueChanged -= ExposureSlider_ValueChanged; var value = exposureControl.Value; ExposureSlider.Value = value.Ticks; ExposureSlider.ValueChanged += ExposureSlider_ValueChanged; } else { var exposure = mediaCapture.VideoDeviceController.Exposure; double value; if (exposure.TryGetValue(out value)) { ExposureSlider.Minimum = exposure.Capabilities.Min; ExposureSlider.Maximum = exposure.Capabilities.Max; ExposureSlider.StepFrequency = exposure.Capabilities.Step; ExposureSlider.ValueChanged -= ExposureSlider_ValueChanged; ExposureSlider.Value = value; ExposureSlider.ValueChanged += ExposureSlider_ValueChanged; } else { ExposureSlider.Visibility = Visibility.Collapsed; } bool autoValue; if (exposure.TryGetAuto(out autoValue)) { ExposureAutoCheckBox.IsChecked = autoValue; } else { ExposureAutoCheckBox.Visibility = Visibility.Collapsed; } } } private void SetWhiteBalanceControl() { // white balance control var whiteBalanceControl = mediaCapture.VideoDeviceController.WhiteBalanceControl; if (whiteBalanceControl.Supported) { WbSlider.Visibility = Visibility.Visible; WbComboBox.Visibility = Visibility.Visible; if (WbComboBox.ItemsSource == null) { WbComboBox.ItemsSource = Enum.GetValues(typeof(ColorTemperaturePreset)).Cast<ColorTemperaturePreset>(); } WbComboBox.SelectedItem = whiteBalanceControl.Preset; if (whiteBalanceControl.Max - whiteBalanceControl.Min > whiteBalanceControl.Step) { WbSlider.Minimum = whiteBalanceControl.Min; WbSlider.Maximum = whiteBalanceControl.Max; WbSlider.StepFrequency = whiteBalanceControl.Step; WbSlider.ValueChanged -= WbSlider_ValueChanged; WbSlider.Value = whiteBalanceControl.Value; WbSlider.ValueChanged += WbSlider_ValueChanged; } else { WbSlider.Visibility = Visibility.Collapsed; } } else { WbComboBox.Visibility = Visibility.Collapsed; var whitebalance = mediaCapture.VideoDeviceController.WhiteBalance; double value; if (whitebalance.TryGetValue(out value)) { WbSlider.Minimum = whitebalance.Capabilities.Min; WbSlider.Maximum = whitebalance.Capabilities.Max; WbSlider.StepFrequency = whitebalance.Capabilities.Step; WbSlider.ValueChanged -= WbSlider_ValueChanged; WbSlider.Value = value; WbSlider.ValueChanged += WbSlider_ValueChanged; } else { WbSlider.Visibility = Visibility.Collapsed; } bool autoValue; if (whitebalance.TryGetAuto(out autoValue)) { WbAutoCheckBox.Visibility = Visibility.Visible; WbAutoCheckBox.IsChecked = autoValue; WbAutoCheckBox.Checked += WbCheckBox_CheckedChanged; WbAutoCheckBox.Unchecked += WbCheckBox_CheckedChanged; } } } private void WbCheckBox_CheckedChanged(object sender, RoutedEventArgs e) { if (mediaCapture.VideoDeviceController.WhiteBalance.Capabilities.AutoModeSupported) { mediaCapture.VideoDeviceController.WhiteBalance.TrySetAuto(WbAutoCheckBox.IsChecked.Value); if (!WbAutoCheckBox.IsChecked.Value) { mediaCapture.VideoDeviceController.WhiteBalance.TrySetValue(WbSlider.Value); } } } private async void WebcamComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem; if (selectedItem == null) return; var encodingProperties = (selectedItem.Tag as StreamPropertiesHelper).EncodingProperties; await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, encodingProperties); SetExposureControls(); SetWhiteBalanceControl(); // load settings var settings = AppSettingsContainer.GetCachedSettings(); if (ExposureAutoCheckBox.Visibility == Visibility.Visible && ExposureSlider.Visibility == Visibility.Visible) { ExposureSlider.Value = settings.WebcamExposure; ExposureAutoCheckBox.IsChecked = settings.WebcamExposureAuto; } if (WbSlider.Visibility == Visibility.Visible) { WbSlider.Value = settings.WebcamWhiteBalance; } if (WbAutoCheckBox.Visibility == Visibility.Visible) { WbAutoCheckBox.IsChecked = settings.WebcamWhiteBalanceAuto; } } catch (Exception ex) { var msg = new MessageDialog("The device is not ready."); await msg.ShowAsync(); } } private async void WebcamDeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var webcamDevice = WebcamDeviceComboBox.SelectedItem as ComboBoxItem; var audioDevice = AudioDeviceComboBox.SelectedItem as ComboBoxItem; if (webcamDevice == null || audioDevice == null) return; try { await InitWebcamAsync(webcamDevice.Tag.ToString(), audioDevice.Tag.ToString()); PopulateVideoDeviceProperties(MediaStreamType.VideoRecord, WebcamComboBox, true); } catch (Exception ex) { var msg = new MessageDialog("Unauthorized access to video and audio recording. Please change setting in Windows settings."); await msg.ShowAsync(); } } private async void AudioDeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var webcamDevice = WebcamDeviceComboBox.SelectedItem as ComboBoxItem; var audioDevice = AudioDeviceComboBox.SelectedItem as ComboBoxItem; if (webcamDevice == null || audioDevice == null) return; try { await InitWebcamAsync(webcamDevice.Tag.ToString(), audioDevice.Tag.ToString()); PopulateVideoDeviceProperties(MediaStreamType.VideoRecord, WebcamComboBox, true); await InitAudioMeterAsync(); } catch (UnauthorizedAccessException ex) { var msg = new MessageDialog("Unauthorized access to video and audio recording. Please change setting in Windows settings."); await msg.ShowAsync(); } } private async void ExposureSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { var value = TimeSpan.FromTicks((long)(sender as Slider).Value); if (mediaCapture.VideoDeviceController.ExposureControl.Supported) { await mediaCapture.VideoDeviceController.ExposureControl.SetValueAsync(value); } else { mediaCapture.VideoDeviceController.Exposure.TrySetValue((long)(sender as Slider).Value); } } private async void ExposureCheckBox_CheckedChanged(object sender, RoutedEventArgs e) { var autoExposure = ((sender as CheckBox).IsChecked == true); if (mediaCapture.VideoDeviceController.ExposureControl.Supported) { await mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(autoExposure); } else { mediaCapture.VideoDeviceController.Exposure.TrySetAuto(autoExposure); if (!autoExposure) { mediaCapture.VideoDeviceController.Exposure.TrySetValue(ExposureSlider.Value); } } } private async void WbComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selected = (ColorTemperaturePreset)WbComboBox.SelectedItem; WbSlider.IsEnabled = (selected == ColorTemperaturePreset.Manual); await mediaCapture.VideoDeviceController.WhiteBalanceControl.SetPresetAsync(selected); } private async void WbSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { var value = (sender as Slider).Value; if (mediaCapture.VideoDeviceController.WhiteBalanceControl.Supported) { await mediaCapture.VideoDeviceController.WhiteBalanceControl.SetValueAsync((uint)value); } else { mediaCapture.VideoDeviceController.WhiteBalance.TrySetValue(value); } } #endregion #region Recording private async void ToggleButton_Checked(object sender, RoutedEventArgs e) { var button = (ToggleButton)sender; // get storage folder if (storageFolder == null) { var msg = new MessageDialog("Please choose a folder first..."); await msg.ShowAsync(); button.IsChecked = false; return; } // check storage folder permissions try { var files = await storageFolder.GetFilesAsync(); } catch { var dialog = new MessageDialog( "The selected storage directory does not exist anymore or is not accessable. Please select a new directory.", "Directory not found or not enough permissions"); await dialog.ShowAsync(); button.IsChecked = false; return; } var requestSuspensionExtension = new ExtendedExecutionForegroundSession(); requestSuspensionExtension.Reason = ExtendedExecutionForegroundReason.Unspecified; var requestExtensionResult = await requestSuspensionExtension.RequestExtensionAsync(); // get storage files var time = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss_"); var screenFile = await storageFolder.CreateFileAsync(time + "slides.mp4"); var webcamFile = await storageFolder.CreateFileAsync(time + "talkinghead.mp4"); var jsonFile = await storageFolder.CreateFileAsync(time + "meta.json"); // get encoder properties var frameRate = uint.Parse(((string)FrameRateComboBox.SelectedItem).Replace("fps", "")); var quality = (VideoEncodingQuality)Enum.Parse(typeof(VideoEncodingQuality), (string)QualityComboBox.SelectedItem, false); var useSourceSize = UseCaptureItemSizeCheckBox.IsChecked.Value; var temp = MediaEncodingProfile.CreateMp4(quality); uint bitrate = 2500000; var width = temp.Video.Width; var height = temp.Video.Height; // get capture item var picker = new GraphicsCapturePicker(); captureItem = await picker.PickSingleItemAsync(); if (captureItem == null) { button.IsChecked = false; return; } // use the capture item's size for the encoding if desired if (useSourceSize) { width = (uint)captureItem.Size.Width; height = (uint)captureItem.Size.Height; } // we have a screen resolution of more than 4K? if (width > 1920) { var v = width / 1920; width = 1920; height /= v; } // even if we're using the capture item's real size, // we still want to make sure the numbers are even. width = EnsureEven(width); height = EnsureEven(height); // tell the user we've started recording var originalBrush = MainTextBlock.Foreground; MainTextBlock.Foreground = new SolidColorBrush(Colors.Red); MainProgressBar.IsIndeterminate = true; button.IsEnabled = false; MainTextBlock.Text = "3"; await Task.Delay(1000); MainTextBlock.Text = "2"; await Task.Delay(1000); MainTextBlock.Text = "1"; await Task.Delay(1000); button.IsEnabled = true; MainTextBlock.Text = "● rec"; _timerCount = 0; _timer.Start(); try { // start webcam recording MediaEncodingProfile webcamEncodingProfile = null; if (AdaptBitrateCheckBox.IsChecked.Value) { var selectedItem = WebcamComboBox.SelectedItem as ComboBoxItem; var encodingProperties = (selectedItem.Tag as StreamPropertiesHelper); if (encodingProperties.Height > 720) { webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p); webcamEncodingProfile.Video.Bitrate = 8000000; } else if (encodingProperties.Height > 480) { webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); webcamEncodingProfile.Video.Bitrate = 5000000; } else { webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); } } else { webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); } mediaRecording = await mediaCapture.PrepareLowLagRecordToStorageFileAsync(webcamEncodingProfile, webcamFile); // kick off the screen encoding parallel using (var stream = await screenFile.OpenAsync(FileAccessMode.ReadWrite)) using (screenCapture = new Encoder(screenDevice, captureItem)) { // webcam recording if (mediaCapture != null) { await mediaRecording.StartAsync(); } // screen recording await screenCapture.EncodeAsync( stream, width, height, bitrate, frameRate); } MainTextBlock.Foreground = originalBrush; // user has finished recording, so stop webcam recording await mediaRecording.StopAsync(); await mediaRecording.FinishAsync(); _timer.Stop(); } catch (Exception ex) { _timer.Stop(); var dialog = new MessageDialog( $"Uh-oh! Something went wrong!\n0x{ex.HResult:X8} - {ex.Message}", "Recording failed"); await dialog.ShowAsync(); button.IsChecked = false; MainTextBlock.Text = "failure"; MainTextBlock.Foreground = originalBrush; MainProgressBar.IsIndeterminate = false; captureItem = null; if (mediaRecording != null) { await mediaRecording.StopAsync(); await mediaRecording.FinishAsync(); } return; } // at this point the encoding has finished MainTextBlock.Text = "saving..."; // save slide markers var recording = new Recording() { Slides = screenCapture.GetTimestamps() }; var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(recording, Formatting.Indented, settings); await FileIO.WriteTextAsync(jsonFile, json); // add metadata var recordingMetadataDialog = new RecordingMetadataDialog(); var recordingMetadataDialogResult = await recordingMetadataDialog.ShowAsync(); if (recordingMetadataDialogResult == ContentDialogResult.Primary) { recording.Description = recordingMetadataDialog.LectureTitle; if (recordingMetadataDialog.LectureDate.HasValue) { recording.LectureDate = recordingMetadataDialog.LectureDate.Value.DateTime; } } else { recording.Description = null; recording.LectureDate = DateTime.Now; } json = JsonConvert.SerializeObject(recording, Formatting.Indented, settings); await FileIO.WriteTextAsync(jsonFile, json); // tell the user we're done button.IsChecked = false; MainTextBlock.Text = "done"; MainProgressBar.IsIndeterminate = false; requestSuspensionExtension.Dispose(); } private void CaptureManager_RecordLimitationExceeded(MediaCapture sender) { // stop the recording screenCapture?.Dispose(); MainTextBlock.Text = "Limit reached (3h)"; } private void ToggleButton_Unchecked(object sender, RoutedEventArgs e) { // If the encoder is doing stuff, tell it to stop screenCapture?.Dispose(); } private uint EnsureEven(uint number) { return (number % 2 == 0) ? number : number + 1; } #endregion private void MainPage_AppServiceConnected(object sender, EventArgs e) { App.Connection.RequestReceived += AppService_RequestReceived; } private async void AppService_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var msg = args.Request.Message; var result = msg["TYPE"].ToString(); if (result == "SlideChanged") { screenCapture?.AddCurrentTimestamp(); } else if (result == "Status") { if (msg["STATUS"].ToString() == "CONNECTED") { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PowerPointGreen.Visibility = Visibility.Visible; PowerPointRed.Visibility = Visibility.Collapsed; }); } else { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PowerPointGreen.Visibility = Visibility.Collapsed; PowerPointRed.Visibility = Visibility.Visible; }); } } } private async void Page_Loaded(object sender, RoutedEventArgs e) { // load external app and init webcam await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); await PopulateAudioAndVideoDevicesAsync(); await LoadSettings(); //await InitAudioMeterAsync(); } private async void BtnFolderPicker_Click(object sender, RoutedEventArgs e) { var folderPicker = new FolderPicker(); folderPicker.ViewMode = PickerViewMode.List; folderPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary; folderPicker.FileTypeFilter.Add("*"); storageFolder = await folderPicker.PickSingleFolderAsync(); if (storageFolder != null) { FolderName.Text = storageFolder.Path; } } } }
using Umbraco.Core; using Umbraco.Web.Runtime; namespace Umbraco.Web { /// <summary> /// Represents the Umbraco global.asax class. /// </summary> public class UmbracoApplication : UmbracoApplicationBase { protected override IRuntime GetRuntime() { return new WebRuntime(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.DataAccess.Data { public interface IAbstractFactory { IFile Create(FileTypes fileFormat); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Threading; namespace Robotersteuerung.ScriptExecutorCommands { abstract class ScriptExecutorCommand { protected string cmd; protected string[] args; Dispatcher dispatcher = ScriptWindow.instance.Dispatcher; public abstract void run(); } }
using System.ComponentModel.Composition; using System.Linq; using Torshify.Radio.Core.Services; using Torshify.Radio.Framework; using Torshify.Radio.Framework.Commands; namespace Torshify.Radio.Core.Views.Settings.General { [Export("GeneralSettingsSection", typeof(ISettingsSection))] [PartCreationPolicy(CreationPolicy.NonShared)] public class HotkeySection : ISettingsSection { #region Fields [Import] private IHotkeyService _hotkeyService = null; #endregion Fields #region Constructors public HotkeySection() { HeaderInfo = new HeaderInfo { Title = "Global hotkeys" }; UI = new HotkeySectionView { DataContext = this }; AddHotkeyCommand = new StaticCommand(ExecuteAddHotkey); RemoveHotkeyCommand = new AutomaticCommand<GlobalHotkey>(ExecuteRemoveHotkey, CanExecuteRemoveHotkey); RestoreDefaultHotkeysCommand = new StaticCommand(ExecuteRestoreDefaultHotkeys); } #endregion Constructors #region Properties public HeaderInfo HeaderInfo { get; private set; } public object UI { get; private set; } public IHotkeyService HotkeyService { get { return _hotkeyService; } } public StaticCommand RestoreDefaultHotkeysCommand { get; private set; } public StaticCommand AddHotkeyCommand { get; private set; } public AutomaticCommand<GlobalHotkey> RemoveHotkeyCommand { get; private set; } #endregion Properties #region Methods public void Load() { } public void Save() { _hotkeyService.Save(); } private void ExecuteRestoreDefaultHotkeys() { _hotkeyService.RestoreDefaults(); } private bool CanExecuteRemoveHotkey(GlobalHotkey hotkey) { return hotkey != null && _hotkeyService.ConfiguredHotkeys.Contains(hotkey); } private void ExecuteRemoveHotkey(GlobalHotkey hotkey) { _hotkeyService.Remove(hotkey.Id); } private void ExecuteAddHotkey() { _hotkeyService.Add(new GlobalHotkey()); } #endregion Methods } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using HackerNews.Api; using Microsoft.AspNetCore.Mvc; using HackerNews.Web.Models; namespace HackerNews.Web.Controllers { public class HomeController : Controller { public IActionResult Index() { var api = new HackerNewsApi(); return View(api.GetTopStories()); } } }
using UnityEngine; using System.Collections; using System.IO; using System; public class Game : MonoBehaviour { // Обьекты для организации дочерних в иерархии public GameObject Foods; public GameObject WallsObjects; // Основной массив для хранения обьектов стен static public GameObject[,] Walls; // Загрузка обьектов стены,призраков,еды,игрока и т.д public GameObject Player; public GameObject GhostObj; public GameObject FoodObj; static public GameObject[] Ghosts ; public GameObject Ugol; public GameObject Stena; public GameObject Per4; public GameObject Per3; public GameObject tup; public GameObject Cube; // Координаты точек спавна static public string[] Spawns; static public float BoostCount = 0.0f ; static public bool Boost = false; int Count = 0 ; float deltaTime = 0 ; void Start () { Application.targetFrameRate = 30; deltaTime = Time.time; Count = 0; // Грузим из prefs все нужные данные : тип обьекта,угол поворота и координаты спавнов String Filename = Menu.NamesArr [Menu.selGridInt]; string LevelArray = PlayerPrefs.GetString (Filename); string[] LevelAngles = PlayerPrefs.GetString ("angles" + Filename).Split (','); // массив для хранения углов поворота обьектов стены Spawns = PlayerPrefs.GetString ("spawns" + Filename).Split (','); // координаты спавнов Walls = new GameObject[Menu.CubeNumX, Menu.CubeNumY]; // массив для хранения стен на сцене var ArrayCount = 0; // Добавляем обьекты на сцену в зависимости от типа обьекта for (var i = 0; i< Menu.CubeNumX; i ++) { for (var j = 0; j < Menu.CubeNumY; j++) { AddToStage (i, j, (int)Char.GetNumericValue (LevelArray [ArrayCount]), Convert.ToSingle (LevelAngles [ArrayCount])); ArrayCount++; } } PlayerClass.NumAtX = Convert.ToInt32 (Spawns [0]) ; PlayerClass.NumAtY = Convert.ToInt32 (Spawns [1]); Player.transform.position = new Vector3 (PlayerClass.NumAtX * Menu.CubeSize,PlayerClass.NumAtY * Menu.CubeSize, Menu.CubeSize / 4); Ghosts = new GameObject[Menu.GhostCols]; } void Update () { if ( Time.time- deltaTime > 0.7f && Count< Menu.GhostCols ) { deltaTime = Time.time; newGhost(); Count++; } // Расчет режима "страха" для призраков if( Boost == true && Time.time-BoostCount >= 6.0f ) { Game.Ghosts = GameObject.FindGameObjectsWithTag("Ghost"); foreach( GameObject GhostObj in Game.Ghosts) { if( GhostObj .GetComponent<Ghost>().State == 2 ) { GhostObj .GetComponent<Ghost>().State = 0; } } Boost = false; BoostCount = 0.0f; } } void newGhost() { GameObject newGhostObj = GhostObj as GameObject; newGhostObj.GetComponent<Ghost>().NumAtX = Convert.ToInt32 (Spawns [2]) ; newGhostObj.GetComponent<Ghost>().NumAtY = Convert.ToInt32 (Spawns [3]); newGhostObj.transform.position = new Vector3 ( Convert.ToInt32 (Spawns [2]) * Menu.CubeSize,Convert.ToInt32 (Spawns [3]) * Menu.CubeSize, Menu.CubeSize / 4); newGhostObj.name = "Ghost"; Instantiate(newGhostObj) ; } public void AddToStage (int TargetI, int TargetJ, int CubeType, float ug) { switch (CubeType) { case 0: //AttachToArr (TargetI, TargetJ, 0, Cube, ug); break; case 1: AttachToArr (TargetI, TargetJ, 1, Ugol, ug); break; case 2: AttachToArr (TargetI, TargetJ, 2, Stena, ug); break; case 3: AttachToArr (TargetI, TargetJ, 3, Per3, ug); break; case 4: AttachToArr (TargetI, TargetJ, 4, Per4, ug); break; case 5: AttachToArr (TargetI, TargetJ, 5, tup, ug); break; } } public void AttachToArr (int k, int m, int typen, GameObject obj, float ug) { FoodObj.GetComponent<Food>().boost = false; if( k % 3 == 0 && m % 3 == 0) { FoodObj.GetComponent<Food>().boost = true; } FoodObj.transform.position = new Vector3 (+ k * Menu.CubeSize, m * Menu.CubeSize, Menu.CubeSize / 4); FoodObj.transform.localScale = new Vector3 (Menu.CubeSize /6, Menu.CubeSize/6, Menu.CubeSize/6); GameObject ChildObject = Instantiate(FoodObj) as GameObject ; ChildObject.name = "Food"; ChildObject.transform.parent = Foods.transform; obj.GetComponent<Wall> ().i = k; obj.GetComponent<Wall> ().j = m; obj.GetComponent<Wall> ().Type_number = typen; obj.transform.rotation = Quaternion.Euler (0, 0, transform.rotation.eulerAngles.z + ug); Walls [k, m] = Instantiate (obj) as GameObject; Walls[k,m].name = "WallObject"; Walls[k,m].transform.parent = WallsObjects.transform; } void OnGUI () { int buttonWidth = 100; GUIStyle style = GUI.skin.GetStyle ("Button"); style.fontSize = 12; if (GUI.Button (new Rect (Screen.width / 2 + 10 + buttonWidth / 2, Screen.height - Menu.CubeSize - 10, buttonWidth, Menu.CubeSize + 5), "Exit")) { Application.LoadLevel ("Menu"); } if (GUI.Button (new Rect (Screen.width / 2 + 10 + buttonWidth / 2, Screen.height - Menu.CubeSize *2 - 20, buttonWidth, Menu.CubeSize + 5), "find")) { } } }
using Unity.Entities; using UnityEngine; //Makes it so Component Data can be put onto GameObjects before Entitiy Conversion. [GenerateAuthoringComponent] public struct PaddleInputData :IComponentData { public KeyCode upKey; public KeyCode downKey; }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Common; namespace Vigenère { class Program { private static readonly string message = "meet me after the toga party"; private static readonly string key = "ZPBYJRSKFLXQNWVDHMGUTOIAEC"; private static string Encrypt(string message, string key) { string cipher = string.Empty; for (int i = 0; i < message.Length; i++) { char p = char.ToUpper(message[i]); int alphabetIndex = Defines.ALPHABET.IndexOf(p); if (alphabetIndex >= 0) { cipher += key[alphabetIndex]; } else { cipher += p; } } return cipher; } private static string Decrypt(string cipher, string key) { string msg = string.Empty; for (int i = 0; i < cipher.Length; i++) { char p = char.ToUpper(cipher[i]); int cipherIndex = key.IndexOf(p); if (cipherIndex >= 0) { msg += Defines.ALPHABET[cipherIndex]; } else { msg += p; } } return msg; } static void Main(string[] args) { string cipher = Encrypt(message, key); string msg = Decrypt(cipher, key); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerInput : MonoBehaviour { [SerializeField] // Player Instance private Player playerInstance; void FixedUpdate(){ WatchMove(); } void Update() { if(Input.GetButtonDown("Fire1")) InputBasicAttack(); // 일반 공격 if(Input.GetButton("Fire2")) InputSpecialAttack(); // 특수 공격 if(Input.GetButtonDown("Dodge")) InputDodge(); // 회피 } void WatchMove() { Vector3 direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")); playerInstance.PlayerMove(direction.normalized); } void InputBasicAttack() { RaycastHit hit; if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, 1 << 8)) { switch(playerInstance.playerState) { case PlayerState.Dodge : case PlayerState.SecondDodge : playerInstance.DodgeAttack(hit.point); break; case PlayerState.Idle : case PlayerState.Move : case PlayerState.BasicAttack : playerInstance.BasicAttack(hit.point); break; } } } void InputSpecialAttack() { RaycastHit hit; if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, 1 << 8)) { playerInstance.SpecialAttack(hit.point); } } void InputDodge() { playerInstance.Dodge(); } }
using Dapper; using Dominio; using Oracle.ManagedDataAccess.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class DbContador : IDisposable { public IEnumerable<Contador> Listar() { using (OracleConnection cnn = new OracleConnection(Properties.Settings.Default.ConnectionString)) { return cnn.Query<Contador>("Select * from CAD_CONTADOR"); } } public Contador Selecionar(decimal SQ_CONTADOR) { using (OracleConnection cnn = new OracleConnection(Properties.Settings.Default.ConnectionString)) { return cnn.QueryFirstOrDefault<Contador>("Select * from CAD_CONTADOR Where SQ_CONTADOR=:SQ_CONTADOR ", new { SQ_CONTADOR = SQ_CONTADOR }); } } public IEnumerable<Contribuinte> RetornaContribuintePorContador(decimal SQ_CONTADOR) { using (OracleConnection cnn = new OracleConnection(Properties.Settings.Default.ConnectionString)) { return cnn.Query<Contribuinte>(@"SELECT CM.* FROM ADM_OBJETOS.CAD_CONTRIBUINTE_MUNICIPAL CM INNER JOIN ADM_OBJETOS.CAD_CONTADOR_CONTRIBUINTE CC ON CC.SQ_CONTRIBUINTE = CM.SQ_CONTRIBUINTE WHERE CC.SQ_CONTADOR = :SQ_CONTADOR", new { SQ_CONTADOR = SQ_CONTADOR }); } } public void Incluir(Contador contador) { using (OracleConnection dbConnection = new OracleConnection(Properties.Settings.Default.ConnectionString)) { dbConnection.Open(); using (var trn = dbConnection.BeginTransaction()) { try { dbConnection.Execute(@"INSERT INTO CAD_CONTADOR (NU_CRC, NM_CONTADOR, NM_LOGRADOURO, NU_LOGRADOURO, NM_COMPLEMENTO, NU_CEP, NM_BAIRRO, NU_TELEFONE, NM_EMAIL_COMERCIAL) VALUES (:NU_CRC, :NM_CONTADOR, :NM_LOGRADOURO, :NU_LOGRADOURO, :NM_COMPLEMENTO, :NU_CEP, :NM_BAIRRO, :NU_TELEFONE, :NM_EMAIL_COMERCIAL)", contador, trn); trn.Commit(); } catch { trn.Rollback(); throw; } } } } public void Atualizar(Contador contador) { using (OracleConnection dbConnection = new OracleConnection(Properties.Settings.Default.ConnectionString)) { dbConnection.Open(); using (var trn = dbConnection.BeginTransaction()) { try { dbConnection.Execute(@" UPDATE CAD_CONTADOR SET NU_CRC = :NU_CRC, NM_CONTADOR = :NM_CONTADOR NM_LOGRADOURO = :NM_LOGRADOURO, NU_LOGRADOURO = :NU_LOGRADOURO, NM_COMPLEMENTO = :NM_COMPLEMENTO, NU_CEP = :NU_CEP, NM_BAIRRO = :NM_BAIRRO, NU_TELEFONE = :NU_TELEFONE, NM_EMAIL_COMERCIAL : NM_EMAIL_COMERCIAL WHERE SQ_CONTADOR = :SQ_CONTADOR", contador, trn); trn.Commit(); } catch { trn.Rollback(); throw; } } } } public void Excluir(decimal SQ_CONTADOR) { using (OracleConnection dbConnection = new OracleConnection(Properties.Settings.Default.ConnectionString)) { dbConnection.Open(); using (var trn = dbConnection.BeginTransaction()) { try { dbConnection.Execute(@"DELETE FROM CAD_CONTADOR_CONTRIBUINTE WHERE SQ_CONTADOR = :SQ_CONTADOR", new { SQ_CONTADOR = SQ_CONTADOR }, trn); dbConnection.Execute(@"DELETE FROM CAD_CONTADOR WHERE SQ_CONTADOR = :SQ_CONTADOR", new { SQ_CONTADOR = SQ_CONTADOR }, trn); trn.Commit(); } catch (Exception e) { trn.Rollback(); throw e; } } } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { GC.Collect(); } disposedValue = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Karkas.Ornek.TypeLibrary.Ornekler; using Karkas.Ornek.Dal.Ornekler; using NUnit.Framework; namespace Karkas.Ornek.ConsoleApp.Testler { [TestFixture] public class DenemeGuidIdentityTest { [Test] public void Ekle() { DenemeGuidIdentity dgi = new DenemeGuidIdentity(); dgi.DenemeKey = Guid.NewGuid(); dgi.DenemeKolon = "addd"; DenemeGuidIdentityDal dal = new DenemeGuidIdentityDal(); long sonuc = dal.Ekle(dgi); } [Test] public void Guncelle() { DenemeGuidIdentity dgi = new DenemeGuidIdentity(); DenemeGuidIdentityDal dal = new DenemeGuidIdentityDal(); List<DenemeGuidIdentity> list = dal.SorgulaHepsiniGetir(); dgi.DenemeKey = list.ElementAt(0).DenemeKey; dgi.DenemeNo = 11; dgi.DenemeKolon = "addd"; dal.Guncelle(dgi); } } }
using FeelingGoodApp.Data; namespace FeelingGoodApp.Models { public class UserProfileViewModel { public int Id { get; set; } public string query { get; set; } public string gender { get; set; } public float weight_kg { get; set; } public float height_cm { get; set; } public int age { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace linq { // Build a collection of customers1 who are millionaires // public class Customer // { // public string Name { get; set; } // public double Balance { get; set; } // public string Bank { get; set; } // } // public class MillionaireBankReport // { // public string bankName { get; set; } // public int num { get; set; } // } /* TASK: As in the previous exercise, you're going to output the millionaires, but you will also display the full name of the bank. You also need to sort the millionaires' names, ascending by their LAST name. Example output: Tina Fey at Citibank Joe Landy at Wells Fargo Sarah Ng at First Tennessee Les Paul at Wells Fargo Peg Vale at Bank of America */ // Define a bank public class Bank { public string Symbol { get; set; } public string Name { get; set; } } // Define a customer public class Customer { public string Name { get; set; } public double Balance { get; set; } public string Bank { get; set; } } public class ReportItem { public string CustomerName { get; set; } public string BankName { get; set; } public string GetLastName() { return CustomerName.Split(" ")[1]; } } class Program { static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List<string> fruits = new List<string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable<string> LFruits = from fruit in fruits where fruit.StartsWith("L") orderby fruit ascending select fruit; foreach (string fruit in LFruits) { Console.WriteLine(fruit); } // Which of the following numbers are multiples of 4 or 6 List<int> numbers = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable<int> fourSixMultiples = numbers.Where(num => num % 4 == 0 || num % 6 == 0); foreach (int num in fourSixMultiples) { Console.WriteLine(num); } // Order these student names alphabetically, in descending order (Z to A) List<string> names = new List<string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; List<string> descend = names.OrderByDescending(name => name.First()).ToList(); foreach (string name in descend) { Console.WriteLine(name); } // Build a collection of these numbers sorted in ascending order List<int> numbers1 = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; List<int> sortedNums = numbers1.OrderBy(a => a).ToList(); foreach (int num in sortedNums) { Console.WriteLine(num); } // Output how many numbers are in this list List<int> numbersA = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine($"NumbersA list contains {numbersA.Count} numbers"); // How much money have we made? List<double> purchases = new List<double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; Console.WriteLine($"We have made {purchases.Sum()}"); // What is our most expensive product? List<double> prices = new List<double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; Console.WriteLine($"Our most expensive product costs ${prices.Max()}"); // List<Customer> customers1 = new List<Customer>() { // new Customer(){ Name="Bob Lesman", Balance=80345.66, Bank="FTB"}, // new Customer(){ Name="Joe Landy", Balance=9284756.21, Bank="WF"}, // new Customer(){ Name="Meg Ford", Balance=487233.01, Bank="BOA"}, // new Customer(){ Name="Peg Vale", Balance=7001449.92, Bank="BOA"}, // new Customer(){ Name="Mike Johnson", Balance=790872.12, Bank="WF"}, // new Customer(){ Name="Les Paul", Balance=8374892.54, Bank="WF"}, // new Customer(){ Name="Sid Crosby", Balance=957436.39, Bank="FTB"}, // new Customer(){ Name="Sarah Ng", Balance=56562389.85, Bank="FTB"}, // new Customer(){ Name="Tina Fey", Balance=1000000.00, Bank="CITI"}, // new Customer(){ Name="Sid Brown", Balance=49582.68, Bank="CITI"} // }; // List<Customer> millionaires = customers1.FindAll(a => a.Balance >= 1000000); // foreach(Customer millionaire in millionaires) { // Console.WriteLine(millionaire.Name); // } // /* // Given the same customer set, display how many millionaires per bank. // Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq // Example Output: // WF 2 // BOA 1 // FTB 1 // CITI 1 // */ // IEnumerable<MillionaireBankReport> bankReport = (from millionaire in millionaires // group millionaire by millionaire.Bank into bankGroup // select new MillionaireBankReport { // bankName = bankGroup.Key, // num = bankGroup.Count() // }); // foreach(MillionaireBankReport MBP in bankReport) // { // Console.WriteLine($"{MBP.bankName}: {MBP.num}"); // } // Create some banks and store in a List List<Bank> banks = new List<Bank>() { new Bank(){ Name="First Tennessee", Symbol="FTB"}, new Bank(){ Name="Wells Fargo", Symbol="WF"}, new Bank(){ Name="Bank of America", Symbol="BOA"}, new Bank(){ Name="Citibank", Symbol="CITI"}, }; // Create some customers and store in a List List<Customer> customers = new List<Customer>() { new Customer(){ Name="Bob Lesman", Balance=80345.66, Bank="FTB"}, new Customer(){ Name="Joe Landy", Balance=9284756.21, Bank="WF"}, new Customer(){ Name="Meg Ford", Balance=487233.01, Bank="BOA"}, new Customer(){ Name="Peg Vale", Balance=7001449.92, Bank="BOA"}, new Customer(){ Name="Mike Johnson", Balance=790872.12, Bank="WF"}, new Customer(){ Name="Les Paul", Balance=8374892.54, Bank="WF"}, new Customer(){ Name="Sid Crosby", Balance=957436.39, Bank="FTB"}, new Customer(){ Name="Sarah Ng", Balance=56562389.85, Bank="FTB"}, new Customer(){ Name="Tina Fey", Balance=1000000.00, Bank="CITI"}, new Customer(){ Name="Sid Brown", Balance=49582.68, Bank="CITI"} }; // You will need to use the `Where()` // and `Select()` methods to generate // instances of the following class. List<ReportItem> millionaireReport = ( from milli in customers.Where(customer => customer.Balance >= 1000000).ToList() join bank in banks on milli.Bank equals bank.Symbol select new ReportItem { CustomerName = milli.Name, BankName = bank.Name }).ToList(); foreach (var item in millionaireReport.OrderBy(cust => cust.GetLastName() )) { Console.WriteLine($"{item.CustomerName} at {item.BankName}"); } } } }
using System; using System.Collections.Generic; using System.Text; namespace ClassMetotDemo { class CustomerManager { public void Ekle(Customer musteriEkle) { Console.WriteLine("Müşteriniz Sisteme Eklenmiştir. : " + musteriEkle.Name + " " + musteriEkle.Surname); } public void Liste(Customer musteriListe) { Console.WriteLine("Müşterileriniz Listelenmiştir. -> " + musteriListe.Name + " " + musteriListe.Surname + "-" + musteriListe.Age ); } public void Silme(Customer musteriSilme) { Console.WriteLine("Müşteriniz Sistemden Silinmiştir. : " + musteriSilme.Name + " " + musteriSilme.Surname); } } }
// Accord Imaging Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Imaging { using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Security; /// <summary> /// Joint representation of both Integral Image and Squared Integral Image. /// </summary> /// /// <remarks> /// Using this representation, both structures can be created in a single pass /// over the data. This is interesting for real time applications. This class /// also accepts a channel parameter indicating the Integral Image should be /// computed using a specified color channel. This avoids costly conversions. /// </remarks> /// [SecurityCritical] public unsafe class IntegralImage2 : IDisposable { private long[,] nSumImage; // normal integral image private long[,] sSumImage; // squared integral image private long[,] tSumImage; // tilted integral image private long* nSum; // normal integral image private long* sSum; // squared integral image private long* tSum; // tilted integral image private GCHandle nSumHandle; private GCHandle sSumHandle; private GCHandle tSumHandle; private int width; private int height; private int nWidth; private int nHeight; private int tWidth; private int tHeight; /// <summary> /// Gets the image's width. /// </summary> /// public int Width { get { return width; } } /// <summary> /// Gets the image's height. /// </summary> /// public int Height { get { return height; } } /// <summary> /// Gets the Integral Image for values' sum. /// </summary> /// public long[,] Image { get { return nSumImage; } } /// <summary> /// Gets the Integral Image for values' squared sum. /// </summary> /// public long[,] Squared { get { return sSumImage; } } /// <summary> /// Gets the Integral Image for tilted values' sum. /// </summary> /// public long[,] Rotated { get { return tSumImage; } } /// <summary> /// Constructs a new Integral image of the given size. /// </summary> /// protected IntegralImage2(int width, int height, bool computeTilted) { this.width = width; this.height = height; this.nWidth = width + 1; this.nHeight = height + 1; this.tWidth = width + 2; this.tHeight = height + 2; this.nSumImage = new long[nHeight, nWidth]; this.nSumHandle = GCHandle.Alloc(nSumImage, GCHandleType.Pinned); this.nSum = (long*)nSumHandle.AddrOfPinnedObject().ToPointer(); this.sSumImage = new long[nHeight, nWidth]; this.sSumHandle = GCHandle.Alloc(sSumImage, GCHandleType.Pinned); this.sSum = (long*)sSumHandle.AddrOfPinnedObject().ToPointer(); if (computeTilted) { this.tSumImage = new long[tHeight, tWidth]; this.tSumHandle = GCHandle.Alloc(tSumImage, GCHandleType.Pinned); this.tSum = (long*)tSumHandle.AddrOfPinnedObject().ToPointer(); } } /// <summary> /// Constructs a new Integral image from a Bitmap image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(Bitmap image) { return FromBitmap(image, 0, false); } /// <summary> /// Constructs a new Integral image from a Bitmap image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// <param name="channel">The image channel to consider in the computations. Default is 0.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(Bitmap image, int channel) { return FromBitmap(image, channel, false); } /// <summary> /// Constructs a new Integral image from a Bitmap image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// <param name="computeTilted"><c>True</c> to compute the tilted version of the integral image, /// <c>false</c> otherwise. Default is false.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(Bitmap image, bool computeTilted) { return FromBitmap(image, 0, computeTilted); } /// <summary> /// Constructs a new Integral image from a Bitmap image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// <param name="channel">The image channel to consider in the computations. Default is 0.</param> /// <param name="computeTilted"><c>True</c> to compute the tilted version of the integral image, /// <c>false</c> otherwise. Default is false.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(Bitmap image, int channel, bool computeTilted) { // check image format if (!(image.PixelFormat == PixelFormat.Format8bppIndexed || image.PixelFormat == PixelFormat.Format24bppRgb || image.PixelFormat == PixelFormat.Format32bppArgb || image.PixelFormat == PixelFormat.Format32bppRgb)) { throw new UnsupportedImageFormatException("Only grayscale, 24 and 32 bpp RGB images are supported."); } // lock source image BitmapData imageData = image.LockBits( new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat); // process the image IntegralImage2 im = FromBitmap(imageData, channel, computeTilted); // unlock image image.UnlockBits(imageData); return im; } /// <summary> /// Constructs a new Integral image from a BitmapData image. /// </summary> /// /// <param name="imageData">The source image from where the integral image should be computed.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="imageData">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(BitmapData imageData) { return FromBitmap(imageData, 0); } /// <summary> /// Constructs a new Integral image from a BitmapData image. /// </summary> /// /// <param name="imageData">The source image from where the integral image should be computed.</param> /// <param name="channel">The image channel to consider in the computations. Default is 0.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="imageData">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(BitmapData imageData, int channel) { return FromBitmap(new UnmanagedImage(imageData), channel); } /// <summary> /// Constructs a new Integral image from a BitmapData image. /// </summary> /// /// <param name="imageData">The source image from where the integral image should be computed.</param> /// <param name="channel">The image channel to consider in the computations. Default is 0.</param> /// <param name="computeTilted"><c>True</c> to compute the tilted version of the integral image, /// <c>false</c> otherwise. Default is false.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="imageData">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(BitmapData imageData, int channel, bool computeTilted) { return FromBitmap(new UnmanagedImage(imageData), channel, computeTilted); } /// <summary> /// Constructs a new Integral image from a BitmapData image. /// </summary> /// /// <param name="imageData">The source image from where the integral image should be computed.</param> /// <param name="computeTilted"><c>True</c> to compute the tilted version of the integral image, /// <c>false</c> otherwise. Default is false.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="imageData">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(BitmapData imageData, bool computeTilted) { return FromBitmap(new UnmanagedImage(imageData), 0, computeTilted); } /// <summary> /// Constructs a new Integral image from an unmanaged image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// <param name="channel">The image channel to consider in the computations. Default is 0.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(UnmanagedImage image, int channel) { return FromBitmap(image, channel, false); } /// <summary> /// Constructs a new Integral image from an unmanaged image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(UnmanagedImage image) { return FromBitmap(image, 0, false); } /// <summary> /// Constructs a new Integral image from an unmanaged image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// <param name="computeTilted"><c>True</c> to compute the tilted version of the integral image, /// <c>false</c> otherwise. Default is false.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(UnmanagedImage image, bool computeTilted) { return FromBitmap(image, 0, computeTilted); } /// <summary> /// Constructs a new Integral image from an unmanaged image. /// </summary> /// /// <param name="image">The source image from where the integral image should be computed.</param> /// <param name="channel">The image channel to consider in the computations. Default is 0.</param> /// <param name="computeTilted"><c>True</c> to compute the tilted version of the integral image, /// <c>false</c> otherwise. Default is false.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="image">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(UnmanagedImage image, int channel, bool computeTilted) { // check image format if (!(image.PixelFormat == PixelFormat.Format8bppIndexed || image.PixelFormat == PixelFormat.Format24bppRgb || image.PixelFormat == PixelFormat.Format32bppArgb || image.PixelFormat == PixelFormat.Format32bppRgb)) { throw new UnsupportedImageFormatException("Only grayscale, 24 and 32 bpp RGB images are supported."); } int pixelSize = System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8; // get source image size int width = image.Width; int height = image.Height; int stride = image.Stride; int offset = stride - width * pixelSize; // create integral image IntegralImage2 im = new IntegralImage2(width, height, computeTilted); long* nSum = im.nSum; long* sSum = im.sSum; long* tSum = im.tSum; int nWidth = im.nWidth; int tWidth = im.tWidth; if (image.PixelFormat == PixelFormat.Format8bppIndexed && channel != 0) throw new ArgumentException("Only the first channel is available for 8 bpp images.", "channel"); byte* srcStart = (byte*)image.ImageData.ToPointer() + channel; // do the job byte* src = srcStart; // for each line for (int y = 1; y <= height; y++) { int yy = nWidth * (y); int y1 = nWidth * (y - 1); // for each pixel for (int x = 1; x <= width; x++, src += pixelSize) { long p1 = *src; long p2 = p1 * p1; int r = yy + (x); int a = yy + (x - 1); int b = y1 + (x); int c = y1 + (x - 1); nSum[r] = p1 + nSum[a] + nSum[b] - nSum[c]; sSum[r] = p2 + sSum[a] + sSum[b] - sSum[c]; } src += offset; } if (computeTilted) { src = srcStart; // Left-to-right, top-to-bottom pass for (int y = 1; y <= height; y++, src += offset) { int yy = tWidth * (y); int y1 = tWidth * (y - 1); for (int x = 2; x < width + 2; x++, src += pixelSize) { int a = y1 + (x - 1); int b = yy + (x - 1); int c = y1 + (x - 2); int r = yy + (x); tSum[r] = *src + tSum[a] + tSum[b] - tSum[c]; } } { int yy = tWidth * (height); int y1 = tWidth * (height + 1); for (int x = 2; x < width + 2; x++, src += pixelSize) { int a = yy + (x - 1); int c = yy + (x - 2); int b = y1 + (x - 1); int r = y1 + (x); tSum[r] = tSum[a] + tSum[b] - tSum[c]; } } // Right-to-left, bottom-to-top pass for (int y = height; y >= 0; y--) { int yy = tWidth * (y); int y1 = tWidth * (y + 1); for (int x = width + 1; x >= 1; x--) { int r = yy + (x); int b = y1 + (x - 1); tSum[r] += tSum[b]; } } for (int y = height + 1; y >= 0; y--) { int yy = tWidth * (y); for (int x = width + 1; x >= 2; x--) { int r = yy + (x); int b = yy + (x - 2); tSum[r] -= tSum[b]; } } } return im; } /// <summary> /// Gets the sum of the pixels in a rectangle of the Integral image. /// </summary> /// /// <param name="x">The horizontal position of the rectangle <c>x</c>.</param> /// <param name="y">The vertical position of the rectangle <c>y</c>.</param> /// <param name="height">The rectangle's height <c>h</c>.</param> /// <param name="width">The rectangle's width <c>w</c>.</param> /// /// <returns>The sum of all pixels contained in the rectangle, computed /// as I[y, x] + I[y + h, x + w] - I[y + h, x] - I[y, x + w].</returns> /// public long GetSum(int x, int y, int width, int height) { int a = nWidth * (y) + (x); int b = nWidth * (y + height) + (x + width); int c = nWidth * (y + height) + (x); int d = nWidth * (y) + (x + width); return nSum[a] + nSum[b] - nSum[c] - nSum[d]; } /// <summary> /// Gets the sum of the squared pixels in a rectangle of the Integral image. /// </summary> /// /// <param name="x">The horizontal position of the rectangle <c>x</c>.</param> /// <param name="y">The vertical position of the rectangle <c>y</c>.</param> /// <param name="height">The rectangle's height <c>h</c>.</param> /// <param name="width">The rectangle's width <c>w</c>.</param> /// /// <returns>The sum of all pixels contained in the rectangle, computed /// as I²[y, x] + I²[y + h, x + w] - I²[y + h, x] - I²[y, x + w].</returns> /// public long GetSum2(int x, int y, int width, int height) { int a = nWidth * (y) + (x); int b = nWidth * (y + height) + (x + width); int c = nWidth * (y + height) + (x); int d = nWidth * (y) + (x + width); return sSum[a] + sSum[b] - sSum[c] - sSum[d]; } /// <summary> /// Gets the sum of the pixels in a tilted rectangle of the Integral image. /// </summary> /// /// <param name="x">The horizontal position of the rectangle <c>x</c>.</param> /// <param name="y">The vertical position of the rectangle <c>y</c>.</param> /// <param name="height">The rectangle's height <c>h</c>.</param> /// <param name="width">The rectangle's width <c>w</c>.</param> /// /// <returns>The sum of all pixels contained in the rectangle, computed /// as T[y + w, x + w + 1] + T[y + h, x - h + 1] - T[y, x + 1] - T[y + w + h, x + w - h + 1].</returns> /// public long GetSumT(int x, int y, int width, int height) { int a = tWidth * (y + width) + (x + width + 1); int b = tWidth * (y + height) + (x - height + 1); int c = tWidth * (y) + (x + 1); int d = tWidth * (y + width + height) + (x + width - height + 1); return tSum[a] + tSum[b] - tSum[c] - tSum[d]; } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// </summary> /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged resources and performs other cleanup operations /// before the <see cref="IntegralImage2"/> is reclaimed by garbage collection. /// </summary> /// ~IntegralImage2() { Dispose(false); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// /// <param name="disposing"><c>true</c> to release both managed /// and unmanaged resources; <c>false</c> to release only unmanaged /// resources.</param> /// protected virtual void Dispose(bool disposing) { if (disposing) { // free managed resources // (i.e. IDisposable objects) } // free native resources if (nSumHandle.IsAllocated) { nSumHandle.Free(); nSum = null; } if (sSumHandle.IsAllocated) { sSumHandle.Free(); sSum = null; } if (tSumHandle.IsAllocated) { tSumHandle.Free(); tSum = null; } } #endregion } }
using UnityEngine; using System.Collections; using UnityEditor; public class EditModifier : Editor { [MenuItem("GameObject/Tag/修改为Model标签")] static void TagModifierToModel() { ModifierTag("Model"); } [MenuItem("GameObject/Tag/修改为Floor标签")] static void TagModifierToFloor() { ModifierTag("Floor"); } [MenuItem("GameObject/Prefab/增加地面")] static void AddFloorPrefab() { GameObject floor = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/prefab/Cube.prefab"); foreach (GameObject item in Selection.gameObjects) { GameObject newFloor = PrefabUtility.InstantiatePrefab(floor)as GameObject; newFloor.transform.parent = item.transform; newFloor.transform.localPosition = Vector3.zero; newFloor.transform.localScale = new Vector3(80,0.005f,80); } } private static void ModifierTag(string newTag) { foreach(GameObject selectedGameObject in Selection.gameObjects) { selectedGameObject.tag = newTag; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using JoveZhao.Framework; namespace BPiaoBao.Common { public class HttpWebRequestHelper { /// <summary> /// Get方法 /// </summary> /// <param name="strUrl"></param> /// <returns></returns> public static string Get(string strUrl) { try { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(strUrl); HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.GetEncoding("GBK")); string content = reader.ReadToEnd(); reader.Close(); responseSorce.Close(); return content; } catch (Exception e) { throw new CustomException(100001, e.Message); } } /// <summary> /// Post方法 /// </summary> /// <param name="strUrl"></param> /// <param name="postData"></param> /// <returns></returns> public static string Post(string strUrl, string postData) { try { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(strUrl); byte[] data = Encoding.GetEncoding("GBK").GetBytes(postData); requestScore.Method = "Post"; requestScore.ContentType = "application/x-www-form-urlencoded"; requestScore.ContentLength = data.Length; requestScore.KeepAlive = true; //使用cookies //requestScore.CookieContainer = ...; Stream stream = requestScore.GetRequestStream(); stream.Write(data, 0, data.Length); HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.GetEncoding("GBK")); string content = reader.ReadToEnd(); stream.Close(); reader.Close(); responseSorce.Close(); return content; } catch (Exception e) { //throw new CustomException(100001, e.Message); Logger.WriteLog(LogType.ERROR, "Request Exception(url--->"+strUrl+" data--->"+postData+") "+ e.Message); return ""; } } /// <summary> /// HTML标签过滤 /// </summary> /// <param name="html"></param> /// <param name="lable"></param> /// <returns></returns> public static string CheckStr(string html, string[] lable) { return lable.Select(lb => String.Format(@"</?{0}[^>]*?>", lb)).Aggregate(html, (current, reg) => System.Text.RegularExpressions.Regex.Replace(current, reg, "", System.Text.RegularExpressions.RegexOptions.IgnoreCase)); } } }
using System.ComponentModel; using System.ComponentModel.Composition; using System.Linq; using System.Windows; using Raven.Client; using Torshify.Radio.Core.Models; using Torshify.Radio.Framework; using WPFLocalizeExtension.Engine; namespace Torshify.Radio.Core.Startables { public class ShellSettingsHandler : IStartable { #region Properties [Import] public IDocumentStore DocumentStore { get; set; } #endregion Properties #region Methods void IStartable.Start() { var mainWindow = Application.Current.MainWindow; using (var session = DocumentStore.OpenSession()) { var settings = session.Query<ApplicationSettings>().FirstOrDefault(); if (settings != null && settings.FirstTimeWizardRun) { mainWindow.Width = settings.WindowWidth; mainWindow.Height = settings.WindowHeight; mainWindow.Left = settings.WindowLeft; mainWindow.Top = settings.WindowTop; } } mainWindow.Closing += MainWindowOnClosing; mainWindow.Show(); } private void MainWindowOnClosing(object sender, CancelEventArgs cancelEventArgs) { using (var session = DocumentStore.OpenSession()) { var settings = session.Query<ApplicationSettings>().FirstOrDefault(); if (settings == null) { settings = new ApplicationSettings(); } var mainWindow = Application.Current.MainWindow; settings.WindowHeight = mainWindow.ActualHeight; settings.WindowWidth = mainWindow.ActualWidth; settings.WindowLeft = mainWindow.Left; settings.WindowTop = mainWindow.Top; settings.Culture = LocalizeDictionary.Instance.Culture.ToString(); session.Store(settings); session.SaveChanges(); } } #endregion Methods } }
using Planning.AdvandcedProjectionActionSelection.OptimalPlanner; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Planning.AdvandcedProjectionActionSelection.PrivacyLeakageCalculation; namespace Planning { class MapsAgent { public static Mutex heursticCalcultionMutex = (Mutex)null; public static Dictionary<string, Mutex> massageListMutex = (Dictionary<string, Mutex>)null; public static Mutex goalChackMutex = (Mutex)null; public static Dictionary<string, bool> preferFlags = (Dictionary<string, bool>)null; public static Mutex tmpMutex = null; public string name = ""; public HashSet<GroundedPredicate> publicFacts = null; public AdvancedProjectionHeuristic projectionHeuristic = null; public Dictionary<string, List<Action>> heuristicPlan = null; public HashSet<GroundedPredicate> privateFacts = null; public List<GroundedPredicate> goal = null; private List<Action> m_actions = null; public List<Action> publicActions = null; public List<Action> privateActions = null; // private Problem problem; private Domain domain; private Problem problem; public MapsVertex startState = null; Dictionary<State, int> privateStateToIndex = null; Dictionary<int, State> indexToPrivateState = null; public List<GroundedPredicate> allGoal = null; public List<Landmark> publicRelevantLandmark = null; private List<Order> orderList = null; HashSet<MapsVertex> closeList = null; HashSet<MapsVertex> myOpenList = null; bool fGoal; MapsVertex courentVertex = null; bool first; Dictionary<string, int> landmarksCount = null; Dictionary<string, HashSet<MapsVertex>> openLists = null; Dictionary<string, HashSet<MapsVertex>> receivedStates = null; //Dictionary<string, Mutex> globalMutex; List<string> agentsNames = null; public List<Order> ReasonableOrdering = null; Dictionary<string, List<Predicate>> actionName_to_revealedDependenciesList; Dictionary<string, List<Predicate>> actionName_to_allDependenciesList; Dictionary<string, List<Predicate>> actionName_to_preconditionsDependenciesList; List<Predicate> dependenciesAtStartState; HashSet<Tuple<string, Predicate>> dependenciesUsed; //Revealing dependencies when stuck: Dictionary<Dependency, List<MapsVertex>> dependency_to_nonPublishedStatesList; PriorityQueue<Dependency, int> nextDependencyToBeRevealed; const int NUM_STATES_UNTIL_REVEALING_DEPENDENCY = 1000; int currentAmountOfStates; //now we need to use these datastructures in order to pick which dependency should be revealed when we get to a dead-end (1000 states without solving the problem) public MapsVertex startVertexForTrace; public Agent regularAgent; public MapsVertex realStartStateVertex; //For leakage calculation: public List<MapsVertex> allSentStates { get; private set; } public void AddToAllSentStates(MapsVertex sentVertex) { allSentStates.Add(sentVertex); allStates.Add(sentVertex); } public List<MapsVertex> allReceivedStates { get; private set; } public void AddToAllReceivedStates(MapsVertex recVertex) { allReceivedStates.Add(recVertex); allStates.Add(recVertex); } public List<MapsVertex> allStates { get; private set; } public static void ResetStaticFields() { counter = 0; preferFlags = (Dictionary<string, bool>)null; } public int GetID() { return Agent.getID(name); } public static void InitMutex() { heursticCalcultionMutex = new Mutex(); tmpMutex = new Mutex(); } public MapsAgent(MapsVertex start, Agent a, List<GroundedPredicate> m_allGoal, Dictionary<string, int> m_landmarksCount, Dictionary<string, HashSet<MapsVertex>> m_openLists, Dictionary<string, HashSet<MapsVertex>> m_receivedStates, Dictionary<string, Mutex> m_globalMutex, Dictionary<string, int> countOfReasonableOrdering, List<GroundedPredicate> fullState) { startVertexForTrace = start; realStartStateVertex = null; firstIt = true; domain = a.domain; problem = a.problem; privateStateToIndex = new Dictionary<State, int>(); indexToPrivateState = new Dictionary<int, State>(); goal = new List<GroundedPredicate>(a.goal); m_actions = new List<Action>(a.m_actions); publicActions = a.publicActions; privateActions = a.privateActions; //ReasonableOrdering = new List<Order>(); ReasonableOrdering = a.ReasonableOrdering; name = a.name; publicRelevantLandmark = a.publicRelevantLandmark; orderList = a.orderList; publicFacts = a.PublicPredicates; privateFacts = new HashSet<GroundedPredicate>(); foreach (GroundedPredicate gp in a.Predicates) { if (!publicFacts.Contains(gp)) { privateFacts.Add(gp); } } allGoal = new List<GroundedPredicate>(); allGoal.AddRange(m_allGoal); landmarksCount = m_landmarksCount; openLists = m_openLists; //globalMutex = m_globalMutex; receivedStates = m_receivedStates; State privateStartState = new State((Problem)null); List<GroundedPredicate> publicStartState = new List<GroundedPredicate>(); foreach (GroundedPredicate gp in a.startState.m_lPredicates) { if (!a.PublicPredicates.Contains(gp)) privateStartState.AddPredicate(gp); else { publicStartState.Add(gp); } } /* foreach (GroundedPredicate gp in aproximationState.Predicates) { if (PublicPredicates.Contains(gp)) { aproximatePublicState.AddPredicate(gp); } }*/ // prePlanning(); closeList = new HashSet<MapsVertex>(); agentsNames = openLists.Keys.ToList(); // Dictionary<State, int> closeList = new Dictionary<State, int>(); myOpenList = new HashSet<MapsVertex>(); myPreferableOpenList = new HashSet<MapsVertex>(); // MapsVertex agentStartVertex = new MapsVertex(privateStartState, publicStartState, landmarksCount, landmarksCount.Keys.ToArray(), name, allGoal.Count, countOfReasonableOrdering); myOpenList.Add(start); fGoal = false; MapsVertex courentVertex = null; first = true; actionName_to_revealedDependenciesList = new Dictionary<string, List<Predicate>>(); actionName_to_allDependenciesList = new Dictionary<string, List<Predicate>>(); actionName_to_preconditionsDependenciesList = new Dictionary<string, List<Predicate>>(); dependenciesAtStartState = new List<Predicate>(); dependenciesUsed = new HashSet<Tuple<string, Predicate>>(); allSentStates = new List<MapsVertex>(); allReceivedStates = new List<MapsVertex>(); allStates = new List<MapsVertex>(); } public void AddToEffectsActionsAndDependencies(string actionName, List<Predicate> predicates) { actionName_to_revealedDependenciesList.Add(actionName, predicates); } public void AddToAllDependenciesListOfAction(string actionName, List<Predicate> predicates) { actionName_to_allDependenciesList.Add(actionName, predicates); } public void AddToPreconditionActionsAndDependencies(string actionName, List<Predicate> predicates) { actionName_to_preconditionsDependenciesList.Add(actionName, predicates); } public void AddToUsedDependencies(string action, Predicate effect) { dependenciesUsed.Add(new Tuple<string, Predicate>(action, effect)); } public int GetAmountOfUsedDependencies() { return dependenciesUsed.Count; } public void SetDependenciesAtStartState(List<Predicate> predicates) { dependenciesAtStartState = predicates; } public List<Predicate> GetPredicatesRevealedByAction(string actionName) { return actionName_to_revealedDependenciesList[actionName]; } public List<Predicate> GetAllPossibleDependenciesOfAction(string actionName) { throw new NotImplementedException(); } public List<Predicate> GetPredicatesPreconditionsForAction(string actionName) { return actionName_to_preconditionsDependenciesList[actionName]; } public List<Predicate> GetDependenciesAtStartState() { return dependenciesAtStartState; } public void SetPublicOpenLists(Dictionary<string, HashSet<MapsVertex>> newGlobalOpenList) { openLists = newGlobalOpenList; } public HashSet<Predicate> WhatICanGet(HashSet<Predicate> courrentStateOrg) { HashSet<Predicate> courrentState = new HashSet<Predicate>(courrentStateOrg); bool flag2 = true; List<Action> tempActionList = new List<Action>(); while (flag2) { flag2 = false; foreach (Action act in privateActions) { if (tempActionList.Contains(act)) continue; if (Contains(courrentState, act.HashPrecondition)) { tempActionList.Add(act); if (act.Effects != null) { foreach (GroundedPredicate addProp in act.HashEffects) { if (!courrentState.Contains(addProp)) { courrentState.Add(addProp); flag2 = true; } } } } } } return courrentState; } public Dictionary<GroundedPredicate, int> GetRelaxGraph(State s, List<GroundedPredicate> restGoals) { Dictionary<GroundedPredicate, int> deleteGraph = new Dictionary<GroundedPredicate, int>(); foreach (GroundedPredicate gp in s.m_lPredicates) { deleteGraph.Add(gp, 0); } HashSet<Predicate> tmpState = new HashSet<Predicate>(s.m_lPredicates); bool stop = false; int level = 1; List<GroundedPredicate> setCopy = new List<GroundedPredicate>(); HashSet<Action> allReadyUse = new HashSet<Action>(); while (!stop) { stop = true; foreach (Action action in m_actions) { if (allReadyUse.Contains(action)) continue; if (Contains(tmpState, action.HashPrecondition)) { allReadyUse.Add(action); foreach (GroundedPredicate eff in action.HashEffects) { if (!tmpState.Contains(eff) && !setCopy.Contains(eff)) { //publicPre.Add(eff, 1); setCopy.Add(eff); } } } } foreach (GroundedPredicate add in setCopy) { tmpState.Add(add); if (publicFacts.Contains(add)) { deleteGraph.Add(add, level); } stop = false; } level++; setCopy = new List<GroundedPredicate>(); if (!stop) { stop = true; foreach (GroundedPredicate goalFact in restGoals) { if (!tmpState.Contains(goalFact)) { stop = false; break; } } } } return deleteGraph; } public bool[][] Geth(State courentState, out bool[] satisfiedNew, bool[] lVetor, bool[] oVector) { bool[] landmarksVector = new bool[lVetor.Length]; bool[] ReasonableOrdering = new bool[oVector.Length]; Array.Copy(lVetor, landmarksVector, lVetor.Length); Array.Copy(oVector, ReasonableOrdering, oVector.Length); bool[] newPublicRelevantLandmarks = null; bool[] newReasonableOrdering = null; int notSatisfy = SatisfyLandmark(courentState.m_lPredicates, landmarksVector, out newPublicRelevantLandmarks, ReasonableOrdering, out newReasonableOrdering, out satisfiedNew); bool[][] ans = new bool[2][]; ans[0] = new bool[newPublicRelevantLandmarks.Length]; ans[1] = new bool[newReasonableOrdering.Length]; Array.Copy(newPublicRelevantLandmarks, ans[0], newPublicRelevantLandmarks.Length); Array.Copy(newReasonableOrdering, ans[1], newReasonableOrdering.Length); return ans; } public bool[][] GetInitialVectors(State courrent) { bool[] landmarkVector = new bool[publicRelevantLandmark.Count]; bool[] newLandmarkVector = new bool[publicRelevantLandmark.Count]; for (int i = 0; i < landmarkVector.Length; i++) { landmarkVector[i] = false; } bool[] actionVector = new bool[privateActions.Count]; bool[] reasonableOrdering = new bool[ReasonableOrdering.Count()]; bool[] outReasonableOrdering = null; bool[] satisfiedNew = null; SatisfyLandmark(courrent.m_lPredicates, landmarkVector, out newLandmarkVector, reasonableOrdering, out outReasonableOrdering, out satisfiedNew); bool[][] initialVectors = new bool[2][]; initialVectors[0] = newLandmarkVector; initialVectors[1] = outReasonableOrdering; return initialVectors; } private int SatisfyLandmark2(HashSet<Predicate> newState, bool[] landmarks, out bool[] notSatisfiedLandmarks, bool[] reasonableOrderingVector, out bool[] outReasonableOrdering, out bool[] satisfiedNew) { outReasonableOrdering = new bool[reasonableOrderingVector.Length]; Array.Copy(reasonableOrderingVector, outReasonableOrdering, reasonableOrderingVector.Length); int notSatisfied = 0; bool f = false; notSatisfiedLandmarks = new bool[landmarks.Length]; satisfiedNew = new bool[landmarks.Length]; for (int i = 0; i < landmarks.Length; i++) { f = false; if (landmarks[i] == false) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; satisfiedNew[i] = true; f = true; /*for (int k = 0; k < outReasonableOrdering.Length; k++) { if (outReasonableOrdering[k] == false && ReasonableOrdering[k].lendmark1.Equals(publicRelevantLandmark[i])) { outReasonableOrdering[k] = true; } }*/ break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied += 1; } } else { //if (publicRelevantLandmark[i].facts.ElementAt(0).Value.Equals("Goal")) if (publicRelevantLandmark[i].GoalLandmark) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; satisfiedNew[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied += 1;// publicRelevantLandmark[i].worth; } } else { notSatisfiedLandmarks[i] = true; foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { satisfiedNew[i] = true; break; } } } } } bool agein = true; while (agein) { agein = false; for (int i = 0; i < notSatisfiedLandmarks.Length; i++) { f = false; if (notSatisfiedLandmarks[i] == true) { /* foreach (Order order in orderList) { // if(order.lendmark1.ToString().Equals(Domain.FALSE_PREDICATE) ) // continue; if (order.lendmark1.Equals(publicRelevantLandmark[i])) { int index = order.lendmark2.index; if (index > -1) { if (notSatisfiedLandmarks[index] == false) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied += publicRelevantLandmark[i].worth; agein = true; break; } } } } }*/ int counter = 0; foreach (Order order in ReasonableOrdering) { if (outReasonableOrdering[counter] == false) { if (order.lendmark2.Equals(publicRelevantLandmark[i])) { int index = order.lendmark1.index; if (notSatisfiedLandmarks[index] == false) { notSatisfiedLandmarks[i] = false; notSatisfied += 1;// publicRelevantLandmark[i].worth; agein = true; break; } } } counter++; } } } } for (int i = 0; i < notSatisfiedLandmarks.Length; i++) { if (landmarks[i] == false && notSatisfiedLandmarks[i] == true) { for (int k = 0; k < outReasonableOrdering.Length; k++) { if (outReasonableOrdering[k] == false && ReasonableOrdering[k].lendmark1.Equals(publicRelevantLandmark[i])) { outReasonableOrdering[k] = true; } } } } return notSatisfied; } private int SatisfyLandmark(HashSet<Predicate> newState, bool[] landmarks, out bool[] notSatisfiedLandmarks, bool[] reasonableOrderingVector, out bool[] outReasonableOrdering, out bool[] satisfiedNew) { outReasonableOrdering = new bool[reasonableOrderingVector.Length]; Array.Copy(reasonableOrderingVector, outReasonableOrdering, reasonableOrderingVector.Length); int notSatisfied = 0; bool f = false; notSatisfiedLandmarks = new bool[landmarks.Length]; satisfiedNew = new bool[landmarks.Length]; for (int i = 0; i < landmarks.Length; i++) { f = false; if (landmarks[i] == false) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; satisfiedNew[i] = true; f = true; for (int k = 0; k < outReasonableOrdering.Length; k++) { if (outReasonableOrdering[k] == false && ReasonableOrdering[k].lendmark1.Equals(publicRelevantLandmark[i])) { outReasonableOrdering[k] = true; } } break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied += 1; } } else { //if (publicRelevantLandmark[i].facts.ElementAt(0).Value.Equals("Goal")) if (publicRelevantLandmark[i].GoalLandmark) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; satisfiedNew[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied += 1;// publicRelevantLandmark[i].worth; } } else { notSatisfiedLandmarks[i] = true; foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { satisfiedNew[i] = true; break; } } } } } bool agein = true; while (agein) { agein = false; for (int i = 0; i < notSatisfiedLandmarks.Length; i++) { f = false; if (notSatisfiedLandmarks[i] == true) { /* foreach (Order order in orderList) { // if(order.lendmark1.ToString().Equals(Domain.FALSE_PREDICATE) ) // continue; if (order.lendmark1.Equals(publicRelevantLandmark[i])) { int index = order.lendmark2.index; if (index > -1) { if (notSatisfiedLandmarks[index] == false) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied += publicRelevantLandmark[i].worth; agein = true; break; } } } } }*/ int counter = 0; foreach (Order order in ReasonableOrdering) { if (outReasonableOrdering[counter] == false) { if (order.lendmark2.Equals(publicRelevantLandmark[i])) { int index = order.lendmark1.index; if (notSatisfiedLandmarks[index] == false) { notSatisfiedLandmarks[i] = false; notSatisfied += 1;// publicRelevantLandmark[i].worth; agein = true; break; } } } counter++; } } } } return notSatisfied; } public int SetPrivateState(State PrivateState) { if (!privateStateToIndex.ContainsKey(PrivateState)) { privateStateToIndex.Add(PrivateState, privateStateToIndex.Count); indexToPrivateState.Add(privateStateToIndex.Count - 1, PrivateState); return privateStateToIndex.Count - 1; } else { return privateStateToIndex[PrivateState]; } } public State GetPrivateState(int index) { return indexToPrivateState[index]; } private bool Contains(HashSet<GroundedPredicate> x, HashSet<GroundedPredicate> y) { if (y == null) return true; if (x == null) { if (y.Count == 0) return true; return false; } foreach (GroundedPredicate gP in y) { if (!x.Contains(gP)) return false; } return true; } private bool Contains(HashSet<GroundedPredicate> x, List<Predicate> y) { if (y == null) return true; if (x == null) { if (y.Count == 0) return true; return false; } foreach (GroundedPredicate gP in y) { if (!x.Contains(gP)) return false; } return true; } private bool Contains(HashSet<Predicate> x, List<Predicate> y) { if (y == null) return true; if (x == null) { if (y.Count == 0) return true; return false; } foreach (GroundedPredicate gP in y) { if (!x.Contains(gP)) return false; } return true; } private bool Contains(HashSet<GroundedPredicate> x, List<GroundedPredicate> y) { if (y == null) return true; if (x == null) { if (y.Count == 0) return true; return false; } foreach (GroundedPredicate gP in y) { if (!x.Contains(gP)) return false; } return true; } private bool Contains(State x, List<Predicate> y) { if (y == null) return true; if (x == null) { if (y.Count == 0) return true; return false; } foreach (GroundedPredicate gP in y) { if (!x.m_lPredicates.Contains(gP)) return false; } return true; } private bool Contains(State x, List<GroundedPredicate> y) { if (y == null) return true; if (x == null) { if (y.Count == 0) return true; return false; } foreach (GroundedPredicate gP in y) { if (!x.m_lPredicates.Contains(gP)) return false; } return true; } private int SatisfyLandmark(HashSet<Predicate> newState, bool[] landmarks, out bool[] notSatisfiedLandmarks) { int notSatisfied = 0; bool f = false; notSatisfiedLandmarks = new bool[landmarks.Length]; for (int i = 0; i < landmarks.Length; i++) { f = false; if (landmarks[i] == false) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied++; } } else { if (publicRelevantLandmark[i].facts.ElementAt(0).Value.Equals("Goal")) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied++; } } else { notSatisfiedLandmarks[i] = true; } } } bool agein = true; while (agein) { agein = false; for (int i = 0; i < notSatisfiedLandmarks.Length; i++) { f = false; if (notSatisfiedLandmarks[i] == true) { foreach (Order order in orderList) { if (order.lendmark1 == publicRelevantLandmark[i]) { int index = publicRelevantLandmark.IndexOf(order.lendmark2); if (notSatisfiedLandmarks[index] == false) { foreach (GroundedPredicate fact in publicRelevantLandmark[i].facts.Keys) { if (newState.Contains(fact)) { notSatisfiedLandmarks[i] = true; f = true; break; } } if (!f) { notSatisfiedLandmarks[i] = false; notSatisfied++; agein = true; break; } } } } } } } return notSatisfied; } public Dictionary<MapsVertex, HashSet<MapsVertex>> parentToChildren = new Dictionary<MapsVertex, HashSet<MapsVertex>>(); HashSet<MacroAction> allMacroActions = new HashSet<MacroAction>(); bool sendToAll = true; public static int counter = 0; int minh = 100000; VertexComparer vc = new VertexComparer(); HashSet<MapsVertex> notSended = new HashSet<MapsVertex>(); HashSet<MacroAction> macroActions = new HashSet<MacroAction>(); // HashSet<MacroAction> localMacro = new HashSet<MacroAction>(); public List<string> BeginPlanning() { try { courentVertex = null; foreach (MapsVertex publicVertex in openLists[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; myOpenList.Add(publicVertex); } } if (openLists[name].Count > 0) { openLists[name] = new HashSet<MapsVertex>(); } if (!sendToAll) { foreach (MapsVertex publicVertex in receivedStates[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; myOpenList.Add(publicVertex); } } if (receivedStates[name].Count > 0) { receivedStates[name] = new HashSet<MapsVertex>(); } } if (myOpenList.Count > 0) { courentVertex = FindMinByLandmak(myOpenList); //if (courentVertex.h == 10) // Console.Write("d"); if (!sendToAll) { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { Action action = courentVertex.lplan.Last(); if (courentVertex.returnTo != null && !action.isGoalAction) { if (MapsPlanner.AgentToInfluActions[name][courentVertex.returnTo[0]].Contains(action)) { SendVertex(courentVertex, courentVertex.returnTo[0]); } } else { SendVertex(courentVertex, action); } } //if (courentVertex.lplan.Count > 0 && (courentVertex.fromOthers || courentVertex.lplan.Last().isDeletePublic) && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) if (courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) { if (courentVertex.fromOthers) { SendVertexToInf(courentVertex, courentVertex.lplan.Last()); } else { if (courentVertex.lplan.Last().isDeletePublic) { SendVertexToInf2(courentVertex, courentVertex.lplan.Last()); } } // if(courentVertex.lplan.Last().isDeletePublic) // Console.WriteLine("dd"); } } else { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { //SendVertexToAll(courentVertex); bool flag = true; if (myOpenList.Contains(courentVertex, vc)) { flag = false; Program.notSendedStates++; notSended.Add(courentVertex); } else if (closeList.Contains(courentVertex, vc)) { flag = false; Program.notSendedStates++; notSended.Add(courentVertex); } if (flag) SendVertexToAll(courentVertex); } } Program.StateExpendCounter++; // if (name.Contains("2")&& courentVertex.h==5) // Console.Write(" "); closeList.Add(courentVertex); if (courentVertex.h == 0) { if (courentVertex.IsGoal(allGoal)) { Program.StartHighLevelPlanning = DateTime.Now; Console.WriteLine("***************************** "); // Console.WriteLine("massageEffCounter: "+MapsPlanner.massageEffCounter); //Console.WriteLine("massagePreCounter: " + MapsPlanner.massagePreCounter); List<Action> allActions = new List<Action>(); foreach (Action act in courentVertex.lplan) { if (act is MacroAction) { Program.countMacro++; Program.countAvgPerMacro += ((MacroAction)act).microActions.Count; } } Program.countAvgPerMacro = Program.countAvgPerMacro / Program.countMacro; relaxActions(allActions, courentVertex.lplan); Program.countActions.Add(courentVertex.lplan.Count); Program.actionSum += courentVertex.lplan.Count; List<string> lplan = new List<string>(); foreach (Action act in allActions) lplan.Add(act.Name); return lplan; } else { Console.WriteLine("****"); } } List<Action> addMacroActions = new List<Action>(); foreach (Action action in m_actions) { MapsVertex newVertex = courentVertex.Aplly(action); if (newVertex != null) { newVertex.returnTo = courentVertex.returnTo; bool inlClose = closeList.Contains(newVertex); bool inlOpen = myOpenList.Contains(newVertex); if (!inlClose && !inlOpen) { if (newVertex.h < minh) { minh = newVertex.h; Console.Write(minh + " "); } myOpenList.Add(newVertex); } } } m_actions.AddRange(addMacroActions); } return null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } } HashSet<MapsVertex> myPreferableOpenList = null; public int GetCountOfPreferableList() { return myPreferableOpenList.Count; } int PreferableCounter = 1; bool firstIteration = true; bool firstIt; public static bool thereIsPrivate; public bool openIsEmpty() { return openLists[name].Count == 0 && myPreferableOpenList.Count == 0 && myOpenList.Count == 0; } public List<string> BeginPreferablePlanning() { try { courentVertex = null; foreach (MapsVertex publicVertex in openLists[name]) { Program.cancellationTokenSource.Token.ThrowIfCancellationRequested(); publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); inOpenList = inOpenList && myPreferableOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; publicVertex.changingAgent = true; /* MacroAction newAct = new MacroAction(publicVertex.publicParent, publicVertex); if (!macroActions.Contains(newAct)) { macroActions.Add(newAct); //m_actions.Add(newAct); } */ if (publicVertex.isPreferable) { myPreferableOpenList.Add(publicVertex); } else { myOpenList.Add(publicVertex); } } } if (openLists[name].Count > 0) { openLists[name] = new HashSet<MapsVertex>(); } if (!sendToAll) { foreach (MapsVertex publicVertex in receivedStates[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); inOpenList = inOpenList && myPreferableOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; publicVertex.changingAgent = true; if (publicVertex.isPreferable) { myPreferableOpenList.Add(publicVertex); } else { myOpenList.Add(publicVertex); } } } if (receivedStates[name].Count > 0) { receivedStates[name] = new HashSet<MapsVertex>(); } } if (myOpenList.Count == 0 && notSended.Count > 0 && myPreferableOpenList.Count == 0) { foreach (MacroAction ma in macroActions) { foreach (MapsVertex mv in notSended) { MapsVertex newMv = mv.Aplly(ma); if (newMv != null) { bool incloseList = closeList.Contains(newMv); bool inOpenList = myOpenList.Contains(newMv); if (!incloseList && !inOpenList) { myOpenList.Add(newMv); } } } } } int old_h = 0; PreferableCounter = 1000; if (myOpenList.Count > 0 || myPreferableOpenList.Count > 0) { if ((myOpenList.Count == 0 || PreferableCounter > 0) && myPreferableOpenList.Count > 0) { courentVertex = FindMinByLandmak(myPreferableOpenList); // old_h = courentVertex.ComputeFF_h(); if (Program.projectionVersion == Program.ProjectionVersion.fullGlobal) { // courentVertex.GetProjection_h(); } if (Program.projectionVersion == Program.ProjectionVersion.ProjectionFF) { // PreferableCounter = 1000; if (!courentVertex.changingAgent) { courentVertex.GetProjection_h(); } else { // if(thereIsPrivate) { courentVertex.GetProjection_h(); } } // if (courentVertex.h != old_h) // Console.WriteLine("ddd"); } if (Program.projectionVersion == Program.ProjectionVersion.Global) { PreferableCounter = 10000; if (courentVertex.changingAgent) courentVertex.FindLocalPlan(); } if (Program.projectionVersion == Program.ProjectionVersion.GlobalV2) { PreferableCounter = 10000; if (courentVertex.changingAgent) courentVertex.FindLocalPlan(); } if (courentVertex.h < minh) { PreferableCounter += 1000; minh = courentVertex.h; // if (minh==0) Console.Write(minh + " "); } PreferableCounter--; } else { // if (Program.projectionVersion != Program.ProjectionVersion.ProjectionFF) if (true) // global prefer operator { if (Program.projectionVersion == Program.ProjectionVersion.Global) { if (MapsAgent.preferFlags.Values.Contains(true)) return null; } else { if (MapsAgent.preferFlags.Values.Contains(true) && !firstIt) return null; } } firstIt = false; courentVertex = FindMinByLandmak(myOpenList); //old_h = courentVertex.ComputeFF_h(); if (Program.projectionVersion == Program.ProjectionVersion.ProjectionFF) { if (!courentVertex.changingAgent) { courentVertex.GetProjection_h(); } else { //if (thereIsPrivate) { courentVertex.GetProjection_h(); } } } else courentVertex.GetProjection_h(); //if (courentVertex.h != old_h) // Console.WriteLine("ddd"); if (courentVertex.h < minh) { minh = courentVertex.h; // if (minh == 0) Console.Write(minh + " "); } PreferableCounter++; } /* if (courentVertex.h >= int.MaxValue / 2) { return null; }*/ //if (courentVertex.h < old_h-1&& old_h!=1000) // Console.Write("d"); if (!sendToAll) { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { Action action = courentVertex.lplan.Last(); if (courentVertex.returnTo != null && !action.isGoalAction) { if (MapsPlanner.AgentToInfluActions[name][courentVertex.returnTo[0]].Contains(action)) { SendVertex(courentVertex, courentVertex.returnTo[0]); } } else { SendVertex(courentVertex, action); } } //if (courentVertex.lplan.Count > 0 && (courentVertex.fromOthers || courentVertex.lplan.Last().isDeletePublic) && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) if (courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) { if (courentVertex.fromOthers) { SendVertexToInf(courentVertex, courentVertex.lplan.Last()); } else { if (courentVertex.lplan.Last().isDeletePublic) { SendVertexToInf2(courentVertex, courentVertex.lplan.Last()); } } // if(courentVertex.lplan.Last().isDeletePublic) // Console.WriteLine("dd"); } } else { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { //SendVertexToAll(courentVertex); bool flag = true; bool sendingRealStartState = false; /* * This is for sending only states that are different in their public reflection. * If there is a state that we already sent that has the same public reflection as this state, * don't send this state. We will remove this for now and return to it later if we see it is needed. * We can come to this later by saying as if this vertex has the "vertex.traceStateForPublicRevealedState" * of his father, this way it will make it's childern to put their iparent as their grandfather's iparent. if (closeList.Contains(courentVertex, vc)) { flag = false; } */ if (flag) { flag = MapsPlanner.MAFSPublisher.CanPublish(this, courentVertex); if (flag) { courentVertex.h_when_sent = courentVertex.h; MapsPlanner.tracesHandler.publishState(courentVertex, this); //Handle i-parent dictionary: courentVertex.agent2iparentVertex = new Dictionary<string, MapsVertex>(courentVertex.publicParent.agent2iparentVertex); HandleIParent(courentVertex, this); courentVertex.senderAgent = this.name; if (courentVertex.lplan.Last().Name.Contains("turn-to-regular-actions-stage")) { realStartStateVertex = courentVertex; if (MapsPlanner.tracesHandler.usesRealStartState()) { int startStateID = TraceState.GetNextStateID(); Dictionary<string, int> iparents = new Dictionary<string, int>(); MapsPlanner.tracesHandler.publishRealStartState(this, courentVertex, startStateID, iparents); } sendingRealStartState = true; } } } if (!flag) { //courentVertex.agent2iparentVertex = courentVertex.publicParent.agent2iparentVertex; courentVertex.agent2iparent = courentVertex.publicParent.agent2iparent; courentVertex.traceStateForPublicRevealedState = courentVertex.publicParent.traceStateForPublicRevealedState; // not sending... Program.notSendedStates++; //notSended.Add(courentVertex); //Skip the expansion of this vertex: closeList.Add(courentVertex); goto done_outer_if; } if (flag && !MapsPlanner.directMessage) SendVertexToAllAgentOnNextListUse(courentVertex, sendingRealStartState); else { if (flag && MapsPlanner.directMessage) SendVertexToAll(courentVertex); } } } Program.StateExpendCounter++; // if (name.Contains("2")&& courentVertex.h==5) // Console.Write(" "); closeList.Add(courentVertex); if (courentVertex.h == 1) { //courentVertex.GetProjection_h(); //Console.Write("dd"); } if (courentVertex.h == 0) { if (courentVertex.IsGoal(allGoal)) { if (courentVertex.h != 0) Console.WriteLine("chack this"); Program.StartHighLevelPlanning = DateTime.Now; Console.WriteLine("***************************** "); // Console.WriteLine("massageEffCounter: "+MapsPlanner.massageEffCounter); //Console.WriteLine("massagePreCounter: " + MapsPlanner.massagePreCounter); List<Action> allActions = new List<Action>(); foreach (Action act in courentVertex.lplan) { if (act is MacroAction) { Program.countMacro++; Program.countAvgPerMacro += ((MacroAction)act).microActions.Count; } } Program.countAvgPerMacro = Program.countAvgPerMacro / Program.countMacro; relaxActions(allActions, courentVertex.lplan); Program.countActions.Add(courentVertex.lplan.Count); Program.actionSum += courentVertex.lplan.Count; List<string> lplan = new List<string>(); List<string> highLevelPlan = new List<string>(); foreach (Action act in allActions) { lplan.Add(act.Name); if (act.isPublic) { highLevelPlan.Add(act.Name); } } MapsPlanner.highLevelPlan = highLevelPlan; MapsPlanner.tracesHandler.PublishGoalState(courentVertex, this); return lplan; } else { // Console.WriteLine("****"); } } // List<Action> addMacroActions = new List<Action>(); // bool chack = false; foreach (Action action in m_actions) { MapsVertex newVertex = courentVertex.Aplly(action); if (newVertex != null) { // chack = true; newVertex.returnTo = courentVertex.returnTo; bool inlClose = closeList.Contains(newVertex); bool inlOpen = myOpenList.Contains(newVertex); inlOpen = inlOpen && myPreferableOpenList.Contains(newVertex); if (!inlClose && !inlOpen) { if (newVertex.isPreferable)// && newVertex.relaxPlan.Count>0) { // newVertex.GetProjection_h(); myPreferableOpenList.Add(newVertex); } else { myOpenList.Add(newVertex); } } } } // if (!chack) // Console.Write("DD"); // m_actions.AddRange(addMacroActions); } //This is for skipping the expansion of states that shouldn't be expanded or revieled to the other agents: done_outer_if: if (myPreferableOpenList.Count > 0) MapsAgent.preferFlags[name] = true; else { MapsAgent.preferFlags[name] = false; } return null; } catch (System.Threading.ThreadAbortException taex) { //Don't print stack trace, because it just makes it look bad... Console.WriteLine(); //Go one line down so the heuristics will not disturb the "failed" printout return null; } catch(OperationCanceledException cancellationEx) { //Don't print stack trace, because it just makes it look bad... Console.WriteLine(); //Go one line down so the heuristics will not disturb the "failed" printout return null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } } private void HandleIParent(MapsVertex courentVertex, MapsAgent mapsAgent) { // check if the public parent of this vertex is the i-parent of it (sent by the current agent - or it is the start state...) if(courentVertex.publicParent.senderAgent == mapsAgent.name || courentVertex.publicParent == startVertexForTrace) { // if it is, then update the i-parent of this state to be the public parent of this state courentVertex.agent2iparentVertex[mapsAgent.name] = courentVertex.publicParent; } else { // if it is not, then the i-parent of this state is the same as the public parent's state courentVertex.agent2iparentVertex[mapsAgent.name] = courentVertex.publicParent.agent2iparentVertex[mapsAgent.name]; } } public List<string> BeginPreferableFFPlanning() { try { MapsAgent.preferFlags[name] = false; courentVertex = null; foreach (MapsVertex publicVertex in openLists[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); inOpenList = inOpenList && myPreferableOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; publicVertex.changingAgent = true; MacroAction newAct = new MacroAction(publicVertex.publicParent, publicVertex); if (!macroActions.Contains(newAct)) { macroActions.Add(newAct); //m_actions.Add(newAct); } if (publicVertex.isPreferable) { myPreferableOpenList.Add(publicVertex); } else { myOpenList.Add(publicVertex); } } } if (openLists[name].Count > 0) { openLists[name] = new HashSet<MapsVertex>(); } if (!sendToAll) { foreach (MapsVertex publicVertex in receivedStates[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); inOpenList = inOpenList && myPreferableOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; publicVertex.changingAgent = true; if (publicVertex.isPreferable) { myPreferableOpenList.Add(publicVertex); } else { myOpenList.Add(publicVertex); } } } if (receivedStates[name].Count > 0) { receivedStates[name] = new HashSet<MapsVertex>(); } } if (myOpenList.Count == 0 && notSended.Count > 0 && myPreferableOpenList.Count == 0) { foreach (MacroAction ma in macroActions) { foreach (MapsVertex mv in notSended) { MapsVertex newMv = mv.Aplly(ma); if (newMv != null) { bool incloseList = closeList.Contains(newMv); bool inOpenList = myOpenList.Contains(newMv); if (!incloseList && !inOpenList) { myOpenList.Add(newMv); } } } } } int old_h = 0; PreferableCounter = 1000; if (myOpenList.Count > 0 || myPreferableOpenList.Count > 0) { if ((myOpenList.Count == 0 || PreferableCounter > 0) && myPreferableOpenList.Count > 0) { courentVertex = FindMinByLandmak(myPreferableOpenList); old_h = courentVertex.h; if (!courentVertex.changingAgent) courentVertex.h = courentVertex.ComputeFF_h(); if (courentVertex.h < minh) { PreferableCounter += 1000; minh = courentVertex.h; Console.Write(minh + " "); } PreferableCounter--; } else { if (true) { if (MapsAgent.preferFlags.Values.Contains(true) && !firstIt) return null; } firstIt = false; courentVertex = FindMinByLandmak(myOpenList); old_h = courentVertex.h; if (!courentVertex.changingAgent) courentVertex.h = courentVertex.ComputeFF_h(); if (courentVertex.h < minh) { minh = courentVertex.h; Console.Write(minh + " "); } PreferableCounter++; } if (!sendToAll) { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { Action action = courentVertex.lplan.Last(); if (courentVertex.returnTo != null && !action.isGoalAction) { if (MapsPlanner.AgentToInfluActions[name][courentVertex.returnTo[0]].Contains(action)) { SendVertex(courentVertex, courentVertex.returnTo[0]); } } else { SendVertex(courentVertex, action); } } if (courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) { if (courentVertex.fromOthers) { SendVertexToInf(courentVertex, courentVertex.lplan.Last()); } else { if (courentVertex.lplan.Last().isDeletePublic) { SendVertexToInf2(courentVertex, courentVertex.lplan.Last()); } } } } else { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { bool flag = true; if (closeList.Contains(courentVertex, vc)) { flag = false; Program.notSendedStates++; notSended.Add(courentVertex); } if (flag && !MapsPlanner.directMessage) SendVertexToAllAgentOnNextListUse(courentVertex, false); else { if (flag && MapsPlanner.directMessage) SendVertexToAll(courentVertex); } } } Program.StateExpendCounter++; closeList.Add(courentVertex); if (courentVertex.h == 0) { if (courentVertex.IsGoal(allGoal)) { if (courentVertex.h != 0) Console.WriteLine("chack this"); Program.StartHighLevelPlanning = DateTime.Now; Console.WriteLine("***************************** "); // Console.WriteLine("massageEffCounter: "+MapsPlanner.massageEffCounter); //Console.WriteLine("massagePreCounter: " + MapsPlanner.massagePreCounter); List<Action> allActions = new List<Action>(); foreach (Action act in courentVertex.lplan) { if (act is MacroAction) { Program.countMacro++; Program.countAvgPerMacro += ((MacroAction)act).microActions.Count; } } Program.countAvgPerMacro = Program.countAvgPerMacro / Program.countMacro; relaxActions(allActions, courentVertex.lplan); Program.countActions.Add(courentVertex.lplan.Count); Program.actionSum += courentVertex.lplan.Count; List<string> lplan = new List<string>(); foreach (Action act in allActions) lplan.Add(act.Name); return lplan; } else { // Console.WriteLine("****"); } } List<Action> addMacroActions = new List<Action>(); foreach (Action action in m_actions) { MapsVertex newVertex = courentVertex.Aplly(action); if (newVertex != null) { newVertex.returnTo = courentVertex.returnTo; bool inlClose = closeList.Contains(newVertex); bool inlOpen = myOpenList.Contains(newVertex); inlOpen = inlOpen && myPreferableOpenList.Contains(newVertex); if (!inlClose && !inlOpen) { if (newVertex.isPreferable) { //newVertex.h = newVertex.ComputeFF_h(); myPreferableOpenList.Add(newVertex); } else { myOpenList.Add(newVertex); } } } } m_actions.AddRange(addMacroActions); } if (myPreferableOpenList.Count > 0) MapsAgent.preferFlags[name] = true; return null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } } public void BeginDistrebutedPreferablePlanning() { MapsVertex courentVertex = null; /* if (firstIteration) { courentVertex = FindMinByLandmak(myOpenList); MapsPlanner.tmpMutex.WaitOne(); // MapsPlanner.heursticCalcultionMutex.WaitOne(); courentVertex.GetProjection_h(); // MapsPlanner.heursticCalcultionMutex.ReleaseMutex(); MapsPlanner.tmpMutex.ReleaseMutex(); if (courentVertex.h < minh) { minh = courentVertex.h; Console.Write(minh + " "); } }*/ while (!MapsPlanner.findGoal) { try { /* tmpMutex.WaitOne(); foreach (MapsVertex publicVertex in openLists[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); inOpenList = inOpenList && myPreferableOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; publicVertex.changingAgent = true; MacroAction newAct = new MacroAction(publicVertex.publicParent, publicVertex); if (!macroActions.Contains(newAct)) { macroActions.Add(newAct); //m_actions.Add(newAct); } if (publicVertex.isPreferable) { myPreferableOpenList.Add(publicVertex); } else { myOpenList.Add(publicVertex); } } } if (openLists[name].Count > 0) { openLists[name] = new HashSet<MapsVertex>(); } tmpMutex.ReleaseMutex();*/ /* if (!sendToAll) { foreach (MapsVertex publicVertex in receivedStates[name]) { publicVertex.ChangeAgent(name, orderList, publicRelevantLandmark, ReasonableOrdering); bool incloseList = false; bool inOpenList = false; incloseList = closeList.Contains(publicVertex); inOpenList = myOpenList.Contains(publicVertex); inOpenList = inOpenList && myPreferableOpenList.Contains(publicVertex); if (!incloseList && !inOpenList) { publicVertex.fromOthers = true; publicVertex.changingAgent = true; if (publicVertex.isPreferable) { myPreferableOpenList.Add(publicVertex); } else { myOpenList.Add(publicVertex); } } } if (receivedStates[name].Count > 0) { receivedStates[name] = new HashSet<MapsVertex>(); } } if (myOpenList.Count == 0 && notSended.Count > 0 && myPreferableOpenList.Count == 0) { foreach (MacroAction ma in localMacro) { foreach (MapsVertex mv in notSended) { MapsVertex newMv = mv.Aplly(ma); if (newMv != null) { bool incloseList = closeList.Contains(newMv); bool inOpenList = myOpenList.Contains(newMv); if (!incloseList && !inOpenList) { myOpenList.Add(newMv); } } } } } */ int old_h = 0; if (name.Contains("4")) Console.WriteLine("stop"); if (myOpenList.Count > 0 || myPreferableOpenList.Count > 0) { if ((myOpenList.Count == 0 || PreferableCounter > 0) && myPreferableOpenList.Count > 0) { // MapsPlanner.heursticCalcultionMutex.WaitOne(); courentVertex = FindMinByLandmak(myPreferableOpenList); // MapsPlanner.heursticCalcultionMutex.ReleaseMutex(); old_h = courentVertex.h; if (Program.projectionVersion == Program.ProjectionVersion.Local) { if (courentVertex.localPlan == null) { heursticCalcultionMutex.WaitOne(); courentVertex.GetProjection_h(); heursticCalcultionMutex.ReleaseMutex(); } } if (Program.projectionVersion == Program.ProjectionVersion.Global) { if (courentVertex.changingAgent) { heursticCalcultionMutex.WaitOne(); courentVertex.GetProjection_h(); heursticCalcultionMutex.ReleaseMutex(); } //courentVertex.GroundMyLocal(); } if (courentVertex.h < minh) { PreferableCounter += 1000; minh = courentVertex.h; // Console.Write(minh + " "); } PreferableCounter--; } else { courentVertex = FindMinByLandmak(myOpenList); old_h = courentVertex.h; Console.WriteLine("Try to Enter: " + name); heursticCalcultionMutex.WaitOne(); Console.WriteLine("Enter: " + name); courentVertex.GetProjection_h(); heursticCalcultionMutex.ReleaseMutex(); Console.WriteLine("Exit: " + name); if (courentVertex.h < minh) { minh = courentVertex.h; // Console.Write(minh + " "); } PreferableCounter++; } if (courentVertex.h >= int.MaxValue / 2) { continue; } if (name.Contains("4")) Console.WriteLine("stop"); /*if (!sendToAll) { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { Action action = courentVertex.lplan.Last(); if (courentVertex.returnTo != null && !action.isGoalAction) { if (MapsPlanner.AgentToInfluActions[name][courentVertex.returnTo[0]].Contains(action)) { SendVertex(courentVertex, courentVertex.returnTo[0]); } } else { SendVertex(courentVertex, action); } } //if (courentVertex.lplan.Count > 0 && (courentVertex.fromOthers || courentVertex.lplan.Last().isDeletePublic) && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) if (courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic && !courentVertex.lplan.Last().isGoalAction) { if (courentVertex.fromOthers) { SendVertexToInf(courentVertex, courentVertex.lplan.Last()); } else { if (courentVertex.lplan.Last().isDeletePublic) { SendVertexToInf2(courentVertex, courentVertex.lplan.Last()); } } // if(courentVertex.lplan.Last().isDeletePublic) // Console.WriteLine("dd"); } } else { if (!courentVertex.fromOthers && courentVertex.lplan.Count > 0 && courentVertex.lplan.Last().isPublic) { //SendVertexToAll(courentVertex); bool flag = true; if (myOpenList.Contains(courentVertex, vc) || myPreferableOpenList.Contains(courentVertex, vc)) { flag = false; Program.notSendedStates++; notSended.Add(courentVertex); } else { if (closeList.Contains(courentVertex, vc)) { flag = false; Program.notSendedStates++; notSended.Add(courentVertex); } } if (flag) { SendVertexToAllLockFirst(courentVertex); } } }*/ Program.StateExpendCounter++; // if (name.Contains("2")&& courentVertex.h==5) // Console.Write(" "); closeList.Add(courentVertex); if (courentVertex.h == 1) { //courentVertex.GetProjection_h(); //Console.Write("dd"); } if (courentVertex.h == 0) { if (courentVertex.IsGoal(allGoal)) { //MapsPlanner.goalChackMutex.WaitOne(); if (MapsPlanner.findGoal == true) { // MapsPlanner.goalChackMutex.ReleaseMutex(); return; } else { MapsPlanner.findGoal = true; // MapsPlanner.goalChackMutex.ReleaseMutex(); } if (courentVertex.h != 0) Console.WriteLine("chack this"); Program.StartHighLevelPlanning = DateTime.Now; Console.WriteLine("***************************** "); // Console.WriteLine("massageEffCounter: "+MapsPlanner.massageEffCounter); //Console.WriteLine("massagePreCounter: " + MapsPlanner.massagePreCounter); List<Action> allActions = new List<Action>(); foreach (Action act in courentVertex.lplan) { if (act is MacroAction) { Program.countMacro++; Program.countAvgPerMacro += ((MacroAction)act).microActions.Count; } } Program.countAvgPerMacro = Program.countAvgPerMacro / Program.countMacro; relaxActions(allActions, courentVertex.lplan); Program.countActions.Add(courentVertex.lplan.Count); Program.actionSum += courentVertex.lplan.Count; List<string> lplan = new List<string>(); foreach (Action act in allActions) lplan.Add(act.Name); MapsPlanner.finalPlan = lplan; } else { // Console.WriteLine("****"); } } List<Action> addMacroActions = new List<Action>(); foreach (Action action in m_actions) { MapsVertex newVertex = courentVertex.Aplly(action); if (newVertex != null) { newVertex.returnTo = courentVertex.returnTo; bool inlClose = closeList.Contains(newVertex); bool inlOpen = myOpenList.Contains(newVertex); inlOpen = inlOpen && myPreferableOpenList.Contains(newVertex); if (!inlClose && !inlOpen) { if (newVertex.isPreferable) { myPreferableOpenList.Add(newVertex); } else { myOpenList.Add(newVertex); } } } } //m_actions.AddRange(addMacroActions); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } Console.WriteLine("***********************"); } public void SendVertexToInf(MapsVertex mv, Action lastAction) { try { List<string> sendingTo = new List<string>(); foreach (string agentName in MapsPlanner.influencedByAgents[name].ToList()) { if (mv.shareWith != null && mv.shareWith.Contains(agentName)) continue; sendingTo.Add(agentName); } for (int i = 0; i < sendingTo.Count; i++) { // if (lastAction==null || !MapsPlanner.actionMap[lastAction.Name].Contains(agentName)) { string agentName = sendingTo[i]; if (mv.returnTo != null && mv.returnTo.Contains(agentName)) continue; MapsPlanner.massagePreCounter++; Program.sendedStateCounter++; MapsVertex sendingVertex = new MapsVertex(mv); sendingVertex.fullCopy(mv); if (mv.returnTo != null) sendingVertex.returnTo = new List<string>(mv.returnTo); else { sendingVertex.returnTo = new List<string>(); } sendingVertex.returnTo.Insert(0, name); //sendingVertex.returnTo = name; if (mv.shareWith != null) sendingVertex.shareWith = new HashSet<string>(mv.shareWith); else sendingVertex.shareWith = new HashSet<string>(); for (int j = 0; j < sendingTo.Count; j++) { sendingVertex.shareWith.Add(sendingTo[j]); } sendingVertex.shareWith.Add(name); if (!receivedStates[agentName].Contains(sendingVertex)) { receivedStates[agentName].Add(sendingVertex); Program.messages++; } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void SendVertexToInf2(MapsVertex mv, Action lastAction) { try { List<string> sendingTo = new List<string>(); foreach (string agentName in MapsPlanner.recoverActionEffect[name][lastAction.Name]) { if (mv.shareWith != null && mv.shareWith.Contains(agentName)) continue; sendingTo.Add(agentName); } for (int i = 0; i < sendingTo.Count; i++) { // if (lastAction==null || !MapsPlanner.actionMap[lastAction.Name].Contains(agentName)) { string agentName = sendingTo[i]; if (mv.returnTo != null && mv.returnTo.Contains(agentName)) continue; MapsPlanner.massagePreCounter++; Program.sendedStateCounter++; MapsVertex sendingVertex = new MapsVertex(mv); sendingVertex.fullCopy(mv); if (mv.returnTo != null) sendingVertex.returnTo = new List<string>(mv.returnTo); else { sendingVertex.returnTo = new List<string>(); } sendingVertex.returnTo.Insert(0, name); if (mv.shareWith != null) sendingVertex.shareWith = new HashSet<string>(mv.shareWith); else sendingVertex.shareWith = new HashSet<string>(); for (int j = 0; j < sendingTo.Count; j++) { sendingVertex.shareWith.Add(sendingTo[j]); } sendingVertex.shareWith.Add(name); if (!receivedStates[agentName].Contains(sendingVertex)) { receivedStates[agentName].Add(sendingVertex); Program.messages++; } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void SendVertex(MapsVertex mv, Action lastAction) { try { if (lastAction.isGoalAction) { SendVertexToAll(mv); return; } foreach (string agentName in MapsPlanner.actionMap[lastAction.Name]) { if (agentName.Equals(name)) continue; MapsPlanner.massageEffCounter++; mv.shareWith = MapsPlanner.actionMap[lastAction.Name]; Program.sendedStateCounter++; MapsVertex sendingVertex = new MapsVertex(mv); sendingVertex.fullCopy(mv); sendingVertex.shareWith = MapsPlanner.actionMap[lastAction.Name]; if (!openLists[agentName].Contains(sendingVertex)) { openLists[agentName].Add(sendingVertex); Program.messages++; } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void SendVertex(MapsVertex mv, string agentName) { try { MapsPlanner.massageEffCounter++; mv.shareWith = new HashSet<string>(); mv.shareWith.Add(name); mv.shareWith.Add(agentName); Program.sendedStateCounter++; MapsVertex sendingVertex = new MapsVertex(mv); sendingVertex.fullCopy(mv); sendingVertex.shareWith = new HashSet<string>(); sendingVertex.shareWith.Add(name); sendingVertex.shareWith.Add(agentName); //sendingVertex.isReceivedState = mv.isReceivedState; if (mv.returnTo.Count == 1) sendingVertex.returnTo = null; else { sendingVertex.returnTo = new List<string>(mv.returnTo); sendingVertex.returnTo.RemoveAt(0); } if (!openLists[agentName].Contains(sendingVertex)) { openLists[agentName].Add(sendingVertex); Program.messages++; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void SendVertexToAll(MapsVertex mv) { try { AddToAllSentStates(mv); foreach (string index in agentsNames) { if (!name.Equals(index)) { ++MapsPlanner.massageEffCounter; mv.shareWith = MapsPlanner.sendedToAllSign; ++Program.sendedStateCounter; MapsVertex mapsVertex = new MapsVertex(mv); mapsVertex.fullCopy(mv); if (Program.projectionVersion == Program.ProjectionVersion.Global || Program.projectionVersion == Program.ProjectionVersion.GlobalV2) { if (mv.isPreferable && (mv.relaxPlan.Count != 0 || mv.afterMe == null || !mv.afterMe.Equals(index))) mapsVertex.isPreferable = false; else MapsAgent.preferFlags[index] = true; } if (Program.projectionVersion == Program.ProjectionVersion.fullGlobal && (mv.isPreferable && mv.relaxPlan.Count > 0)) { if (!BuildAgents_II.mapActionNameToAgents[mv.relaxPlan[0]].Contains(index)) mapsVertex.isPreferable = false; else MapsAgent.preferFlags[index] = true; } mapsVertex.shareWith = MapsPlanner.sendedToAllSign; if (!openLists[index].Contains(mapsVertex)) { openLists[index].Add(mapsVertex); ++Program.messages; } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void SendVertexToAllAgentOnNextListUse(MapsVertex mv, bool sendingRealStartState) { try { // save the sent state as sent for the sender agent: AddToAllSentStates(mv); foreach (string index in agentsNames) { if (!name.Equals(index)) { ++MapsPlanner.massageEffCounter; mv.shareWith = MapsPlanner.sendedToAllSign; ++Program.sendedStateCounter; MapsVertex mapsVertex = new MapsVertex(mv); mapsVertex.fullCopy(mv); mapsVertex.senderAgent = this.name; mapsVertex.agent2iparentVertex = mv.agent2iparentVertex; if (Program.projectionVersion == Program.ProjectionVersion.Global || Program.projectionVersion == Program.ProjectionVersion.GlobalV2) { if (mv.isPreferable && (mv.relaxPlan.Count != 0 || mv.afterMe == null || !mv.afterMe.Equals(index))) mapsVertex.isPreferable = false; else if (mv.isPreferable) MapsAgent.preferFlags[index] = true; } else { if (Program.projectionVersion == Program.ProjectionVersion.fullGlobal && (mv.isPreferable && mv.relaxPlan.Count > 0)) { if (!BuildAgents_II.mapActionNameToAgents[mv.relaxPlan[0]].Contains(index)) mapsVertex.isPreferable = false; else if (mv.isPreferable) MapsAgent.preferFlags[index] = true; } else { if (mv.isPreferable) MapsAgent.preferFlags[index] = true; } } mapsVertex.shareWith = MapsPlanner.sendedToAllSign; if (!openLists[index].Contains(mapsVertex)) { MapsPlanner.nextGlobalOpenList[index].Add(mapsVertex); ++Program.messages; } mapsVertex.h_when_sent = mv.h; if (sendingRealStartState && MapsPlanner.tracesHandler.usesRealStartState()) { // we recieved the real start state, so we need to save it in this agent's trace. MapsPlanner.tracesHandler.publishRealStartState(MapsPlanner.name2mapsAgent[index], mapsVertex, -1, null); } else { // we recieved a regular state, save it in the trace. MapsPlanner.tracesHandler.RecieveState(mapsVertex, MapsPlanner.name2mapsAgent[index], mv, this); } // save the received state as received for the receiver agent: MapsPlanner.name2mapsAgent[index].AddToAllReceivedStates(mapsVertex); // iparent: HandleIParent(mapsVertex, MapsPlanner.name2mapsAgent[index]); if(mv == realStartStateVertex) { MapsPlanner.name2mapsAgent[index].realStartStateVertex = mapsVertex; } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void SendVertexToAllLockFirst(MapsVertex mv) { try { foreach (string agentName in agentsNames) { if (!name.Equals(agentName)) { MapsPlanner.massageEffCounter++; mv.shareWith = MapsPlanner.sendedToAllSign; Program.sendedStateCounter++; MapsVertex sendingVertex = new MapsVertex(mv); sendingVertex.fullCopy(mv); sendingVertex.shareWith = MapsPlanner.sendedToAllSign; // tmpMutex.WaitOne(); // globalMutex[agentName].WaitOne(); if (!openLists[agentName].Contains(sendingVertex)) { openLists[agentName].Add(sendingVertex); Program.messages++; } // tmpMutex.ReleaseMutex(); // globalMutex[agentName].ReleaseMutex(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public void relaxActions(List<Action> allActions, List<Action> macroActions) { for (int i = 0; i < macroActions.Count; i++) { if (macroActions[i] is MacroAction) { relaxActions(allActions, ((MacroAction)macroActions[i]).microActions); } else { allActions.Add(macroActions[i]); } } } public MapsVertex MergeVertex(MapsVertex fv, MapsVertex cv1, MapsVertex cv2) { return null; } public List<MapsVertex> FindBestFiveByLandmak(HashSet<MapsVertex> lvertex, int coun) { int count = coun; if (lvertex.Count < count) count = lvertex.Count; List<MapsVertex> ans = new List<MapsVertex>(); for (int i = 0; i < count; i++) { MapsVertex minVertex = null; foreach (MapsVertex mp in lvertex) { if (!ans.Contains(mp)) { minVertex = mp; break; } } foreach (MapsVertex v in lvertex) { if (MapsVertex.ComparerByLandmark(v, minVertex) == -1 && !ans.Contains(v)) { minVertex = v; } } ans.Add(minVertex); } //lvertex.Remove(minVertex); return ans; } public MapsVertex FindMinByLandmak(HashSet<MapsVertex> lvertex) { MapsVertex minVertex = lvertex.ElementAt(0); foreach (MapsVertex v in lvertex) { int res = MapsVertex.ComparerByLandmark(v, minVertex); // int res = 0; // if (v.h < minVertex.h) // res = -1; if (res == -1) { minVertex = v; } else { if (res == 0 && minVertex.returnTo != null && v.returnTo == null) { minVertex = v; } } } lvertex.Remove(minVertex); return minVertex; } public MapsVertex FindMinByLandmakNotDell(HashSet<MapsVertex> lvertex) { MapsVertex minVertex = lvertex.ElementAt(0); foreach (MapsVertex v in lvertex) { if (MapsVertex.ComparerByLandmark(v, minVertex) == -1) { minVertex = v; } } return minVertex; } public MapsVertex FindMinByFF(HashSet<MapsVertex> lvertex) { MapsVertex minVertex = lvertex.ElementAt(0); foreach (MapsVertex v in lvertex) { if (MapsVertex.ComparerByFF(v, minVertex) == -1) { minVertex = v; } } lvertex.Remove(minVertex); return minVertex; } List<Action> relaxtionPlan = null; Dictionary<GroundedPredicate, Action> PreferablesActions = null; Dictionary<GroundedPredicate, int> hspGraph = null; HashSet<GroundedPredicate> iCanGet = null; HashSet<Action> temporalActionsNontGet = null; HashSet<GroundedPredicate> publiciCanGet = null; int level = 1; public HashSet<GroundedPredicate> InitHspGraph(State state) { relaxtionPlan = new List<Action>(); PreferablesActions = new Dictionary<GroundedPredicate, Action>(); //StateInfo oldState = hashOfStates.ElementAt(index).Key; // Landmark l = ppLandmarks.GetMyLandmark(name); // bool otherAgentLandmarks=false; // if (exploreLandmarks == null) // { // exploreLandmarks = l; // otherAgentLandmarks=true; // } hspGraph = new Dictionary<GroundedPredicate, int>(); iCanGet = new HashSet<GroundedPredicate>(); temporalActionsNontGet = new HashSet<Action>(m_actions); HashSet<GroundedPredicate> addList = null; foreach (GroundedPredicate prop in state.Predicates) { iCanGet.Add(prop); hspGraph.Add(prop, 0); PreferablesActions.Add(prop, null); } bool flag2 = true; level = 1; // while (flag2) { flag2 = false; List<Action> tempActionList = new List<Action>(); addList = new HashSet<GroundedPredicate>(); foreach (Action act in temporalActionsNontGet) { if (Contains(iCanGet, act.HashPrecondition)) { tempActionList.Add(act); if (act.Effects != null) { foreach (GroundedPredicate addProp in act.HashEffects) { if (!iCanGet.Contains(addProp) & !addList.Contains(addProp)) { addList.Add(addProp); PreferablesActions.Add(addProp, act); //iCanGet.Add(addProp); flag2 = true; } } } } } foreach (GroundedPredicate addP in addList) { hspGraph.Add(addP, level); iCanGet.Add(addP); } foreach (Action action in tempActionList) { temporalActionsNontGet.Remove(action); } } publiciCanGet = new HashSet<GroundedPredicate>(); foreach (GroundedPredicate gp in iCanGet) { if (publicFacts.Contains(gp)) { publiciCanGet.Add(gp); } } return publiciCanGet; } public KeyValuePair<bool, HashSet<GroundedPredicate>> UpdateHspGraph(HashSet<GroundedPredicate> OtherCanGet, int level, out bool isLocalGoal) { foreach (GroundedPredicate gp in OtherCanGet) { if (!iCanGet.Contains(gp)) { iCanGet.Add(gp); } } HashSet<GroundedPredicate> addList = new HashSet<GroundedPredicate>(); bool flag2 = true; //while (flag2) { flag2 = false; List<Action> tempActionList = new List<Action>(); foreach (Action act in temporalActionsNontGet) { if (Contains(iCanGet, act.HashPrecondition)) { tempActionList.Add(act); if (act.Effects != null) { foreach (GroundedPredicate addProp in act.HashEffects) { if (!iCanGet.Contains(addProp) && !addList.Contains(addProp)) { addList.Add(addProp); // iCanGet.Add(addProp); PreferablesActions.Add(addProp, act); flag2 = true; } } } } } foreach (GroundedPredicate addP in addList) { hspGraph.Add(addP, level); iCanGet.Add(addP); } foreach (Action action in tempActionList) { temporalActionsNontGet.Remove(action); } } HashSet<GroundedPredicate> addingPublicPredicate = new HashSet<GroundedPredicate>(); foreach (GroundedPredicate gp in iCanGet) { if (publicFacts.Contains(gp)) { if (!publiciCanGet.Contains(gp)) { publiciCanGet.Add(gp); if (!OtherCanGet.Contains(gp)) { addingPublicPredicate.Add(gp); } } } } isLocalGoal = true; foreach (GroundedPredicate gp in goal) { if (!iCanGet.Contains(gp)) { isLocalGoal = false; break; } } return new KeyValuePair<bool, HashSet<GroundedPredicate>>(flag2, addingPublicPredicate); } public List<GroundedPredicate> GetPublicfactsGoals() { return goal; } List<GroundedPredicate> relaxGoals = null; HashSet<GroundedPredicate> AchievedFacts = null; public void InitRelaxtionPlan() { relaxGoals = new List<GroundedPredicate>(); //AllLocalGoals = new HashSet<GroundedPredicate>(goal); AchievedFacts = new HashSet<GroundedPredicate>(); relaxPlanPreconditions = new HashSet<GroundedPredicate>(); } public List<GroundedPredicate> UpDateRelaxtionPlan(HashSet<GroundedPredicate> publicGoals, out string flag) { List<GroundedPredicate> newPublicGoals = new List<GroundedPredicate>(); try { HashSet<GroundedPredicate> tmpLayerGoals = new HashSet<GroundedPredicate>(); for (int i = 0; i < relaxGoals.Count; i++) { GroundedPredicate gp = relaxGoals.ElementAt(i); if (AchievedFacts.Contains(gp)) { //relaxGoals.RemoveAt(i); //i--; continue; } if (PreferablesActions.ContainsKey(gp)) { // relaxGoals.RemoveAt(i); // i--; AchievedFacts.Add(gp); Action act = PreferablesActions[gp]; if (act != null) { relaxPlanPreconditions.Add(gp); if (!relaxtionPlan.Contains(act)) { relaxtionPlan.Add(act); foreach (GroundedPredicate pre in act.HashPrecondition) { if (!AchievedFacts.Contains(pre)) { tmpLayerGoals.Add(pre); } } } } } else { throw new Exception("bug"); } } for (int i = 0; i < publicGoals.Count; i++) { GroundedPredicate gp = publicGoals.ElementAt(i); if (AchievedFacts.Contains(gp)) { publicGoals.Remove(gp); i--; continue; } if (PreferablesActions.ContainsKey(gp)) { publicGoals.Remove(gp); i--; Action act = PreferablesActions[gp]; AchievedFacts.Add(gp); if (act != null) { relaxPlanPreconditions.Add(gp); if (!relaxtionPlan.Contains(act)) { relaxtionPlan.Add(act); foreach (GroundedPredicate pre in act.HashPrecondition) { if (!AchievedFacts.Contains(pre)) { tmpLayerGoals.Add(pre); } } } } } } if (tmpLayerGoals.Count > 0) flag = "continue"; else flag = "finsh"; for (int i = 0; i < tmpLayerGoals.Count; i++) { GroundedPredicate gp = tmpLayerGoals.ElementAt(i); if (AchievedFacts.Contains(gp)) { tmpLayerGoals.Remove(gp); i--; } else { if (publicFacts.Contains(gp)) { tmpLayerGoals.Remove(gp); i--; newPublicGoals.Add(gp); } } } relaxGoals = tmpLayerGoals.ToList(); } catch (Exception ex) { flag = "dd"; return null; } return newPublicGoals; } public int GetRelaxPlanSize() { return relaxtionPlan.Count; } HashSet<GroundedPredicate> relaxPlanPreconditions = null; public HashSet<GroundedPredicate> GetRelaxPlanPreconditions() { return relaxPlanPreconditions; } public List<Action> RegGrounding(State courrentState, List<Action> highLevelplan, out int actionCount) { // Console.WriteLine("\nPublic global plan found, searching for private plans"); actionCount = 0; List<Dictionary<CompoundFormula, string>> newPlan = new List<Dictionary<CompoundFormula, string>>(); List<KeyValuePair<string, CompoundFormula>> lplan = new List<KeyValuePair<string, CompoundFormula>>(); foreach (Action act in highLevelplan) { CompoundFormula effect = new CompoundFormula("and"); bool flag = false; foreach (GroundedPredicate gp in act.HashEffects) { if (publicFacts.Contains(gp)) { effect.AddOperand(gp); flag = true; } } if (flag) lplan.Add(new KeyValuePair<string, CompoundFormula>(act.agent, effect)); else actionCount = actionCount; } int count = 0; List<Action> finalPlan = new List<Action>(); int level = 0; CompoundFormula goalFormula = new CompoundFormula("and"); string agentName; foreach (KeyValuePair<string, CompoundFormula> eff in lplan) { agentName = eff.Key; goalFormula = new CompoundFormula(eff.Value); if (name.Equals(agentName)) { bool bUnsolvable = false; //ExternalPlanners externalPlanners = new ExternalPlanners(); //List<string> ffLplan = externalPlanners.Plan(true, false, domain, problem, courrentState, goalFormula,m_actions, 5 * 60 * 1000, out bUnsolvable); HSPHeuristic hsp = new HSPHeuristic(m_actions, goalFormula.GetAllPredicates().ToList(), false); ForwardSearchPlanner forwardSearch = new ForwardSearchPlanner(m_actions, hsp, 30); List<Action> path = forwardSearch.Plan(courrentState, goalFormula.GetAllPredicates().ToList()); List<string> ffLplan = null; if (path != null) { ffLplan = new List<string>(); foreach (Action act in path) { ffLplan.Add(act.Name); } } if (ffLplan != null) { List<string> todo = ffLplan; foreach (string act in todo) { actionCount++; State s = courrentState.ApplyII(domain.mapActionNameToAction[act]); if (s == null) throw new Exception(); courrentState = s; finalPlan.Add(domain.mapActionNameToAction[act]); } } else { Program.KillPlanners(); } } else { //actionCount++; courrentState = courrentState.ApplyEffect(goalFormula, publicFacts); } } return finalPlan; } public List<Action> RegGroundingFF(State courrentState, List<Action> highLevelplan, out int actionCount) { // Console.WriteLine("\nPublic global plan found, searching for private plans"); actionCount = 0; List<Dictionary<CompoundFormula, string>> newPlan = new List<Dictionary<CompoundFormula, string>>(); List<KeyValuePair<string, CompoundFormula>> lplan = new List<KeyValuePair<string, CompoundFormula>>(); foreach (Action act in highLevelplan) { CompoundFormula effect = new CompoundFormula("and"); bool flag = false; foreach (GroundedPredicate gp in act.HashEffects) { if (publicFacts.Contains(gp)) { effect.AddOperand(gp); flag = true; } } if (flag) lplan.Add(new KeyValuePair<string, CompoundFormula>(act.agent, effect)); else actionCount = actionCount; } int count = 0; List<Action> finalPlan = new List<Action>(); int level = 0; CompoundFormula goalFormula = new CompoundFormula("and"); string agentName; foreach (KeyValuePair<string, CompoundFormula> eff in lplan) { agentName = eff.Key; goalFormula = new CompoundFormula(eff.Value); if (name.Equals(agentName)) { bool bUnsolvable = false; ExternalPlanners externalPlanners = new ExternalPlanners(); List<string> ffLplan = externalPlanners.Plan(true, false, false, domain, problem, courrentState, goalFormula, m_actions, 5 * 60 * 1000, out bUnsolvable, null); if (ffLplan != null) { List<string> todo = ffLplan; foreach (string act in todo) { actionCount++; State s = courrentState.ApplyII(domain.mapActionNameToAction[act]); if (s == null) throw new Exception(); courrentState = s; finalPlan.Add(domain.mapActionNameToAction[act]); } } else { Program.KillPlanners(); } } else { //actionCount++; courrentState = courrentState.ApplyEffect(goalFormula, publicFacts); } } return finalPlan; } // } public List<Action> Grounding(int agentIndex, State courrentState, List<Action> highLevelplan, out int actionCount, out int allActionCount, out Dictionary<int, List<string>> groupPlan) { List<List<Action>> dellList = new List<List<Action>>(); State orginalState = courrentState; List<List<CompoundFormula>> effSets = new List<List<CompoundFormula>>(); groupPlan = new Dictionary<int, List<string>>(); List<KeyValuePair<string, CompoundFormula>> list1 = new List<KeyValuePair<string, CompoundFormula>>(); foreach (Action action in highLevelplan) { Program.cancellationTokenSource.Token.ThrowIfCancellationRequested(); CompoundFormula compoundFormula = new CompoundFormula("and"); bool flag = false; foreach (GroundedPredicate groundedPredicate in action.HashEffects) { if (publicFacts.Contains(groundedPredicate)) { compoundFormula.AddOperand((Predicate)groundedPredicate); flag = true; } } if (flag) { list1.Add(new KeyValuePair<string, CompoundFormula>(action.agent, compoundFormula)); List<CompoundFormula> l = new List<CompoundFormula>(); l.Add(compoundFormula); effSets.Add(l); } } actionCount = 0; allActionCount = 0; List<Dictionary<CompoundFormula, string>> list2 = new List<Dictionary<CompoundFormula, string>>(); List<Action> list3 = new List<Action>(); int index1 = -1; State prev = null; Action prevAction = null; int prevActionCount = 0; int prevAllActionCount = 0; bool twoPublic = false; int countAction = 0; for (int i = 0; i < list1.Count; i++) { Program.cancellationTokenSource.Token.ThrowIfCancellationRequested(); dellList.Add(new List<Action>()); KeyValuePair<string, CompoundFormula> keyValuePair = list1[i]; ++index1; List<Action> privateAndMore = new List<Action>(privateActions); //privateAndMore.Add(highLevelplan[countAction]); //countAction++; CompoundFormula compoundFormula = keyValuePair.Value; if (name.Equals(keyValuePair.Key)) { foreach (Action pubAct in publicActions) { foreach (CompoundFormula cm in effSets[i]) { bool con = true; foreach (GroundedPredicate gp in cm.GetAllPredicates()) if (!pubAct.HashEffects.Contains(gp)) con = false; if (con) privateAndMore.Add(pubAct); } } foreach (Action dellAct in dellList[i]) { privateAndMore.Remove(dellAct); } bool isPublic = false; foreach (Action act in privateAndMore) { if (publicActions.Contains(act)) { isPublic = true; break; } } if (!isPublic) { return null; } List<Action> list4 = new ForwardSearchPlanner(privateAndMore, new HSPHeuristic(privateAndMore, Enumerable.ToList<Predicate>((IEnumerable<Predicate>)compoundFormula.GetAllPredicates()), false), 30).Plan(courrentState, Enumerable.ToList<Predicate>((IEnumerable<Predicate>)compoundFormula.GetAllPredicates())); List<string> list5 = (List<string>)null; if (list4 != null) { list5 = new List<string>(); foreach (Action action in list4) list5.Add(action.Name); prevAction = list4.Last(); prevActionCount = actionCount; prevAllActionCount = allActionCount; } else { // return GroundingByActions(agentIndex, orginalState, highLevelplan, out actionCount, out allActionCount, out groupPlan); if (prev != null) { // try to force other path for the last planning iteration (i-1) dellList[i - 1].Add(prevAction); courrentState = prev; actionCount = prevActionCount; allActionCount = prevAllActionCount; i--; i--; index1--; index1--; // throw new Exception("need to chack this rows"); } else { return null; } } if (list5 != null) { groupPlan[index1] = new List<string>((IEnumerable<string>)list5); foreach (string index2 in list5) { actionCount = actionCount + 1; prev = courrentState; allActionCount = allActionCount + 1; State state = courrentState.ApplyII(domain.mapActionNameToAction[index2]); if (state == null) throw new Exception(); courrentState = state; list3.Add(domain.mapActionNameToAction[index2]); } } // else // Program.KillPlanners(); } else { allActionCount = allActionCount + 1; courrentState = courrentState.ApplyEffect((Formula)compoundFormula, publicFacts); } } groupPlan[highLevelplan.Count + agentIndex] = new List<string>(); return list3; CompoundFormula compoundFormula1 = new CompoundFormula("and"); foreach (GroundedPredicate groundedPredicate in goal) compoundFormula1.AddOperand((Predicate)groundedPredicate); if (compoundFormula1.Operands.Count > 0) { bool bUnsolvable; List<string> list4 = new ExternalPlanners().Plan(true, false, false, domain, problem, courrentState, (Formula)compoundFormula1, m_actions, 300000, out bUnsolvable, null); if (list4 != null) { groupPlan[highLevelplan.Count + agentIndex] = new List<string>((IEnumerable<string>)list4); foreach (string index2 in list4) { actionCount = actionCount + 1; allActionCount = allActionCount + 1; State state = courrentState.ApplyII(domain.mapActionNameToAction[index2]); if (state == null) throw new Exception(); courrentState = state; list3.Add(domain.mapActionNameToAction[index2]); } } else Program.KillPlanners(); } else groupPlan[highLevelplan.Count + agentIndex] = new List<string>(); return list3; } public List<Action> GroundingByActions(int agentIndex, State courrentState, List<Action> highLevelplan, out int actionCount, out int allActionCount, out Dictionary<int, List<string>> groupPlan) { groupPlan = new Dictionary<int, List<string>>(); List<KeyValuePair<string, CompoundFormula>> list1 = new List<KeyValuePair<string, CompoundFormula>>(); foreach (Action action in highLevelplan) { CompoundFormula compoundFormula = new CompoundFormula("and"); bool flag = false; foreach (GroundedPredicate groundedPredicate in action.HashPrecondition) { compoundFormula.AddOperand((Predicate)groundedPredicate); flag = true; } if (flag) list1.Add(new KeyValuePair<string, CompoundFormula>(action.agent, compoundFormula)); } actionCount = 0; allActionCount = 0; List<Dictionary<CompoundFormula, string>> list2 = new List<Dictionary<CompoundFormula, string>>(); List<Action> list3 = new List<Action>(); int index1 = -1; int countAction = 0; foreach (KeyValuePair<string, CompoundFormula> keyValuePair in list1) { ++index1; List<Action> privateAndMore = new List<Action>(privateActions); CompoundFormula compoundFormula = keyValuePair.Value; if (name.Equals(keyValuePair.Key)) { List<Action> list4 = new ForwardSearchPlanner(privateAndMore, new HSPHeuristic(privateAndMore, Enumerable.ToList<Predicate>((IEnumerable<Predicate>)compoundFormula.GetAllPredicates()), false), 30).Plan(courrentState, Enumerable.ToList<Predicate>((IEnumerable<Predicate>)compoundFormula.GetAllPredicates())); list4.Add(highLevelplan[index1]); List<string> list5 = (List<string>)null; if (list4 != null) { list5 = new List<string>(); foreach (Action action in list4) list5.Add(action.Name); } if (list5 != null) { groupPlan[index1] = new List<string>((IEnumerable<string>)list5); foreach (string index2 in list5) { actionCount = actionCount + 1; allActionCount = allActionCount + 1; State state = courrentState.ApplyII(domain.mapActionNameToAction[index2]); if (state == null) throw new Exception(); courrentState = state; list3.Add(domain.mapActionNameToAction[index2]); } } else Program.KillPlanners(); } else { allActionCount = allActionCount + 1; courrentState = courrentState.ApplyEffect((Formula)highLevelplan[index1].Effects, publicFacts); } } groupPlan[highLevelplan.Count + agentIndex] = new List<string>(); return list3; CompoundFormula compoundFormula1 = new CompoundFormula("and"); foreach (GroundedPredicate groundedPredicate in goal) compoundFormula1.AddOperand((Predicate)groundedPredicate); if (compoundFormula1.Operands.Count > 0) { bool bUnsolvable; List<string> list4 = new ExternalPlanners().Plan(true, false, false, domain, problem, courrentState, (Formula)compoundFormula1, m_actions, 300000, out bUnsolvable, null); if (list4 != null) { groupPlan[highLevelplan.Count + agentIndex] = new List<string>((IEnumerable<string>)list4); foreach (string index2 in list4) { actionCount = actionCount + 1; allActionCount = allActionCount + 1; State state = courrentState.ApplyII(domain.mapActionNameToAction[index2]); if (state == null) throw new Exception(); courrentState = state; list3.Add(domain.mapActionNameToAction[index2]); } } else Program.KillPlanners(); } else groupPlan[highLevelplan.Count + agentIndex] = new List<string>(); return list3; } public List<Action> GroundingFF(int agentIndex, State courrentState, List<Action> highLevelplan, out int actionCount, out int allActionCount, Dictionary<int, List<string>> groupPlan) { List<KeyValuePair<string, CompoundFormula>> list1 = new List<KeyValuePair<string, CompoundFormula>>(); foreach (Action action in highLevelplan) { CompoundFormula compoundFormula = new CompoundFormula("and"); bool flag = false; foreach (GroundedPredicate groundedPredicate in action.HashEffects) { if (publicFacts.Contains(groundedPredicate)) { compoundFormula.AddOperand((Predicate)groundedPredicate); flag = true; } } if (flag) list1.Add(new KeyValuePair<string, CompoundFormula>(action.agent, compoundFormula)); } actionCount = 0; allActionCount = 0; List<Dictionary<CompoundFormula, string>> list2 = new List<Dictionary<CompoundFormula, string>>(); List<Action> list3 = new List<Action>(); int index1 = -1; foreach (KeyValuePair<string, CompoundFormula> keyValuePair in list1) { ++index1; CompoundFormula compoundFormula = keyValuePair.Value; if (name.Equals(keyValuePair.Key)) { bool bUnsolvable = false; List<string> list4 = new ExternalPlanners().Plan(true, false, false, domain, problem, courrentState, (Formula)compoundFormula, m_actions, 300000, out bUnsolvable, null); if (list4 != null) { groupPlan[index1] = new List<string>((IEnumerable<string>)list4); foreach (string index2 in list4) { actionCount = actionCount + 1; allActionCount = allActionCount + 1; State state = courrentState.ApplyII(domain.mapActionNameToAction[index2]); if (state == null) throw new Exception(); courrentState = state; list3.Add(domain.mapActionNameToAction[index2]); } } else Program.KillPlanners(); } else { allActionCount = allActionCount + 1; courrentState = courrentState.ApplyEffect((Formula)compoundFormula, publicFacts); } } CompoundFormula compoundFormula1 = new CompoundFormula("and"); foreach (GroundedPredicate groundedPredicate in goal) compoundFormula1.AddOperand((Predicate)groundedPredicate); if (compoundFormula1.Operands.Count > 0) { bool bUnsolvable; List<string> list4 = new ExternalPlanners().Plan(true, false, false, domain, problem, courrentState, (Formula)compoundFormula1, m_actions, 300000, out bUnsolvable, null); if (list4 != null) { groupPlan[highLevelplan.Count + agentIndex] = new List<string>((IEnumerable<string>)list4); foreach (string index2 in list4) { actionCount = actionCount + 1; allActionCount = allActionCount + 1; State state = courrentState.ApplyII(domain.mapActionNameToAction[index2]); if (state == null) throw new Exception(); courrentState = state; list3.Add(domain.mapActionNameToAction[index2]); } } else Program.KillPlanners(); } else groupPlan[highLevelplan.Count + agentIndex] = new List<string>(); return list3; } public static void InitMutex(List<MapsAgent> agents) { MapsAgent.heursticCalcultionMutex = new Mutex(); MapsAgent.massageListMutex = new Dictionary<string, Mutex>(); MapsAgent.goalChackMutex = new Mutex(); MapsAgent.preferFlags = new Dictionary<string, bool>(); foreach (MapsAgent mapsAgent in agents) { MapsAgent.massageListMutex.Add(mapsAgent.name, new Mutex()); MapsAgent.preferFlags.Add(mapsAgent.name, false); } } } }
namespace DpiConverter.Data { internal class TargetRecord { private readonly string targetIndex; private readonly double targetHeight; public TargetRecord(string targetIndex, double targetHeight) { this.targetIndex = targetIndex; this.targetHeight = targetHeight; } public double TargetHeight { get { return this.targetHeight; } } public string TargetIndex { get { return this.targetIndex; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace tpjavacsharp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label3_Click(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { ServiceReference1.ServiceCercleClient objCom = new ServiceReference1.ServiceCercleClient(); ServiceReference1.cercle objCercle = new ServiceReference1.cercle(); objCercle.rayon = Convert.ToDouble( textBox1.Text); if(comboBox1.SelectedItem.ToString().Equals("Perimetre")){ MessageBox.Show(" le perimetre d'un cercle de rayon :"+objCercle.rayon+" est : "+ objCom.CalculerPerimetre(objCercle).ToString()); } if (comboBox1.SelectedItem.ToString().Equals("Surface")) { MessageBox.Show("la surface d'un cercle de rayon :"+objCercle.rayon +"est : "+objCom.CalculerSurface(objCercle).ToString()); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Zealous.Models; namespace Zealous.Controllers { public class EquipmentsController : Controller { private ZealousContext db = new ZealousContext(); const string SessionEquipCart = "equipCart"; // GET: Equipments public ActionResult Index() { return View(db.Equipments.ToList()); } [HttpGet] public ActionResult Book() { var equips = db.Equipments.OrderBy(x => x.EquipmentName).ToList(); var bookedIds = Session[SessionEquipCart] as List<int>; FillBooking(equips, bookedIds); return View(equips); } private static void FillBooking(List<Equipment> equips, List<int> bookedIds) { if (bookedIds != null) { foreach (var e in equips) { e.IsBooked = bookedIds.Contains(e.Id); } } } [HttpGet] public ActionResult BookOne(int equipId) { var bookedIds = Session[SessionEquipCart] as List<int>; if (bookedIds != null) { if (!bookedIds.Contains(equipId)) { bookedIds.Add(equipId); } } else { bookedIds = new List<int>() { equipId }; Session[SessionEquipCart] = bookedIds; } var equips = db.Equipments.OrderBy(x => x.EquipmentName).ToList(); FillBooking(equips, bookedIds); ViewBag.EquipId = equipId; return View("Book", equips); } [HttpGet] public ActionResult RemoveBooking(int equipId) { var bookedIds = Session[SessionEquipCart] as List<int>; if (bookedIds != null) bookedIds.Remove(equipId); var equips = db.Equipments.OrderBy(x => x.EquipmentName).ToList(); FillBooking(equips, bookedIds); ViewBag.EquipId = equipId; return View("Book", equips); } // GET: Equipments/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Equipment equipment = db.Equipments.Find(id); if (equipment == null) { return HttpNotFound(); } return View(equipment); } // GET: Equipments/Create public ActionResult Create() { return View(); } // POST: Equipments/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,EquipmentName,EquipmentDetail")] Equipment equipment) { if (ModelState.IsValid) { db.Equipments.Add(equipment); db.SaveChanges(); return RedirectToAction("Index"); } return View(equipment); } // GET: Equipments/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Equipment equipment = db.Equipments.Find(id); if (equipment == null) { return HttpNotFound(); } return View(equipment); } // POST: Equipments/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,EquipmentName,EquipmentDetail")] Equipment equipment) { if (ModelState.IsValid) { db.Entry(equipment).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(equipment); } // GET: Equipments/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Equipment equipment = db.Equipments.Find(id); if (equipment == null) { return HttpNotFound(); } return View(equipment); } // POST: Equipments/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Equipment equipment = db.Equipments.Find(id); db.Equipments.Remove(equipment); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using CsvUploader.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace CsvUploader.Pages.Internal { /// <summary> /// The page model class for show file view. /// </summary> [Authorize] public class ShowFileModel : PageModel { public IOrderedEnumerable<SupplierInfoModel> Suppliers { get; set; } /// <summary> /// The queryable items of supplier. /// </summary> public IOrderedEnumerable<ItemInfoModel> Items { get; set; } /// <summary> /// The full name of uploaded file. /// </summary> public string FullFileName { get; set; } /// <summary> /// The supplier identifier for items. /// </summary> public string SupplierId { get; set; } /// <summary> /// The sort parameter for identifier of item. /// </summary> public string IdSort { get; set; } /// <summary> /// The sort parameter for name. /// </summary> public string NameSort { get; set; } /// <summary> /// boolean, if specified file is supplier file. /// </summary> public bool IsSupplierFile; /// <summary> /// The Onget method. /// </summary> public void OnGet(string fileName, string sortOrder) { FullFileName = fileName; var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot", "uploads", fileName); try { LoadCsvFile(fileName, path, sortOrder); } catch (Exception e) { ViewData["Feedback"] = "Beim Laden der Datei ist ein Fehler aufgetreten."; Console.WriteLine(e); } } private void LoadCsvFile(string fileName, string filePath, string sortOrder) { try { var lines = System.IO.File.ReadAllLines(filePath, Encoding.Default).ToList(); var firstLine = lines.FirstOrDefault(); if (CheckIfIsSupplierFile(firstLine)) { IsSupplierFile = true; var supplierList = ReadSupplierData(lines); SetOrderedSuppliers(supplierList, sortOrder); } if (CheckIfIsItemFile(firstLine)) { var itemList = ReadItemData(fileName, lines); SetOrderedItems(itemList, sortOrder); } } catch (Exception e) { Console.WriteLine(e); throw; } } private void SetOrderedItems(IEnumerable<ItemInfoModel> itemList, string sortOrder) { IdSort = string.IsNullOrEmpty(sortOrder) ? "id_desc" : string.Empty; NameSort = string.IsNullOrEmpty(sortOrder) || sortOrder.Equals("name") ? "name_desc" : "name"; switch (sortOrder) { case "id_desc": Items = itemList.OrderByDescending(s => s.ItemId); break; case "name": Items = itemList.OrderBy(s => s.Name); break; case "name_desc": Items = itemList.OrderByDescending(s => s.Name); break; default: Items = itemList.OrderBy(s => s.ItemId); break; } } private void SetOrderedSuppliers(IEnumerable<SupplierInfoModel> supplierList, string sortOrder) { IdSort = string.IsNullOrEmpty(sortOrder) ? "id_desc" : string.Empty; NameSort = string.IsNullOrEmpty(sortOrder) || sortOrder.Equals("name") ? "name_desc" : "name"; switch (sortOrder) { case "id_desc": Suppliers = supplierList.OrderByDescending(s => s.SupplierId); break; case "name": Suppliers = supplierList.OrderBy(s => s.Name); break; case "name_desc": Suppliers = supplierList.OrderByDescending(s => s.Name); break; default: Suppliers = supplierList.OrderBy(s => s.SupplierId); break; } } private bool CheckIfIsSupplierFile(string firstLine) { if (firstLine == null) return false; var expectedColumns = $"Lieferantennummer,Lieferantenname,Straße,PLZ,Ort"; return firstLine.Equals(expectedColumns); } private bool CheckIfIsItemFile(string firstLine) { if (firstLine == null) return false; var expectedColums = $"Artikelnummer,Artikelbezeichnung"; return firstLine.Equals(expectedColums); } private IEnumerable<SupplierInfoModel> ReadSupplierData(List<string> lines) { var supplierList = new List<SupplierInfoModel>(); //first line contains no data. lines.Remove(lines.First()); foreach (var line in lines) { var parts = line.Split(','); supplierList.Add(ReadSupplier(parts)); } return supplierList; } private SupplierInfoModel ReadSupplier(string[] parts) { if (parts.Length != 5) throw new ArgumentException(); return new SupplierInfoModel { SupplierId = parts[0], Name = parts[1], Street = parts[2], ZipCode = parts[3], City = parts[4] }; } private IEnumerable<ItemInfoModel> ReadItemData(string supplierId, ICollection<string> lines) { var itemList = new List<ItemInfoModel>(); //first line contains no data. lines.Remove(lines.First()); foreach (var line in lines) { var parts = line.Split(','); if (parts.Length != 2) continue; itemList.Add(ReadItem(parts)); } return itemList; } private ItemInfoModel ReadItem(string[] parts) { if (parts.Length != 2) throw new ArgumentException(); return new ItemInfoModel() { ItemId = parts[0], Name = parts[1] }; } } }
using FluentAssertions; using Xunit; namespace Health.Direct.Policy.Tests { public class PolicyValueFactory_GetInstanceTest { [Fact] public void testGetInstance_assertValue() { IPolicyValue<int> value = PolicyValueFactory.GetInstance(12345); value.GetPolicyValue().Should().Be(12345); value.Should().Be(PolicyValueFactory.GetInstance(12345)); IPolicyValue<string> value2 = PolicyValueFactory.GetInstance("12345"); value2.GetPolicyValue().Should().Be("12345"); value2.Should().Be(PolicyValueFactory.GetInstance("12345")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary4._5 { public abstract class AbstractClass1 { public int Prop1 { get; set; } public abstract void animalSound(); public void sleep() { Console.WriteLine("Zzz"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using QUnit; using System.Text.RegularExpressions; namespace Linq.TestScript { [TestFixture] public class ForDebugTests { [ExpandParams] delegate void ConsoleLogDelegate(params object[] messages); [ScriptAlias("console.log"), IntrinsicProperty] static ConsoleLogDelegate ConsoleLog { get; set; } private string WithRedirectedConsoleLog(Action a) { var old = ConsoleLog; try { var sb = new StringBuilder(); ConsoleLog = args => sb.Append(args.Join(",") + "|"); a(); return sb.ToString(); } finally { ConsoleLog = old; } } [Test] public void TraceWithoutArgumentsWorksForArray() { string s = WithRedirectedConsoleLog(() => new[] { 1, 2, 3, 4, 5 }.Trace().Force()); Assert.AreEqual(s, "Trace,1|Trace,2|Trace,3|Trace,4|Trace,5|"); } [Test] public void TraceWithMessageWorksForArray() { string s = WithRedirectedConsoleLog(() => new[] { 1, 2, 3, 4, 5 }.Trace("X").Force()); Assert.AreEqual(s, "X,1|X,2|X,3|X,4|X,5|"); } [Test] public void TraceWithMessageAndSelectorWorksForArray() { string s = WithRedirectedConsoleLog(() => new[] { 1, 2, 3, 4, 5 }.Trace("X", i => (i * 2).ToString()).Force()); Assert.AreEqual(s, "X,2|X,4|X,6|X,8|X,10|"); } [Test] public void TraceWithoutArgumentsWorksForLinqJSEnumerable() { string s = WithRedirectedConsoleLog(() => Enumerable.Range(1, 10).Trace().Force()); Assert.AreEqual(s, "Trace,1|Trace,2|Trace,3|Trace,4|Trace,5|Trace,6|Trace,7|Trace,8|Trace,9|Trace,10|"); } [Test] public void TraceWithMessageWorksForLinqJSEnumerable() { string s = WithRedirectedConsoleLog(() => Enumerable.Range(1, 10).Trace("X").Force()); Assert.AreEqual(s, "X,1|X,2|X,3|X,4|X,5|X,6|X,7|X,8|X,9|X,10|"); } [Test] public void TraceWithMessageAndSelectorWorksForLinqJSEnumerable() { string s = WithRedirectedConsoleLog(() => Enumerable.Range(1, 10).Trace("X", i => (i * 2).ToString()).Force()); Assert.AreEqual(s, "X,2|X,4|X,6|X,8|X,10|X,12|X,14|X,16|X,18|X,20|"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MsTesting.Test { public class TestingWithMs { } }
using Harmony; using RoR2.Mods; using RoR2; using System; using UnityEngine; using System.Reflection; using System.IO; namespace FireNerf { public class FireNerf { [ModEntry("Fire Nerf", "1.0.0", "Meepen")] public static void Init() { var harmony = HarmonyInstance.Create("dev.meepen.fire-nerf"); harmony.Patch(typeof(DotController).GetMethod("InflictDot", BindingFlags.Static | BindingFlags.Public), new HarmonyMethod(typeof(FirePatch).GetMethod("Prefix", BindingFlags.NonPublic | BindingFlags.Static))); } } public class FirePatch { static void Prefix(GameObject victimObject, GameObject attackerObject, DotController.DotIndex dotIndex, ref float duration, ref float damageMultiplier) { if (dotIndex == DotController.DotIndex.Burn) { damageMultiplier /= 5; duration /= 3; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UploadParser { public class ExcelFile { public string fileName; public string[] sheetName; public string[][][] sheetData; // x= sheet index, y= row number, z= cell value public ExcelFile() { } //Parameterized Constructor public ExcelFile(string filename, int numSheets) { fileName = filename; sheetName = new string[numSheets]; sheetData = new string[numSheets][][]; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class StaticObjects : MonoBehaviour { public static Player Player { get; set; } public static Camera PlayerCamera { get; set; } }
using Netfilmes.Business.Entidades; using Netfilmes.Business.Servicos.Interfaces; using Netfilmes.Repository.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Netfilmes.Business.Servicos.Classes { public class LocacaoService : ILocacaoService { private readonly ILocacaoDAO _locacaoDAO; private readonly IFilmeDAO _filmeDAO; // Esse construtor recebe as dependencias da classe (ponto de injeção) public LocacaoService(ILocacaoDAO locacaoDAO, IFilmeDAO filmeDAO) { _locacaoDAO = locacaoDAO; _filmeDAO = filmeDAO; } // Cadastra uma nova locação e faz a ligação dos filmes com a mesma public bool Cadastrar(Locacao locacao, List<int> filmesId) { bool sucesso = false; try { // Cadastra a locação var locacaoId = _locacaoDAO.Cadastrar(locacao); // Verifica se o cadastro foi realizado, analisando o Id gerado if (locacaoId > 0) { // Percorre a lista de Ids dos filmes selecionados pelo usuario foreach (var id in filmesId) { // Obtem cada filme da locação usando o seu Id var filmeCadastrado = _filmeDAO.ConsultarPorId(id); // Faz a ligação da locação cadastrada com o filme ligado a ela filmeCadastrado.LocacaoId = locacaoId; // Atualiza o filme cadastro, fazendo a ligação com a locação no banco sucesso = _filmeDAO.Cadastrar(filmeCadastrado); } } } catch (Exception e) { throw e; } return sucesso; } // Lista todas as locações public List<Locacao> ListarTodos() { try { return _locacaoDAO.ListarTodos(); } catch (Exception e) { throw e; } } // Termina o relacionamento dos filmes selecionados com a locacao public bool Desalocar(List<int> filmesId) { bool sucesso = false; try { // Percorre a lista de Ids dos filmes selecionados pelo usuario foreach (var id in filmesId) { // Obtem cada filme da locação usando o seu Id var filmeLocado = _filmeDAO.ConsultarPorId(id); // Termina o relacionamento do filme com locacao filmeLocado.LocacaoId = null; // Atualiza o filme no banco de dados sucesso = _filmeDAO.Cadastrar(filmeLocado); } } catch (Exception e) { throw e; } return sucesso; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Text.RegularExpressions; namespace e_Sports { public partial class WebForm2 : System.Web.UI.Page { string con = "Data Source=.;Initial Catalog =tournament;User Id=mr_maverick;Password=sql@server"; protected void Page_Load(object sender, EventArgs e) { } protected void Signup_Click(object sender, EventArgs e) { try { if (IsValidate()) { SqlConnection db = new SqlConnection(con); if (db.State == ConnectionState.Closed) { db.Open(); } string check = "Select count(*) from tbl_registration where email like '" + txtEmail.Text + "'"; SqlCommand ch = new SqlCommand(check, db); Int32 k = (Int32)ch.ExecuteScalar(); if (k != 0) { Response.Write("<script> alert('Email Already Registered !'); </script>"); } else { string insert = "insert into tbl_registration(rtype,fullname,phone,email,pass) values('" + type.SelectedValue + "','" + txtName.Text + "','" + txtPhone.Text + "','" + txtEmail.Text + "','" + txtPass.Text + "')"; SqlCommand cmd = new SqlCommand(insert, db); int m = cmd.ExecuteNonQuery(); if (m == 0) { Response.Write("<script> alert('Registration Fail !'); </script>"); } else { db.Close(); Response.Write("<script> alert('Registration Successful !'); </script>"); Response.Write("<script> window.location.href='homepage.aspx'; </script>"); } } } } catch(Exception ex) { Response.Write("<script> alert('Error:"+ ex +"'); </Script>"); } } protected bool IsValidate() { if (IsTypeValid() && IsNameValid() && IsPhoneValid() && IsEmailValid() && IsPassValid() && IsConfirmValid()) return true; else return false; } protected bool IsTypeValid() { if (type.SelectedValue == "Player" || type.SelectedValue == "Organizer") return true; else { Response.Write("<script> alert('Please Select valid usertype !'); </Script>"); return false; } } protected bool IsNameValid() { if (Regex.IsMatch(txtName.Text, @"^[a-zA-Z'.\s]{1,50}")) return true; else { Response.Write("<script> alert('Please Enter a Valid Name !'); </script>"); return false; } } protected bool IsPhoneValid() { if (Regex.IsMatch(txtPhone.Text, @"^[0-9]{10}")) return true; else { Response.Write("<script> alert('Please Enter a Valid Phone Number !'); </script>"); return false; } } protected bool IsEmailValid() { if (Regex.IsMatch(txtEmail.Text, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")) return true; else { Response.Write("<script> alert('Please Enter a Valid email !'); </script>"); return false; } } protected bool IsPassValid() { if (Regex.IsMatch(txtPass.Text, @"(?=^.{8,10}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{:;'?/>.<,])(?!.*\s).*$")) return true; else { Response.Write("<script> alert('Please Enter a Valid Password !'); </script>"); return false; } } protected bool IsConfirmValid() { if (! txtPass.Text.ToString().Equals(txtConfirm.Text.ToString())) { Response.Write("<script> alert('Password not Matched !'); </script>"); return false; } else { return true; } } } }
using System; using System.Collections.Generic; using UnityEngine; namespace HT.Framework { /// <summary> /// YieldInstruction创建者 /// </summary> public static class YieldInstructioner { private static WaitForEndOfFrame _waitForEndOfFrame = new WaitForEndOfFrame(); private static WaitForFixedUpdate _waitForFixedUpdate = new WaitForFixedUpdate(); private static Dictionary<string, WaitForSeconds> _waitForSeconds = new Dictionary<string, WaitForSeconds>(); private static Dictionary<string, WaitForSecondsRealtime> _waitForSecondsRealtime = new Dictionary<string, WaitForSecondsRealtime>(); /// <summary> /// 获取WaitForEndOfFrame对象 /// </summary> /// <returns>WaitForEndOfFrame对象</returns> public static WaitForEndOfFrame GetWaitForEndOfFrame() { return _waitForEndOfFrame; } /// <summary> /// 获取WaitForFixedUpdate对象 /// </summary> /// <returns>WaitForFixedUpdate对象</returns> public static WaitForFixedUpdate GetWaitForFixedUpdate() { return _waitForFixedUpdate; } /// <summary> /// 获取WaitForSeconds对象 /// </summary> /// <param name="second">等待的秒数</param> /// <returns>WaitForSeconds对象</returns> public static WaitForSeconds GetWaitForSeconds(float second) { string secondStr = second.ToString("F2"); if (!_waitForSeconds.ContainsKey(secondStr)) { _waitForSeconds.Add(secondStr, new WaitForSeconds(second)); } return _waitForSeconds[secondStr]; } /// <summary> /// 获取WaitForSecondsRealtime对象 /// </summary> /// <param name="second">等待的秒数</param> /// <returns>WaitForSecondsRealtime对象</returns> public static WaitForSecondsRealtime GetWaitForSecondsRealtime(float second) { string secondStr = second.ToString("F2"); if (!_waitForSecondsRealtime.ContainsKey(secondStr)) { _waitForSecondsRealtime.Add(secondStr, new WaitForSecondsRealtime(second)); } return _waitForSecondsRealtime[secondStr]; } /// <summary> /// 获取WaitUntil对象 /// </summary> /// <param name="predicate">判断的委托</param> /// <returns>WaitUntil对象</returns> public static WaitUntil GetWaitUntil(Func<bool> predicate) { return new WaitUntil(predicate); } /// <summary> /// 获取WaitWhile对象 /// </summary> /// <param name="predicate">判断的委托</param> /// <returns>WaitWhile对象</returns> public static WaitWhile GetWaitWhile(Func<bool> predicate) { return new WaitWhile(predicate); } } }
using Frostbyte.Entities.Enums; namespace Frostbyte.Entities.Packets { public sealed class PlayPacket : PlayerPacket { public string Hash { get; set; } public int StartTime { get; set; } public int EndTime { get; set; } public bool ShouldReplace { get; set; } public PlayPacket(ulong guildId) : base(guildId, OperationType.Play) { } } }
namespace SatNav { public class Edge { public Edge(Node start, Node end) { Start = start; End = end; } public Node Start { get; } public Node End { get; } public decimal Length => TapeMeasure.GetDistanceBetweenPoints(Start.X, End.X, Start.Y, End.Y); public string Name => Start.Name + End.Name; } }
using Serenity; using Serenity.Data; using Serenity.Services; using System; using System.Data; using MyRequest = Serenity.Services.DeleteRequest; using MyResponse = Serenity.Services.DeleteResponse; using MyRow = ARLink.Default.EmployeeSalaryRow; namespace ARLink.Default { public interface IEmployeeSalaryDeleteHandler : IDeleteHandler<MyRow, MyRequest, MyResponse> {} public class EmployeeSalaryDeleteHandler : DeleteRequestHandler<MyRow, MyRequest, MyResponse>, IEmployeeSalaryDeleteHandler { public EmployeeSalaryDeleteHandler(IRequestContext context) : base(context) { } } }
using System; namespace NopSolutions.NopCommerce.DataAccess.Orders { /// <summary> /// Represents a shopping cart item /// </summary> public partial class DBViewedItem : BaseDBEntity { #region Ctor /// <summary> /// Creates a new instance of DBShoppingCartItem class /// </summary> public DBViewedItem() { } #endregion #region Properties /// <summary> /// Gets or sets the viewed cart item identifier /// </summary> public int ViewedItemID { get; set; } /// <summary> /// Gets or sets the customer session identifier /// </summary> public Guid CustomerSessionGUID { get; set; } /// <summary> /// Gets or sets the product variant identifier /// </summary> public int ProductVariantID { get; set; } /// <summary> /// Gets or sets the date and time of instance creation /// </summary> public DateTime CreatedOn { get; set; } #endregion } }
using REQFINFO.Business; using REQFINFO.Domain; using REQFINFO.Business.Interfaces; using REQFINFO.Website.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using REQFINFO.Utility; namespace REQFINFO.Website.Controllers { public class SiteController : Controller { private IUserBusiness userBusiness; public SiteController(IUserBusiness _userBusiness) { userBusiness = _userBusiness; } // // GET: /Site/ public ActionResult Index() { return View(); } // // GET: /Site/login public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] [ValidateInput(true)] [AllowAnonymous] public ActionResult Login(LoginVM LoginModel) { UserModel userModel = userBusiness.ValidateUser(LoginModel.EmailAddress, LoginModel.Password); if (userModel.Email != null) { SessionManagement.LoggedInUser.IDUser = userModel.IDUser; SessionManagement.LoggedInUser.IDCompany = userModel.IDCompany; SessionManagement.LoggedInUser.FullName = userModel.UserName + " " + userModel.LastName; return RedirectToRoute("WorkfLow"); } else { ViewBag.ValidationMsg = "Invalid Email or Password"; return View("login"); } } /// <summary> /// Forgot password /// </summary> /// <returns></returns> public ActionResult ForgotPassword() { return View(); } [HttpPost] public ActionResult ForgotPassword(ForgotPassword ForgotPassword) { UserModel UserModel = userBusiness.ForgotPassword(ForgotPassword.Email); if (UserModel.IDUser != 0) { var MailResponce = SetPasswordByAdmin(UserModel); if (MailResponce.StatusCode != 200) { // ViewBag.ValidationMsg = MailResponce.Message; TempData["ValidationMsg"] = MailResponce.Message; } else { // ViewBag.SuccessMsg = MailResponce.Message; TempData["SuccessMsg"] = MailResponce.Message; } } else { TempData["ValidationMsg"] = "The email '" + ForgotPassword.Email + "' is not registered for this site. Please try again."; } return RedirectToAction("ForgotPassword"); } public Response SetPasswordByAdmin(UserModel UserModel) { bool isMailSent = true; Response response = new Response(); MailHelper mailHelper = new MailHelper(); MailBodyTemplate mailBodyTemplate = new MailBodyTemplate(); string mailTemplateFolder = ReadConfiguration.MailTemplateFolder; string mailBody = string.Empty; mailHelper.Subject = Constants.PasswordRecoveryMailSubject; mailHelper.ToEmail = UserModel.Email; mailBody = CommonFunctions.ReadFile(Server.MapPath(mailTemplateFolder + Constants.PasswordRecoveryMailFileName)); mailBodyTemplate.RegistrationUserName = UserModel.FirstName; mailBodyTemplate.MailBody = mailBody; mailBodyTemplate.AccountLoginUserId = UserModel.Email; mailBodyTemplate.AccountLoginPassowrd = UserModel.Password; mailBodyTemplate.AccountLoginUrl = ReadConfiguration.WebsiteLogoPath; mailBody = CommonFunctions.ConfigurePasswordRecoveryMailBody(mailBodyTemplate); mailHelper.Body = mailBody; isMailSent = mailHelper.SendEmail(); //TODO: //! use enum to set status rather than string value //TODO: //! handle the messages at client end "Message.js" file if (isMailSent) { response.Message = "An email has been sent to you with existing password. "; response.Status = "Success"; } else { response.Message = "Error while sending mail to user. Please try again."; response.Status = "Fail"; } return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.IO; namespace PracticaSP { public class GenericaXml<T> : IArchivo<T> { public bool Guardar(string path, T lista) { XmlSerializer xmlSer = new XmlSerializer(typeof(T)); XmlTextWriter xmlWri = new XmlTextWriter(path,Encoding.UTF8); bool retorno = false; try { xmlSer.Serialize(xmlWri, lista); retorno = true; } catch (Exception) { } finally { if (retorno = true) { xmlWri.Close(); } } return retorno; } public bool Leer(string archivo, out T datos) { bool retorno = false; XmlTextReader r = null; XmlSerializer s = new XmlSerializer(typeof(T)); datos = default(T); try { r = new XmlTextReader(archivo); datos = (T)s.Deserialize(r); } catch (Exception ex) { } finally { if (!(r is null)) { r.Close(); retorno = true; } } return retorno; } } }
using UnityEngine; using Random = UnityEngine.Random; namespace ManagerScripts { public class SoundScript : MonoBehaviour { public enum Sound { RapidBullet, BurstBullet, SniperBullet, LandmineBullet, Item, Background, Menu, Impact, Struck, NextLevel, Death, Detonation, ACK, NAK, Reload, } public AudioClip SniperBullet, Item, Menu, NextLevel, Death, LandmineBullet, Detonation, ACK, NAK, Reload; public AudioClip[] Impacts; public AudioClip[] Strucks; public AudioClip[] BurstBullets; public AudioClip[] RapidBullets; public static AudioSource a; public static SoundScript soundInstance; // Start is called before the first frame update void Awake() { if (soundInstance) { Destroy(gameObject); return; } soundInstance = this; a = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { } public static void PlaySound(Sound sound) { soundInstance.Play(sound); } public void Play(Sound sound) { switch (sound) { case Sound.RapidBullet: a.PlayOneShot(RapidBullets[Random.Range(0, RapidBullets.Length)], 0.2f); break; case Sound.BurstBullet: a.PlayOneShot(BurstBullets[Random.Range(0, BurstBullets.Length)], 0.1f); break; case Sound.Impact: a.PlayOneShot(Impacts[Random.Range(0, Impacts.Length)], 0.1f); break; case Sound.Menu: a.PlayOneShot(Menu); break; case Sound.SniperBullet: a.PlayOneShot(SniperBullet, 0.2f); break; case Sound.Struck: a.PlayOneShot(Strucks[Random.Range(0,Strucks.Length)]); break; case Sound.NextLevel: a.PlayOneShot(NextLevel, 0.4f); break; case Sound.Death: a.PlayOneShot(Death); break; case Sound.Item: a.PlayOneShot(Item); break; case Sound.LandmineBullet: a.PlayOneShot(LandmineBullet, 0.4f); break; case Sound.Detonation: a.PlayOneShot(Detonation, 0.2f); break; case Sound.ACK: a.PlayOneShot(ACK); break; case Sound.NAK: a.PlayOneShot(NAK); break; case Sound.Reload: a.PlayOneShot(Reload); break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AsEasy.Attrs; using AsEasy.Common; using Dapper; using DataStore.Dal; using DataStore.Entity; namespace AsEasy.Controllers { public class HomeController : BaseController { [AuthLogin] public ActionResult Index() { var roleService = new RoleService(); var pageIndex = GetPageIndexFromQuery(); var pageSize = GetPageSizeFromQuery(); var roles = roleService.GetList(pageIndex, pageSize); return View(roles); } [AuthPermission(Permission.HomeViewMessage)] [AuthLogin] public ActionResult HomeViewMessage() { return Content("HomeViewMessage"); } } }
using System; using FractionAddition.ConsoleApp; using Xunit; namespace Tests { public class WhenOperationIsParsing { [Fact] public void StringWithOnlySpacesThrowsInvalidOperationException() { var operatorString = " "; Action action = () => Operation.Parse(operatorString); var invalidOperationException = Assert.Throws<InvalidOperationException>(action); Assert.Equal("Operation it is not white space", invalidOperationException.Message); } [Fact] public void PlusStringParsingToAdditionOperation() { var plusString = "+"; var operation = Operation.Parse(plusString); Assert.IsType<AdditionOperation>(operation); } [Fact] public void PlusStringWithSpacesParsingToAdditionOperation() { var plusWithSpacesString = " + "; var operation = Operation.Parse(plusWithSpacesString); Assert.IsType<AdditionOperation>(operation); } [Fact] public void StringWithAnotherSymbolThrowsInvalidOperationException() { var stringWithAnotherSymbol = "0"; Action action = () => Operation.Parse(stringWithAnotherSymbol); var invalidOperationException = Assert.Throws<InvalidOperationException>(action); Assert.Equal("This operation is not support", invalidOperationException.Message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NewtonVR; using UnityEngine; class Grabber : MonoBehaviour { public float MaxLength; public float MinLength; public float GrabRadius; public NVRHand Hand; public Transform GrabTransform; private float step = 1; private float length; private Transform grabbed; void Start() { length = MinLength; UpdateTransform(); } void Update() { if (Hand != null) { transform.position = Hand.transform.position; transform.rotation = Hand.transform.rotation; if (Hand.Inputs[NVRButtons.Touchpad].IsPressed) { var touchpad = Hand.Inputs[NVRButtons.Touchpad].Axis; if (touchpad.y > 0.6f) { //Moving up ChangeLength(step); } else if (touchpad.y < -0.6f) { //Moving down ChangeLength(-step); } } GrabTransform.position = transform.position + transform.forward * length * 2; if(grabbed != null) { grabbed.localPosition = Vector3.zero; grabbed.GetComponent<Rigidbody>().velocity = Vector3.zero; if (Hand.Inputs[NVRButtons.Trigger].PressUp) { //Release the grabbed object Release(); } } if (Hand.Inputs[NVRButtons.Trigger].PressDown) { //Grab the closest object PickupClosest(); } } } void ChangeLength(float delta) { float tmpLength = length + delta * Time.unscaledDeltaTime; if(tmpLength > MaxLength) { length = MaxLength; } else if (tmpLength < MinLength) { length = MinLength; } else { length = tmpLength; } UpdateTransform(); } void UpdateTransform() { transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, length); } private void PickupClosest() { NVRInteractable closest = null; float closestDistance = float.MaxValue; var hits = Physics.OverlapSphere(GrabTransform.position, 0.4f); foreach (var hit in hits) { var interactable = hit.transform.GetComponent<NVRInteractable>(); if (interactable == null) continue; float distance = Vector3.Distance(this.transform.position, hit.transform.position); if (distance < closestDistance) { closestDistance = distance; closest = interactable; } } if (closest != null) { Grab(closest); } } private void Grab(NVRInteractable obj) { if (obj is NVRInteractableItem) { NVRInteractableItem item = obj as NVRInteractableItem; item.OnBeginInteraction.Invoke(); } obj.transform.SetParent(GrabTransform); obj.transform.localPosition = Vector3.zero; obj.Rigidbody.velocity = Vector3.zero; grabbed = obj.transform; } void Release() { var item = grabbed.GetComponent<NVRInteractableItem>(); if(item != null) { item.OnEndInteraction.Invoke(); } grabbed.SetParent(null); grabbed = null; } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_SkyboxCamera : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { SkyboxCamera o = new SkyboxCamera(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_skybox(IntPtr l) { int result; try { SkyboxCamera skyboxCamera = (SkyboxCamera)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, skyboxCamera.skybox); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_skybox(IntPtr l) { int result; try { SkyboxCamera skyboxCamera = (SkyboxCamera)LuaObject.checkSelf(l); Skybox skybox; LuaObject.checkType<Skybox>(l, 2, out skybox); skyboxCamera.skybox = skybox; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_skyboxMaterial(IntPtr l) { int result; try { SkyboxCamera skyboxCamera = (SkyboxCamera)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, skyboxCamera.skyboxMaterial); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_skyboxMaterial(IntPtr l) { int result; try { SkyboxCamera skyboxCamera = (SkyboxCamera)LuaObject.checkSelf(l); Material skyboxMaterial; LuaObject.checkType<Material>(l, 2, out skyboxMaterial); skyboxCamera.skyboxMaterial = skyboxMaterial; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.SkyboxCamera"); LuaObject.addMember(l, "skybox", new LuaCSFunction(Lua_RO_SkyboxCamera.get_skybox), new LuaCSFunction(Lua_RO_SkyboxCamera.set_skybox), true); LuaObject.addMember(l, "skyboxMaterial", new LuaCSFunction(Lua_RO_SkyboxCamera.get_skyboxMaterial), new LuaCSFunction(Lua_RO_SkyboxCamera.set_skyboxMaterial), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_SkyboxCamera.constructor), typeof(SkyboxCamera), typeof(LuaGameObject)); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management; using System.Xml.Linq; namespace ServiceWatcher.Backend { /// <summary> /// Operations that can be used to obtain / act on services or processes /// </summary> public class Operations { private static ManagementObject GetProcess(string machineName, string processId) { var scope = new ManagementScope("\\\\" + machineName + "\\root\\cimv2"); var getService = new ObjectQuery( "Select * from Win32_Process where ProcessId = '" + processId + "'"); var search = new ManagementObjectSearcher(scope, getService); ManagementObjectCollection services = search.Get(); foreach (ManagementObject service in services) { return service; } return null; } /// <summary> /// Gets the <see cref="ManagementObject"/> that represents this service. /// </summary> /// <param name="machineName">Name of the machine.</param> /// <param name="serviceName">Name of the service.</param> /// <returns></returns> public static ManagementObject GetService(string machineName, string serviceName) { var scope = new ManagementScope("\\\\" + machineName + "\\root\\cimv2"); var getService = new ObjectQuery("Select Name, State, ProcessId from Win32_Service where Name = '" + serviceName + "'"); var search = new ManagementObjectSearcher(scope, getService); ManagementObjectCollection services = search.Get(); foreach (ManagementObject service in services) { return service; } return null; } /// <summary> /// Kills the process. /// </summary> /// <param name="machineName">Name of the machine.</param> /// <param name="serviceObj">The service obj.</param> /// <param name="observer">The observer.</param> public static void KillProcess(string machineName, ManagementObject serviceObj, ManagementOperationObserver observer) { string str = String.Empty; foreach (var prop in serviceObj.Properties) { str += String.Format("{0} - {1}\r\n", prop.Name, prop.Value); } var processObj = GetProcess(machineName, serviceObj["ProcessId"].ToString()); processObj.InvokeMethod(observer, "Terminate", null); } /// <summary> /// Loads the servers from the config file. /// </summary> /// <returns></returns> public static IEnumerable<Server> LoadServers() { XDocument doc = XDocument.Load("Config.xml"); IEnumerable<Server> results = from server in doc.Descendants("Server") select new Server { Name = (string)server.Attribute("Name"), Services = new ObservableCollection<Service>( from service in server.Descendants("Service") select new Service((string)service.Attribute("DisplayName"), (string)service.Attribute("ShortName"))) }; var servers = results.ToList(); RefreshServers(servers); return servers; } /// <summary> /// Refreshes the list of server information. /// </summary> /// <param name="servers">The servers.</param> public static void RefreshServers(IEnumerable<Server> servers) { foreach (Server server in servers) { string name = server.Name; foreach (Service service in server.Services) { service.ManagementObj = GetService(name, service.Name); } } } /// <summary> /// Starts the service. /// </summary> /// <param name="machineName">Name of the machine.</param> /// <param name="serviceObj">The service obj.</param> /// <param name="observer">The observer.</param> public static void StartService(ManagementObject serviceObj, ManagementOperationObserver observer) { serviceObj.InvokeMethod(observer, "StartService", null); } /// <summary> /// Stops the service. /// </summary> /// <param name="machineName">Name of the machine.</param> /// <param name="serviceObj">The service obj.</param> /// <param name="observer">The observer.</param> public static void StopService(ManagementObject serviceObj, ManagementOperationObserver observer) { serviceObj.InvokeMethod(observer, "StopService", null); } } }
namespace Wild_farm { using System; using System.Linq; public class StartUp { public static void Main() { while (true) { var input = Console.ReadLine(); if (input == "End") { return; } var animalData = input.Split(new char[] { ' ' }).ToArray(); var animalType = animalData[0]; var animalName = animalData[1]; var animalWeight = double.Parse(animalData[2]); var animalLivingRegion = animalData[3]; string catBreed = ""; if (animalType == "Cat") { catBreed = animalData[4]; } var animal = TryAnimalCreate(animalType, animalName, animalWeight, animalLivingRegion, catBreed); animal.MakeSound(); var foodData = Console.ReadLine().Split(new char[] { ' ' }).ToArray(); var foodType = foodData[0]; var foodQuantity = int.Parse(foodData[1]); var food = CreateFood(foodType, foodQuantity); try { animal.Eat(food); } catch (ApplicationException ae) { Console.WriteLine(ae.Message); } Console.WriteLine(animal); } } private static Food CreateFood(string foodType, int foodQuantity) { if (foodType == "Vegetable") { return new Vegetable(foodQuantity); } return new Meat(foodQuantity); } private static Mammal TryAnimalCreate(string animalType, string animalName, double animalWeight, string animalLivingRegion, string catBreed) { Mammal result = null; switch (animalType) { case "Mouse": result = new Mouse(animalName, animalType, animalWeight, animalLivingRegion); break; case "Zebra": result = new Zebra(animalName, animalType, animalWeight, animalLivingRegion); break; case "Cat": result = new Cat(animalName, animalType, animalWeight, animalLivingRegion, catBreed); break; case "Tiger": result = new Tiger(animalName, animalType, animalWeight, animalLivingRegion); break; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; namespace _2.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { public DateTimeOffset CreateData { get; set; } public DateTimeOffset LastLoginDate { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Lab6.DataBases; using Lab6.Entities; using Lab6.Entities.Task; namespace Lab6.DAL { public class AccessBDTasks { public static List<Task> GetAllTasksByEmployeeId(Guid employeeId) { return BDTasks.ListsOfTasks[employeeId]; } public static Task GetTaskById(Guid id) { return BDTasks.ListsOfTasks.Values .First(x => x.Exists(y => y.Id.Equals(id))) .Find(x => x.Id.Equals(id)); } public static List<Task> GetTasksByUpdateDate(DateTime dateTime) { return (from val in BDTasks.ListsOfTasks.Values from task in val where task.LastUpdate.Date == dateTime.Date select task) .ToList(); } public static List<Task> GetTasksByEmployeeId(Guid id) { return BDTasks.ListsOfTasks[id]; } public static List<Task> GetAllUpdatedTasks(Guid id) { return (from val in BDTasks.ListsOfChanges[id] from task in BDTasks.ListsOfTasks[id] where task.Id == val.Id select task) .ToList(); } public static void AddTask(Task task) { AddMemento(new Memento(task.Id, task.Status, task.Description)); if (BDTasks.ListsOfTasks.ContainsKey(task.Owner)) BDTasks.ListsOfTasks[task.Owner].Add(task); else BDTasks.ListsOfTasks.Add(task.Owner, new List<Task>() {task}); } public static void RemoveTask(Guid id) { AddMemento(GetTaskById(id).Changes(null)); BDTasks.ListsOfTasks.Remove(id); } public static void UpdateTask(Task task) { task.LastUpdate = DateTime.Now; var before = BDTasks.ListsOfTasks.Values .First(x => x.Exists(y => y.Id.Equals(task.Id))) .Find(x => x.Id.Equals(task.Id)); if (before != null) AddMemento(before.Changes(task)); if (before == null || task.Owner == before.Owner) { BDTasks.ListsOfTasks[task.Owner] .Insert(BDTasks.ListsOfTasks[task.Owner].FindIndex(x => x.Id.Equals(task.Id)), task); } else { BDTasks.ListsOfTasks[before.Owner] .RemoveAt(BDTasks.ListsOfTasks[before.Owner].FindIndex(x => x.Id.Equals(before.Id))); BDTasks.ListsOfTasks[task.Owner].Add(task); } } public static void GetMemento() { } public static void AddMemento(Memento memento) { if (BDTasks.ListsOfChanges.ContainsKey(memento.Id)) BDTasks.ListsOfChanges[memento.Id].Add(memento); else BDTasks.ListsOfChanges.Add(memento.Id, new List<Memento>() {memento}); } public static void AddNewResolvedTask(Task task) { if (BDTasks.ListsOfLastResolvedTasks.ContainsKey(task.Owner)) BDTasks.ListsOfLastResolvedTasks[task.Owner].Add(task); else BDTasks.ListsOfLastResolvedTasks.Add(task.Owner, new List<Task>() {task}); } public static List<Task> GetLastResolvedTasks(Guid id) { if (BDTasks.ListsOfLastResolvedTasks.ContainsKey(id)) return BDTasks.ListsOfLastResolvedTasks[id]; else return new List<Task>(); } public static void DeleteLastResolvedTasks(Guid id) { BDTasks.ListsOfLastResolvedTasks[id].Clear(); } } }
using System.Collections.Generic; using System.Web.Mvc; using Task03_MobileShop.Areas.Laptops.Models; using Task03_MobileShop.Areas.Smartphones.Models; namespace Task03_MobileShop.Areas.Laptops.Controllers { public class IndexController : Controller { IEnumerable<LaptopViewModel> laptops = new List<LaptopViewModel>() { new LaptopViewModel() { Manufacturer = "Acer", Model = "Aspire ES1-131", Url = "http://www.pcstore.bg/media/catalog/product/cache/1/image/325x250/0dc2d03fe217f8c83829496872af24a0/n/x/nx.mygex.015_1_image.jpg", Info = "Some info about the laptop" }, new LaptopViewModel() { Manufacturer = "HP", Model = "15 N6A60EA", Url = "http://www.pcstore.bg/media/catalog/product/cache/1/image/280x215/0dc2d03fe217f8c83829496872af24a0/n/6/n6a60ea_1_image.jpg", Info = "Some info about the laptop" }, new LaptopViewModel() { Manufacturer = "Lenovo", Model = "100 80MJ00E5BM", Url = "http://www.pcstore.bg/media/catalog/product/cache/1/image/325x250/0dc2d03fe217f8c83829496872af24a0/8/0/80mj00e5bm_1_image.jpg", Info = "Some info about the laptop" } }; // GET: Smartphones/Index public ActionResult Index() { return View(laptops); } } }
using GrandTheftMultiplayer.Server.API; using GrandTheftMultiplayer.Server.Elements; using GrandTheftMultiplayer.Server.Managers; using GrandTheftMultiplayer.Shared.Math; namespace NGGBusDriver { public class BusStop { public CylinderColShape VehicleColShape { get; set; } public int StopId { get; set; } public Vector3 Marker { get; set; } public Object Busstop { get; set; } public TextLabel Label { get; set; } public CylinderColShape BusStopColshape { get; set; } public BusStop() { } public BusStop(CylinderColShape VehicleColShape,Vector3 Marker, Object Busstop,TextLabel Label,CylinderColShape BusStopColshape, int StopId) { this.VehicleColShape = VehicleColShape; this.Marker = Marker; this.Busstop = Busstop; this.Label = Label; this.BusStopColshape = BusStopColshape; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using aaMXItem; using InfluxData.Net.Models; using System.Collections; using System.Collections.Concurrent; using InfluxData.Net; using InfluxData.Net.Helpers; namespace aaInflux { public static class Extensions { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static bool TryAddArray<T>(this BlockingCollection<T> collection, T[] items) { bool returnValue = true; try { foreach (T item in items) { returnValue = returnValue && collection.TryAdd(item); } } catch(Exception ex) { throw ex; } return returnValue; } public static void AddArray<T>(this BlockingCollection<T> collection, T[] items) { try { foreach (T item in items) { collection.Add(item); } } catch (Exception ex) { throw ex; } } public static bool IsAwake(this InfluxData.Net.InfluxDb client, int timeOut = 5000) { bool returnValue; try { Pong pong = new Pong(); Task.Run(async () => { Task<Pong> pongTask = client.PingAsync(); pong = await pongTask; } ).Wait(timeOut); log.DebugFormat("Pong Returns {0}", pong.ToJson()); returnValue = pong.Success; } catch { // Just eat the error because we don't want to log it if the server is just not responding since we have a way to manage it return false; } return returnValue; } } }
using OpenGov.Models; using System.Collections.Generic; namespace OpenGovAlerts { public class Config { public SmtpConfig Smtp { get; set; } public List<Client> Clients { get; set; } public List<Search> Searches { get; set; } } }
namespace K4AdotNet.NativeHandles { // Defined in k4atypes.h: // K4A_DECLARE_HANDLE(k4a_capture_t); // /// <summary>Handle to an Azure Kinect capture.</summary> /// <remarks> /// Empty captures are created with <c>k4a_capture_create()</c>. /// Captures can be obtained from a device using <c>k4a_device_get_capture()</c>. /// </remarks> internal sealed class CaptureHandle : HandleBase, IReferenceDuplicatable<CaptureHandle> { private CaptureHandle() { } /// <summary> /// Call this method if you want to have one more reference to the same capture. /// </summary> /// <returns>Additional reference to the same capture. Don't forget to call <see cref="System.IDisposable.Dispose"/> method for object returned.</returns> public CaptureHandle DuplicateReference() { NativeApi.CaptureReference(handle); return new CaptureHandle { handle = handle }; } protected override bool ReleaseHandle() { NativeApi.CaptureRelease(handle); return true; } public static readonly CaptureHandle Zero = new CaptureHandle(); } }
using System; namespace Crt.Model.Dtos.FinTarget { public class FinTargetSaveDto { public decimal ProjectId { get; set; } public string Description { get; set; } public decimal Amount { get; set; } public decimal FiscalYearLkupId { get; set; } public decimal ElementId { get; set; } public decimal PhaseLkupId { get; set; } public decimal FundingTypeLkupId { get; set; } public DateTime? EndDate { get; set; } } }
using System; //For MethodImpl using System.Runtime.CompilerServices; namespace Unicorn { public class Emitter { // Native handle for this component private IntPtr native_handle = IntPtr.Zero; public bool isActive { get { return get_isActive_Internal(native_handle); } set { set_isActive_Internal(native_handle, value); } } public int id { get { return get_EmitterID_Internal(native_handle); } set { set_EmitterID_Internal(native_handle, value); } } public int shapeType { get { return get_ShapeType_Internal(native_handle); } set { set_ShapeType_Internal(native_handle, value); } } public float duration { get { return get_Duration_Internal(native_handle); } set { set_Duration_Internal(native_handle, value); } } public uint emitRate { get { return get_EmitRate_Internal(native_handle); } set { set_EmitRate_Internal(native_handle, value); } } public uint maxParticles { get { return get_MaxParticle_Internal(native_handle); } set { set_MaxParticle_Internal(native_handle, value); } } public float burstRate { get { return get_BurstRate_Internal(native_handle); } set { set_BurstRate_Internal(native_handle, value); } } public uint burstAmount { get { return get_BurstAmount_Internal(native_handle); } set { set_BurstAmount_Internal(native_handle, value); } } public float angle { get { return get_Angle_Internal(native_handle); } set { set_Angle_Internal(native_handle, value); } } public float radius { get { return get_Radius_Internal(native_handle); } set { set_Radius_Internal(native_handle, value); } } public bool randomizeSize { get { return get_RandomizeSize_Internal(native_handle); } set { set_RandomizeSize_Internal(native_handle, value); } } public float minParticleSize { get { return get_MinParticleSize_Internal(native_handle); } set { set_MinParticleSize_Internal(native_handle, value); } } public float maxParticleSize { get { return get_MaxParticleSize_Internal(native_handle); } set { set_MaxParticleSize_Internal(native_handle, value); } } public bool randomizeSpeed { get { return get_RandomizeSpeed_Internal(native_handle); } set { set_RandomizeSpeed_Internal(native_handle, value); } } public float minParticleSpeed { get { return get_MinParticleSpeed_Internal(native_handle); } set { set_MinParticleSpeed_Internal(native_handle, value); } } public float maxParticleSpeed { get { return get_MaxParticleSpeed_Internal(native_handle); } set { set_MaxParticleSpeed_Internal(native_handle, value); } } public bool randomizeLife { get { return get_RandomizeLife_Internal(native_handle); } set { set_RandomizeLife_Internal(native_handle, value); } } public float minParticleLife { get { return get_MinParticleLife_Internal(native_handle); } set { set_MinParticleLife_Internal(native_handle, value); } } public float maxParticleLife { get { return get_MaxParticleLife_Internal(native_handle); } set { set_MaxParticleLife_Internal(native_handle, value); } } public bool prewarm { get { return get_Prewarm_Internal(native_handle); } set { set_Prewarm_Internal(native_handle, value); } } public bool burst { get { return get_Burst_Internal(native_handle); } set { set_Burst_Internal(native_handle, value); } } public bool loop { get { return get_Loop_Internal(native_handle); } set { set_Loop_Internal(native_handle, value); } } public bool follow { get { return get_Follow_Internal(native_handle); } set { set_Follow_Internal(native_handle, value); } } public bool fade { get { return get_Fade_Internal(native_handle); } set { set_Fade_Internal(native_handle, value); } } public bool velocityOverTime { get { return get_VelocityOverTime_Internal(native_handle); } set { set_VelocityOverTime_Internal(native_handle, value); } } public bool sizeOverTime { get { return get_SizeOverTime_Internal(native_handle); } set { set_SizeOverTime_Internal(native_handle, value); } } public bool speedOverTime { get { return get_SpeedOverTime_Internal(native_handle); } set { set_SpeedOverTime_Internal(native_handle, value); } } public bool colourOverTime { get { return get_ColourOverTime_Internal(native_handle); } set { set_ColourOverTime_Internal(native_handle, value); } } //public Vector4 colourA //{ // get { return get_ColourA_Internal(native_handle); } // set { set_ColourA_Internal(native_handle, value); } //} public Vector4 GetColourA() { return get_ColourA_Internal(native_handle); } public void SetColourA(Vector4 val) { set_ColourA_Internal(native_handle, val); } //public Vector4 colourB //{ // get { return get_ColourB_Internal(native_handle); } // set { set_ColourB_Internal(native_handle, value); } //} public Vector4 GetColourB() { return get_ColourB_Internal(native_handle); } public void SetColourB(Vector4 val) { set_ColourB_Internal(native_handle, val); } //public Vector4 colourStart //{ // get { return get_ColourStart_Internal(native_handle); } // set { set_ColourStart_Internal(native_handle, value); } //} public Vector4 GetColourStart() { return get_ColourStart_Internal(native_handle); } public void SetColourStart(Vector4 val) { set_ColourStart_Internal(native_handle, val); } //public Vector4 colourEnd //{ // get { return get_ColourEnd_Internal(native_handle); } // set { set_ColourEnd_Internal(native_handle, value); } //} public Vector4 GetColourEnd() { return get_ColourEnd_Internal(native_handle); } public void SetColourEnd(Vector4 val) { set_ColourEnd_Internal(native_handle, val); } public Vector3 GetVelocity() { return get_Velocity_Internal(native_handle); } public void SetVelocity(Vector3 val) { set_Velocity_Internal(native_handle, val); } public void AddTexture(string val) { cs_AddTexture_Internal(this.native_handle, val); } public void Play() { cs_Play_Internal(this.native_handle); } public void Stop() { cs_Stop_Internal(this.native_handle); } [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_isActive_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_isActive_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static int get_EmitterID_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_EmitterID_Internal(IntPtr native_handle, int val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static int get_ShapeType_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_ShapeType_Internal(IntPtr native_handle, int val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_Duration_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Duration_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static uint get_EmitRate_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_EmitRate_Internal(IntPtr native_handle, uint val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static uint get_MaxParticle_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MaxParticle_Internal(IntPtr native_handle, uint val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_BurstRate_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_BurstRate_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static uint get_BurstAmount_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_BurstAmount_Internal(IntPtr native_handle, uint val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_Angle_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Angle_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_Radius_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Radius_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_RandomizeSize_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_RandomizeSize_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_MinParticleSize_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MinParticleSize_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_MaxParticleSize_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MaxParticleSize_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_RandomizeSpeed_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_RandomizeSpeed_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_MinParticleSpeed_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MinParticleSpeed_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_MaxParticleSpeed_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MaxParticleSpeed_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_RandomizeLife_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_RandomizeLife_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_MinParticleLife_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MinParticleLife_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static float get_MaxParticleLife_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_MaxParticleLife_Internal(IntPtr native_handle, float val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_Prewarm_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Prewarm_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_Burst_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Burst_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_Loop_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Loop_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_Follow_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Follow_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_Fade_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Fade_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_VelocityOverTime_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_VelocityOverTime_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_SizeOverTime_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_SizeOverTime_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_SpeedOverTime_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_SpeedOverTime_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static bool get_ColourOverTime_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_ColourOverTime_Internal(IntPtr native_handle, bool val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static Vector4 get_ColourA_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_ColourA_Internal(IntPtr native_handle, Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static Vector4 get_ColourB_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_ColourB_Internal(IntPtr native_handle, Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static Vector4 get_ColourStart_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_ColourStart_Internal(IntPtr native_handle, Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static Vector4 get_ColourEnd_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_ColourEnd_Internal(IntPtr native_handle, Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static Vector3 get_Velocity_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void set_Velocity_Internal(IntPtr native_handle, Vector3 val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void cs_AddTexture_Internal(IntPtr native_handle, string val); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void cs_Play_Internal(IntPtr native_handle); [MethodImpl(MethodImplOptions.InternalCall)] public extern static void cs_Stop_Internal(IntPtr native_handle); } }
namespace Newtonsoft.Json.Serialization { using ns16; using System; public class JsonStringContract : JsonPrimitiveContract { public JsonStringContract(Type underlyingType) : base(underlyingType) { base.enum15_0 = Enum15.String; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SaveLoad : MonoBehaviour { public List<float> savedHasil; public int jumlahCoba; public bool resetPrefs; public SoalManager soalManager; private List<float> temp; // Start is called before the first frame update void Start() { temp = new List<float>(); if(resetPrefs){ jumlahCoba = 0; savedHasil[0] = 0; savedHasil[1] = 0; savedHasil[2] = 0; savedHasil[3] = 0; }else{ jumlahCoba = PlayerPrefs.GetInt("coba",0); savedHasil[0] = PlayerPrefs.GetFloat("type1",0); savedHasil[1] = PlayerPrefs.GetFloat("type2",0); savedHasil[2] = PlayerPrefs.GetFloat("type3",0); savedHasil[3] = PlayerPrefs.GetFloat("type4",0); } } void Restart(){ SceneManager.LoadScene("2 kuisioner"); } //Logistic Regression nya disini public int LogisticRegression(List<int> recordedHasil){ jumlahCoba++; // jumlah iterasi satu anak nyoba mengisi PlayerPrefs.SetInt("coba",jumlahCoba); float angka,angka2; for(int i =0;i<savedHasil.Count;i++){ angka = (savedHasil[i] + recordedHasil[i]); temp.Add(angka); } PlayerPrefs.SetFloat("type1",temp[0]); PlayerPrefs.SetFloat("type2",temp[1]); PlayerPrefs.SetFloat("type3",temp[2]); PlayerPrefs.SetFloat("type4",temp[3]); List<float> temp2 = new List<float>(); for(int i =0;i<temp.Count;i++){ angka2 = temp[i]/jumlahCoba; temp2.Add(angka2); } int hasil = MaxValue(temp2); return hasil; } int MaxValue (List<float> intArray) { float max = intArray[0]; int arrayNumber = 0; for (int i=0; i < intArray.Count; i++) { if (intArray[i] > max) { max = intArray[i]; arrayNumber = i; } } return arrayNumber; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Console2.From_026_To_050 { public class _043_PascalTriangle { /* * Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] */ public List<List<int>> PascalTriangle(int n) { List<List<int>> res = new List<List<int>>(); res.Add(new List<int>() { 1 }); if (n == 1) return res; res.Add(new List<int>() { 1, 1 }); if (n == 2) return res; for (int i = 2; i < n; i++) { List<int> tmp = new List<int>() { 1 }; for (int j = 0; j < res[i - 1].Count - 1; j++) { tmp.Add(res[i - 1][j] + res[i - 1][j + 1]); } tmp.Add(1); res.Add(tmp); } return res; } /* * Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. */ public List<int> psacalTriangleII(int n) { if (n == 1) return new List<int>() { 1 }; if (n == 2) return new List<int>() { 1, 1 }; List<int> res = new List<int>(){1,1}; for (int i = 2; i < n; i++) { res.Insert(0, 1); for (int j = 1; j < res.Count - 1; j++) { res[j] = res[j] + res[j + 1]; } res[res.Count - 1] = 1; } return res; } } }
namespace MainClassLibrary { /// <summary> /// Employee class containing all the fields and property of Employee Entity /// </summary> internal class Employee { public int EmpID { get; set; } public string EmpName { get; set; } public int ManagerID { get; set; } public string EmpEmail { get; set; } } }
using ATSBackend.Domain.Entities; using ATSBackend.Application.Interfaces; using ATSBackend.Domain.Interfaces.Services; namespace ATSBackend.Application.Services { public class CurriculoApplication : ApplicationBase<Curriculo>, ICurriculoApplication { private readonly ICurriculoService _curriculoService; public CurriculoApplication(ICurriculoService curriculoService) : base(curriculoService) { _curriculoService = curriculoService; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace LateOS.Models { [MetadataType(typeof(cEstadoFactura))] public partial class tbEstadoFactura { } public class cEstadoFactura { [Display(Name = "ID Estado Factura")] public int estf_Id { get; set; } [Display(Name = "Estado Factura")] [Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} de requerido.")] [MaxLength(25, ErrorMessage = "Excedió el máximo de caracteres permitidos.")] public string estf_Descripcion { get; set; } public int estf_UsuarioCrea { get; set; } public System.DateTime estf_FechaCrea { get; set; } public Nullable<int> estf_UsuarioModifica { get; set; } public Nullable<System.DateTime> estf_FechaModifica { get; set; } public virtual tbUsuarios tbUsuarios { get; set; } public virtual tbUsuarios tbUsuarios1 { get; set; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Collections.Generic; namespace DotNetNuke.Entities.Content.Workflow.Repositories { /// <summary> /// This class is responsible to persist and retrieve workflow entity /// </summary> internal interface IWorkflowRepository { /// <summary> /// This method gets the list of system portal workflows /// </summary> /// <param name="portalId">Portal Id</param> /// <returns>List of system workflows of the portal</returns> IEnumerable<Entities.Workflow> GetSystemWorkflows(int portalId); /// <summary> /// This method gets the list of portal workflows /// </summary> /// <param name="portalId">Portal Id</param> /// <returns>List of workflows of the portal</returns> IEnumerable<Entities.Workflow> GetWorkflows(int portalId); /// <summary> /// This method gets the Workflow by Id /// </summary> /// <param name="workflowId">Workflow Id</param> /// <returns>Workflow entity</returns> Entities.Workflow GetWorkflow(int workflowId); /// <summary> /// This method gets the Workflow by Content Item Id /// </summary> /// <param name="contentItem">Content Item entity</param> /// <returns>Workflow entity</returns> Entities.Workflow GetWorkflow(ContentItem contentItem); /// <summary> /// This method persists a new workflow entity /// </summary> /// <param name="workflow">Workflow entity</param> void AddWorkflow(Entities.Workflow workflow); /// <summary> /// This method persists changes for a workflow entity /// </summary> /// <param name="workflow">Workflow entity</param> void UpdateWorkflow(Entities.Workflow workflow); /// <summary> /// This method hard deletes a workflow /// </summary> /// <param name="workflow">Workflow entity</param> void DeleteWorkflow(Entities.Workflow workflow); } }
namespace AjLisp.Primitives { using System; using System.Collections.Generic; using System.Text; using AjLisp.Language; public class FSubrProgN : FSubr { public override object Execute(List arguments, ValueEnvironment environment) { object result = null; while (!Predicates.IsNil(arguments)) { result = Machine.Evaluate(arguments.First, environment); arguments = arguments.Next; } return result; } } }
/* * DialMyCalls API * * The DialMyCalls API * * OpenAPI spec version: 2.0.1 * Contact: support@dialmycalls.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.DialMyCalls.Model { /// <summary> /// CreateRecordingByPhoneParameters /// </summary> [DataContract] public partial class CreateRecordingByPhoneParameters : IEquatable<CreateRecordingByPhoneParameters> { /// <summary> /// Initializes a new instance of the <see cref="CreateRecordingByPhoneParameters" /> class. /// </summary> /// <param name="Name">(Required) The name of the recording..</param> /// <param name="CalleridId">The caller id that the create recording message should be sent from..</param> /// <param name="Whitelabel">Add or remove the DialMyCalls intro message..</param> /// <param name="Phone">(Required) The recipient&#39;s phone number who will record the message..</param> /// <param name="Extension">The recipient&#39;s phone extension up to 10 numeric digits..</param> public CreateRecordingByPhoneParameters(string Name = null, Guid? CalleridId = null, bool? Whitelabel = null, string Phone = null, string Extension = null) { this.Name = Name; this.CalleridId = CalleridId; this.Whitelabel = Whitelabel; this.Phone = Phone; this.Extension = Extension; } /// <summary> /// (Required) The name of the recording. /// </summary> /// <value>(Required) The name of the recording.</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// The caller id that the create recording message should be sent from. /// </summary> /// <value>The caller id that the create recording message should be sent from.</value> [DataMember(Name="callerid_id", EmitDefaultValue=false)] public Guid? CalleridId { get; set; } /// <summary> /// Add or remove the DialMyCalls intro message. /// </summary> /// <value>Add or remove the DialMyCalls intro message.</value> [DataMember(Name="whitelabel", EmitDefaultValue=false)] public bool? Whitelabel { get; set; } /// <summary> /// (Required) The recipient&#39;s phone number who will record the message. /// </summary> /// <value>(Required) The recipient&#39;s phone number who will record the message.</value> [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } /// <summary> /// The recipient&#39;s phone extension up to 10 numeric digits. /// </summary> /// <value>The recipient&#39;s phone extension up to 10 numeric digits.</value> [DataMember(Name="extension", EmitDefaultValue=false)] public string Extension { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CreateRecordingByPhoneParameters {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CalleridId: ").Append(CalleridId).Append("\n"); sb.Append(" Whitelabel: ").Append(Whitelabel).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" Extension: ").Append(Extension).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CreateRecordingByPhoneParameters); } /// <summary> /// Returns true if CreateRecordingByPhoneParameters instances are equal /// </summary> /// <param name="other">Instance of CreateRecordingByPhoneParameters to be compared</param> /// <returns>Boolean</returns> public bool Equals(CreateRecordingByPhoneParameters other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CalleridId == other.CalleridId || this.CalleridId != null && this.CalleridId.Equals(other.CalleridId) ) && ( this.Whitelabel == other.Whitelabel || this.Whitelabel != null && this.Whitelabel.Equals(other.Whitelabel) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.Extension == other.Extension || this.Extension != null && this.Extension.Equals(other.Extension) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CalleridId != null) hash = hash * 59 + this.CalleridId.GetHashCode(); if (this.Whitelabel != null) hash = hash * 59 + this.Whitelabel.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.Extension != null) hash = hash * 59 + this.Extension.GetHashCode(); return hash; } } } }
using ACO.Util.MTDispatcher; namespace ACO { public class Core : Singleton<Core> { protected Core() { } private void Awake() { SetInstance(this); } public DispatcherAction DispatcherAction = new DispatcherAction(); private void Update() { DispatcherAction.Update(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Collections; namespace RSMS { public partial class ReportFrmFilter : MySubDialogBase { public ReportFrm parentFrm; public Dictionary<int, object> lastValues; private void historyDataRestore() { if (lastValues != null) { foreach (KeyValuePair<int, object> v in lastValues) { if (Controls[v.Key] is TextBox) { Controls[v.Key].Text = v.Value.ToString(); } else if (Controls[v.Key] is ComboBox) { ((ComboBox)Controls[v.Key]).SelectedIndex = (int)v.Value; } else if (Controls[v.Key] is DateTimePicker) { ((DateTimePicker)Controls[v.Key]).Value = (DateTime)v.Value; ((DateTimePicker)Controls[v.Key]).Checked = true; } } } } public ReportFrmFilter() { InitializeComponent(); } private void ReportFrmFilter_Load(object sender, EventArgs e) { st.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 0:0:0")); et.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")); st.Checked = false; et.Checked = false; historyDataRestore(); } private void button1_Click(object sender, EventArgs e) { //所有条件合成传递 ArrayList al = new ArrayList(); lastValues = new Dictionary<int, object>(); int i = 1; string sqlWhere = ""; string whereSplit = ""; //商户代码 if (TB1.Text != "" && TB2.Text != "") { al.Add(new SqlParameter("@v" + i.ToString(), TB1.Text)); sqlWhere += " cCusCode between @v" + i.ToString(); lastValues.Add(Controls.IndexOf(TB1), TB1.Text); i++; al.Add(new SqlParameter("@v" + i.ToString(), TB2.Text)); sqlWhere += " and @v" + i.ToString(); lastValues.Add(Controls.IndexOf(TB2), TB2.Text); whereSplit = " and "; i++; } //车牌号 if (TB3.Text != "") { sqlWhere += whereSplit + " cPlateNum =@v" + i.ToString(); al.Add(new SqlParameter("@v" + i.ToString(), TB3.Text)); lastValues.Add(Controls.IndexOf(TB3), TB3.Text); i++; whereSplit = " and "; } //司机 if (TB4.Text != "") { sqlWhere += whereSplit + " cDriverName=@v" + i.ToString(); al.Add(new SqlParameter("@v" + i.ToString(), TB4.Text)); lastValues.Add(Controls.IndexOf(TB4), TB4.Text); i++; whereSplit = " and "; } //磅单 if (TB5.Text != "") { //cBillNo sqlWhere += whereSplit + " [cBillNo]=@v" + i.ToString(); al.Add(new SqlParameter("@v" + i.ToString(), TB5.Text)); lastValues.Add(Controls.IndexOf(TB5), TB5.Text); i++; whereSplit = " and "; } //ic卡号 if (TB6.Text != "") { sqlWhere += whereSplit + " cICNum=@v" + i.ToString(); al.Add(new SqlParameter("@v" + i.ToString(), TB6.Text)); lastValues.Add(Controls.IndexOf(TB6), TB6.Text); i++; whereSplit = " and "; } //订单号 if (TB7.Text != "") { sqlWhere += whereSplit + " [cOrderNo]=@v" + i.ToString(); al.Add(new SqlParameter("@v" + i.ToString(), TB7.Text)); lastValues.Add(Controls.IndexOf(TB7), TB7.Text); i++; whereSplit = " and "; } //订单类型 if (TB8.Text != "") { sqlWhere += whereSplit + " [cOrderType]=@v" + i.ToString(); al.Add(new SqlParameter("@v" + i.ToString(), TB8.Text)); lastValues.Add(Controls.IndexOf(TB8), TB8.Text); i++; whereSplit = " and "; } //物料代码 if (TB9.Text != "" && TB10.Text != "") { string tmp = " [cSeqNum] in( select distinct [cSeqNum] from [sapPlanOrders] where cInvCode between "; al.Add(new SqlParameter("@v" + i.ToString(), TB9.Text)); tmp += "@v" + i.ToString(); lastValues.Add(Controls.IndexOf(TB9), TB9.Text); i++; al.Add(new SqlParameter("@v" + i.ToString(), TB10.Text)); tmp += " and @v" + i.ToString() + " ) "; lastValues.Add(Controls.IndexOf(TB10), TB10.Text); sqlWhere += whereSplit + tmp; whereSplit = " and "; i++; } //时间 if (st.Checked && et.Checked) { al.Add(new SqlParameter("@v" + i.ToString(), st.Value.ToString("yyyy-MM-dd HH:mm:ss"))); sqlWhere += whereSplit + " [dNetWeightDate] between @v" + i.ToString(); lastValues.Add(Controls.IndexOf(st), st.Value); i++; al.Add(new SqlParameter("@v" + i.ToString(), et.Value.ToString("yyyy-MM-dd HH:mm:ss"))); sqlWhere += " and @v" + i.ToString(); lastValues.Add(Controls.IndexOf(et), et.Value); whereSplit = " and "; i++; } parentFrm.lastValues = lastValues; parentFrm.queryDb(" where " + (sqlWhere == "" ? " 1= 1" : sqlWhere), al); Close(); } private void button3_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "商户代码"; bfcd.headerText2 = "商户名称"; bfcd.retTextId = 1; SqlParameter[] sqlPar = new SqlParameter[2]; sqlPar[0] = new SqlParameter("@v1", "%" + TB1.Text + "%"); sqlPar[1] = new SqlParameter("@v2", "%" + TB1.Text + "%"); bfcd.dt = myHelper.getDataTable("select [cCusCode] , [cCusName] from WeightNotes where AutoId in (select min(AutoId) from WeightNotes group by cCusCode) and ( cCusName like @v1 or cCusCode like @v2)", sqlPar); bfcd.showDlg(); } void bfcd_callBackAction(object sender, myHelper.OPEventArgs e) { if (e != null && e.param != null) { string ctrlName = "TB" + e.param[1]; foreach (Control cl in this.Controls) { if (cl.Name == ctrlName) { cl.Text = e.param[0]; e.param = null; e = null; break; } } } } private void button12_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "商户代码"; bfcd.headerText2 = "商户名称"; bfcd.retTextId = 2; SqlParameter[] sqlPar = new SqlParameter[2]; sqlPar[0] = new SqlParameter("@v1", "%" + TB2.Text + "%"); sqlPar[1] = new SqlParameter("@v2", "%" + TB2.Text + "%"); bfcd.dt = myHelper.getDataTable("select [cCusCode] , [cCusName] from WeightNotes where AutoId in (select min(AutoId) from WeightNotes group by cCusCode) and ( cCusName like @v1 or cCusCode like @v2)", sqlPar); bfcd.showDlg(); //bfcd.dt = myHelper.getDataTable("select [cCusCode] ,[cCusName] from WeightNotes where AutoId in (select min(AutoId) from WeightNotes group by cCusCode) and cCusCode like @v",sqlPar); //bfcd.showDlg(); } private void button4_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "车牌号"; bfcd.headerText2 = null; bfcd.retTextId = 3; bfcd.dt = myHelper.getDataTable("select distinct [cPlateNum] from WeightNotes where [cPlateNum] like @v", new SqlParameter("@v", "%" + TB3.Text + "%")); bfcd.showDlg(); } private void button11_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "司机"; bfcd.headerText2 = null; bfcd.retTextId = 4; bfcd.dt = myHelper.getDataTable("select distinct [cDriverName] from WeightNotes where [cDriverName] like @v", new SqlParameter("@v", "%" + TB4.Text + "%")); bfcd.showDlg(); } private void button5_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "磅单号"; bfcd.headerText2 = null; bfcd.retTextId = 5; bfcd.dt = myHelper.getDataTable("select distinct [cBillNo] from WeightNotes where [cBillNo] like @v", new SqlParameter("@v", "%" + TB5.Text + "%")); bfcd.showDlg(); } private void button10_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "卡片号码"; bfcd.headerText2 = null; bfcd.retTextId = 6; bfcd.dt = myHelper.getDataTable("select distinct [cICNum] from WeightNotes where [cICNum] like @v", new SqlParameter("@v", "%" + TB6.Text + "%")); bfcd.showDlg(); } private void button6_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "订单号"; bfcd.headerText2 = "订单类型"; bfcd.headerText3 = "订单日期"; bfcd.retTextId = 7; bfcd.dt = myHelper.getDataTable("select [cBillNo],[cBillType] ,[dMadeDate] from [sapOrders] where AutoId in (select min(AutoId) from sapOrders group by cBillNo) and cBillNo like @v", new SqlParameter("@v", "%" + TB7.Text + "%")); bfcd.showDlg(); } private void button9_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 1; bfcd.headerText1 = "订单号"; bfcd.headerText2 = "订单类型"; bfcd.headerText3 = "订单日期"; bfcd.retTextId = 8; bfcd.dt = myHelper.getDataTable("select [cBillNo],[cBillType] ,[dMadeDate] from [sapOrders] where AutoId in (select min(AutoId) from sapOrders group by cBillNo) and cBillType like @v", new SqlParameter("@v", "%" + TB8.Text + "%")); bfcd.showDlg(); } private void button7_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "物资代码"; bfcd.headerText2 = "物资名称"; bfcd.headerText3 = null; bfcd.retTextId = 9; SqlParameter[] sqlPar = new SqlParameter[2]; sqlPar[0] = new SqlParameter("@v1", "%" + TB9.Text + "%"); sqlPar[1] = new SqlParameter("@v2", "%" + TB9.Text + "%"); bfcd.dt = myHelper.getDataTable("select [cInvCode],[cInvName] from [sapPlanOrders] where AutoId in (select min(AutoId) from [sapPlanOrders] group by cInvCode) and (cInvCode like @v1 or cInvName like @v2) order by cInvCode", sqlPar); bfcd.showDlg(); } private void button8_Click(object sender, EventArgs e) { BillFilterConsiDlg bfcd = new BillFilterConsiDlg(); bfcd.callBackAction += bfcd_callBackAction; bfcd.selectedIndex = 0; bfcd.headerText1 = "物资代码"; bfcd.headerText2 = "物资名称"; bfcd.headerText3 = null; bfcd.retTextId = 10; SqlParameter[] sqlPar = new SqlParameter[2]; sqlPar[0] = new SqlParameter("@v1", "%" + TB10.Text + "%"); sqlPar[1] = new SqlParameter("@v2", "%" + TB10.Text + "%"); bfcd.dt = myHelper.getDataTable("select [cInvCode],[cInvName] from [sapPlanOrders] where AutoId in (select min(AutoId) from [sapPlanOrders] group by cInvCode) and (cInvCode like @v1 or cInvName like @v2) order by cInvCode", sqlPar); bfcd.showDlg(); } private void button2_Click(object sender, EventArgs e) { Close(); } private void st_ValueChanged(object sender, EventArgs e) { et.Checked = st.Checked; } private void et_ValueChanged(object sender, EventArgs e) { st.Checked = et.Checked; } } }
using System; using System.Collections.Generic; namespace LinkedQueueImplementation { public class LinkedQueue<T> { public int Count { get; private set; } public LinkedQueueNode<T> FirstElement { get; private set; } public LinkedQueueNode<T> LastElement { get; private set; } public void Enqueue(LinkedQueueNode<T> element) { if (this.FirstElement == null) { this.FirstElement = element; } else { if (this.FirstElement.NextInLine == null) { this.FirstElement.NextInLine = element; element.PrevInLine = this.FirstElement; } else { this.LastElement.NextInLine = element; element.PrevInLine = this.LastElement; } this.LastElement = element; } this.Count++; } public LinkedQueueNode<T> Dequeue() { if (this.FirstElement != null) { var result = this.FirstElement; this.FirstElement = this.FirstElement.NextInLine; if (this.FirstElement != null) { this.FirstElement.PrevInLine = null; } return result; } else { throw new NullReferenceException("End of queue reached"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestOlusturmaOtomasyonu { public class Testler { public int Id { get; set; } public string TestName { get; set; } public DateTime BaslamaTarihi { get; set; } public DateTime Bitistarihi { get; set; } public int SoruSayisi { get; set; } public string OgretmenAdi { get; set; } public override string ToString() { return TestName; } } }
using System; using System.Collections.Generic; using System.Text; using ENTITY; //<summary> //Summary description for SuffixPrefixInfo //</summary> namespace ENTITY { public class SuffixPrefixInfo { private decimal _suffixprefixId; private decimal _voucherTypeId; private DateTime _fromDate; private DateTime _toDate; private decimal _startIndex; private string _prefix; private string _suffix; private int _widthOfNumericalPart; private bool _prefillWithZero; private string _narration; private DateTime _extraDate; private string _extra1; private string _extra2; public decimal SuffixprefixId { get { return _suffixprefixId; } set { _suffixprefixId = value; } } public decimal VoucherTypeId { get { return _voucherTypeId; } set { _voucherTypeId = value; } } public DateTime FromDate { get { return _fromDate; } set { _fromDate = value; } } public DateTime ToDate { get { return _toDate; } set { _toDate = value; } } public decimal StartIndex { get { return _startIndex; } set { _startIndex = value; } } public string Prefix { get { return _prefix; } set { _prefix = value; } } public string Suffix { get { return _suffix; } set { _suffix = value; } } public int WidthOfNumericalPart { get { return _widthOfNumericalPart; } set { _widthOfNumericalPart = value; } } public bool PrefillWithZero { get { return _prefillWithZero; } set { _prefillWithZero = value; } } public string Narration { get { return _narration; } set { _narration = value; } } public DateTime ExtraDate { get { return _extraDate; } set { _extraDate = value; } } public string Extra1 { get { return _extra1; } set { _extra1 = value; } } public string Extra2 { get { return _extra2; } set { _extra2 = value; } } } }
using System; using System.Collections.Generic; namespace Evpro.Domain.Entities { public partial class satisfactionsurvey { public int idSurvey { get; set; } public Nullable<System.DateTime> creationDate { get; set; } public string descreptiveText { get; set; } public string messageInfo { get; set; } public bool status { get; set; } public Nullable<int> idEvent_fk { get; set; } public Nullable<int> idParticipant { get; set; } public virtual ourevent ourevent { get; set; } public virtual participant participant { get; set; } } }
using ScribblersSharp; /// <summary> /// Scribble.rs Pad namespace /// </summary> namespace ScribblersPad { /// <summary> /// An interface that represents a game UI layout controller /// </summary> public interface IGameUILayoutController : IScribblersClientController { /// <summary> /// Game UI layout state /// </summary> EGameUILayoutState GameUILayoutState { get; set; } /// <summary> /// Gets invoked when a "ready" game message has been received /// </summary> event ReadyGameMessageReceivedDelegate OnReadyGameMessageReceived; /// <summary> /// Gets invoked when a "next-turn" game message has been received /// </summary> event NextTurnGameMessageReceivedDelegate OnNextTurnGameMessageReceived; /// <summary> /// Gets invoked when a "your-turn" game message has been received /// </summary> event YourTurnGameMessageReceivedDelegate OnYourTurnGameMessageReceived; /// <summary> /// Gets invoked when a "correct-guess" game message has been received /// </summary> event CorrectGuessGameMessageReceivedDelegate OnCorrectGuessGameMessageReceived; /// <summary> /// Gets invoked when drawing board has been shown /// </summary> event DrawingBoardShownDelegate OnDrawingBoardShown; /// <summary> /// Gets invoked when chat has been shown /// </summary> event ChatShownDelegate OnChatShown; /// <summary> /// Shows drawing board /// </summary> void ShowDrawingBoard(); /// <summary> /// Shows chat /// </summary> void ShowChat(); } }
/* SLTrace * TraceSession.cs * * Copyright (c) 2010, Ewen Cheslack-Postava * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of SLTrace nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OpenMetaverse; using System.Collections.Generic; using System.Diagnostics; namespace SLTrace { class TraceSession { public TraceSession(Config cfg) { mConfig = cfg; mClient = new GridClient(); mTracers = new List<ITracer>(); mController = null; mConnectedSimName = null; mNeedsReconnect = false; mDisconnectTime = DateTime.Now; mReconnectWait = TimeSpan.FromSeconds(30); // We turn as many things off as possible -- features are *opt in* by // default, meaning specific loggers must enable these features if they // need them mClient.Settings.MULTIPLE_SIMS = false; mClient.Throttle.Asset = 0; mClient.Throttle.Cloud = 0; mClient.Throttle.Land = 0; mClient.Throttle.Texture = 0; mClient.Throttle.Wind = 0; // Set up our session management callbacks mClient.Network.OnConnected += new NetworkManager.ConnectedCallback(this.ConnectHandler); mClient.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(this.DisconnectHandler); mClient.Network.OnSimConnected += new NetworkManager.SimConnectedCallback(this.SimConnectedHandler); } public GridClient Client { get { return mClient; } } public void AddTracer(ITracer tr) { if (tr != null) mTracers.Add(tr); } public IController Controller { set { mController = value; } } public Config Config { get { return mConfig; } } public void Run(TimeSpan duration) { // Notify all ITracers of start foreach(ITracer tr in mTracers) tr.StartTrace(this); // Notify controller if (mController != null) { Debug.Assert(mClient.Self != null, "Avatar AgentManager is null"); mController.StartTrace(this, mClient.Self); } if (!TryLogin()) { Console.WriteLine("Unable to login."); return; } // Sleep for the specified duration, async callbacks do all the real // work. DateTime start = DateTime.Now; while(true) { System.Threading.Thread.Sleep(1000); if (mController != null) mController.Update(); if (DateTime.Now - start > duration) break; if (mNeedsReconnect && DateTime.Now > mDisconnectTime + mReconnectWait) { bool logged_in = TryLogin(); if (logged_in && (!mConfig.HasStart || (mConnectedSimName.ToLower() == mConfig.StartSim.ToLower()))) { mNeedsReconnect = false; } else { if (logged_in) TryLogout(); mReconnectWait = TimeSpan.FromSeconds(mReconnectWait.TotalSeconds * 2.0); // Exponential back off } } } TryLogout(); // Notify all ITracers of start foreach(ITracer tr in mTracers) tr.StopTrace(); } private bool TryLogin() { bool logged_in; if (Config.HasStart) { string start_loc = NetworkManager.StartLocation(Config.StartSim, Config.StartX, Config.StartY, Config.StartZ); logged_in = mClient.Network.Login( mConfig.FirstName, mConfig.LastName, mConfig.Password, Config.UserAgent, start_loc, Config.UserVersion ); } else { logged_in = mClient.Network.Login( mConfig.FirstName, mConfig.LastName, mConfig.Password, Config.UserAgent, Config.UserVersion ); } Console.WriteLine("Login message: " + mClient.Network.LoginMessage); return logged_in; } private void TryLogout() { // And logout... mClient.Network.Logout(); } private void ConnectHandler(object sender) { Console.WriteLine("I'm connected to the simulator"); } private void DisconnectHandler(NetworkManager.DisconnectType type, string message) { Console.WriteLine("Got disconnected from sim: " + message); // Signal need for reconnect to main loop mNeedsReconnect = true; mDisconnectTime = DateTime.Now; mReconnectWait = TimeSpan.FromSeconds(30); } private void SimConnectedHandler(Simulator sim) { mConnectedSimName = sim.Name; } private Config mConfig; private GridClient mClient; private List<ITracer> mTracers; private IController mController; private string mConnectedSimName; private bool mNeedsReconnect; private DateTime mDisconnectTime; private TimeSpan mReconnectWait; } // class TraceSession } // namespace SLTrace
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JoneEu { public class Funcoes { public static int trataInt(object Values, int Default = 0) { try { return Convert.ToInt32(Values); } catch { return Default; } } public static string trataString(object Values, string Default = "") { try { return Convert.ToString(Values); } catch { return Default; } } public static double trataDouble(object Values, double Default = 0) { try { return Convert.ToDouble(Values); } catch { return Default; } } } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Data; using System.Globalization; using System.Net; using System.Xml; using NopSolutions.NopCommerce.BusinessLogic.Caching; using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings; using NopSolutions.NopCommerce.BusinessLogic.Profile; using NopSolutions.NopCommerce.Common; using NopSolutions.NopCommerce.DataAccess; using NopSolutions.NopCommerce.DataAccess.Directory; namespace NopSolutions.NopCommerce.BusinessLogic.Directory { /// <summary> /// Currency manager /// </summary> public partial class CurrencyManager { #region Constants private const string CURRENCIES_ALL_KEY = "Nop.currency.all-{0}"; private const string CURRENCIES_BY_ID_KEY = "Nop.currency.id-{0}"; private const string CURRENCIES_PATTERN_KEY = "Nop.currency."; #endregion #region Utilities private static CurrencyCollection DBMapping(DBCurrencyCollection dbCollection) { if (dbCollection == null) return null; CurrencyCollection collection = new CurrencyCollection(); foreach (DBCurrency dbItem in dbCollection) { Currency item = DBMapping(dbItem); collection.Add(item); } return collection; } private static Currency DBMapping(DBCurrency dbItem) { if (dbItem == null) return null; Currency item = new Currency(); item.CurrencyID = dbItem.CurrencyID; item.Name = dbItem.Name; item.CurrencyCode = dbItem.CurrencyCode; item.Rate = dbItem.Rate; item.DisplayLocale = dbItem.DisplayLocale; item.CustomFormatting = dbItem.CustomFormatting; item.Published = dbItem.Published; item.DisplayOrder = dbItem.DisplayOrder; item.CreatedOn = dbItem.CreatedOn; item.UpdatedOn = dbItem.UpdatedOn; return item; } #endregion #region Methods /// <summary> /// Gets currency live rates /// </summary> /// <param name="ExchangeRateCurrencyCode">Exchange rate currency code</param> /// <param name="UpdateDate">Update date</param> /// <param name="Rates">Currency rates table</param> public static void GetCurrencyLiveRates(string ExchangeRateCurrencyCode, out DateTime UpdateDate, out DataTable Rates) { if (String.IsNullOrEmpty(ExchangeRateCurrencyCode) || ExchangeRateCurrencyCode.ToLower() != "eur") throw new NopException("You can use our \"CurrencyLiveRate\" service only when exchange rate currency code is set to EURO"); UpdateDate = DateTime.Now; Rates = new DataTable(); Rates.Columns.Add("CurrencyCode", typeof(string)); Rates.Columns.Add("Rate", typeof(decimal)); HttpWebRequest request = WebRequest.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml") as HttpWebRequest; using (WebResponse response = request.GetResponse()) { XmlDocument document = new XmlDocument(); document.Load(response.GetResponseStream()); XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("ns", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); nsmgr.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01"); XmlNode node = document.SelectSingleNode("gesmes:Envelope/ns:Cube/ns:Cube", nsmgr); UpdateDate = DateTime.ParseExact(node.Attributes["time"].Value, "yyyy-MM-dd", null); NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; provider.NumberGroupSeparator = ""; foreach (XmlNode node2 in node.ChildNodes) Rates.Rows.Add(new object[] {node2.Attributes["currency"].Value, double.Parse(node2.Attributes["rate"].Value, provider) }); } } /// <summary> /// Deletes currency /// </summary> /// <param name="CurrencyID">Currency identifier</param> public static void DeleteCurrency(int CurrencyID) { DBProviderManager<DBCurrencyProvider>.Provider.DeleteCurrency(CurrencyID); if (CurrencyManager.CacheEnabled) { NopCache.RemoveByPattern(CURRENCIES_PATTERN_KEY); } } /// <summary> /// Gets a currency /// </summary> /// <param name="CurrencyID">Currency identifier</param> /// <returns>Currency</returns> public static Currency GetCurrencyByID(int CurrencyID) { if (CurrencyID == 0) return null; string key = string.Format(CURRENCIES_BY_ID_KEY, CurrencyID); object obj2 = NopCache.Get(key); if (CurrencyManager.CacheEnabled && (obj2 != null)) { return (Currency)obj2; } DBCurrency dbItem = DBProviderManager<DBCurrencyProvider>.Provider.GetCurrencyByID(CurrencyID); Currency currency = DBMapping(dbItem); if (CurrencyManager.CacheEnabled) { NopCache.Max(key, currency); } return currency; } /// <summary> /// Gets a currency by code /// </summary> /// <param name="CurrencyCode">Currency code</param> /// <returns>Currency</returns> public static Currency GetCurrencyByCode(string CurrencyCode) { if (String.IsNullOrEmpty(CurrencyCode)) return null; CurrencyCollection currencies = GetAllCurrencies(); foreach (Currency currency in currencies) { if (currency.CurrencyCode.ToLowerInvariant() == CurrencyCode.ToLowerInvariant()) { return currency; } } return null; } /// <summary> /// Gets all currencies /// </summary> /// <returns>Currency collection</returns> public static CurrencyCollection GetAllCurrencies() { bool showHidden = NopContext.Current.IsAdmin; string key = string.Format(CURRENCIES_ALL_KEY, showHidden); object obj2 = NopCache.Get(key); if (CurrencyManager.CacheEnabled && (obj2 != null)) { return (CurrencyCollection)obj2; } DBCurrencyCollection dbCollection = DBProviderManager<DBCurrencyProvider>.Provider.GetAllCurrencies(showHidden); CurrencyCollection currencyCollection = DBMapping(dbCollection); if (CurrencyManager.CacheEnabled) { NopCache.Max(key, currencyCollection); } return currencyCollection; } /// <summary> /// Inserts a currency /// </summary> /// <param name="Name">The name</param> /// <param name="CurrencyCode">The currency code</param> /// <param name="Rate">The rate</param> /// <param name="DisplayLocale">The display locale</param> /// <param name="CustomFormatting">The custom formatting</param> /// <param name="Published">A value indicating whether the entity is published</param> /// <param name="DisplayOrder">The display order</param> /// <param name="CreatedOn">The date and time of instance creation</param> /// <param name="UpdatedOn">The date and time of instance update</param> /// <returns>A currency</returns> public static Currency InsertCurrency(string Name, string CurrencyCode, decimal Rate, string DisplayLocale, string CustomFormatting, bool Published, int DisplayOrder, DateTime CreatedOn, DateTime UpdatedOn) { try { CultureInfo ci = CultureInfo.GetCultureInfo(DisplayLocale); } catch (Exception) { throw new NopException("Specified display locale culture is not supported"); } CreatedOn = DateTimeHelper.ConvertToUtcTime(CreatedOn); UpdatedOn = DateTimeHelper.ConvertToUtcTime(UpdatedOn); DBCurrency dbItem = DBProviderManager<DBCurrencyProvider>.Provider.InsertCurrency(Name, CurrencyCode, Rate, DisplayLocale, CustomFormatting, Published, DisplayOrder, CreatedOn, UpdatedOn); Currency currency = DBMapping(dbItem); if (CurrencyManager.CacheEnabled) { NopCache.RemoveByPattern(CURRENCIES_PATTERN_KEY); } return currency; } /// <summary> /// Updates the currency /// </summary> /// <param name="CurrencyID">Currency identifier</param> /// <param name="Name">The name</param> /// <param name="CurrencyCode">The currency code</param> /// <param name="Rate">The rate</param> /// <param name="DisplayLocale">The display locale</param> /// <param name="CustomFormatting">The custom formatting</param> /// <param name="Published">A value indicating whether the entity is published</param> /// <param name="DisplayOrder">The display order</param> /// <param name="CreatedOn">The date and time of instance creation</param> /// <param name="UpdatedOn">The date and time of instance update</param> /// <returns>A currency</returns> public static Currency UpdateCurrency(int CurrencyID, string Name, string CurrencyCode, decimal Rate, string DisplayLocale, string CustomFormatting, bool Published, int DisplayOrder, DateTime CreatedOn, DateTime UpdatedOn) { try { CultureInfo ci = CultureInfo.GetCultureInfo(DisplayLocale); } catch (Exception) { throw new NopException("Specified display locale culture is not supported"); } CreatedOn = DateTimeHelper.ConvertToUtcTime(CreatedOn); UpdatedOn = DateTimeHelper.ConvertToUtcTime(UpdatedOn); DBCurrency dbItem = DBProviderManager<DBCurrencyProvider>.Provider.UpdateCurrency(CurrencyID, Name, CurrencyCode, Rate, DisplayLocale, CustomFormatting, Published, DisplayOrder, CreatedOn, UpdatedOn); Currency currency = DBMapping(dbItem); if (CurrencyManager.CacheEnabled) { NopCache.RemoveByPattern(CURRENCIES_PATTERN_KEY); } return currency; } /// <summary> /// Converts currency /// </summary> /// <param name="Amount">Amount</param> /// <param name="SourceCurrencyCode">Source currency code</param> /// <param name="TargetCurrencyCode">Target currency code</param> /// <returns>Converted value</returns> public static decimal ConvertCurrency(decimal Amount, Currency SourceCurrencyCode, Currency TargetCurrencyCode) { decimal result = Amount; if (SourceCurrencyCode.CurrencyID == TargetCurrencyCode.CurrencyID) return result; if (result != decimal.Zero && SourceCurrencyCode.CurrencyID != TargetCurrencyCode.CurrencyID) { result = ConvertToPrimaryExchangeRateCurrency(result, SourceCurrencyCode); result = ConvertFromPrimaryExchangeRateCurrency(result, TargetCurrencyCode); } result = Math.Round(result, 2); return result; } /// <summary> /// Converts to primary exchange rate currency /// </summary> /// <param name="Amount">Amount</param> /// <param name="SourceCurrencyCode">Source currency code</param> /// <returns>Converted value</returns> public static decimal ConvertToPrimaryExchangeRateCurrency(decimal Amount, Currency SourceCurrencyCode) { decimal result = Amount; if (result != decimal.Zero && SourceCurrencyCode.CurrencyID != PrimaryExchangeRateCurrency.CurrencyID) { decimal ExchangeRate = SourceCurrencyCode.Rate; if (ExchangeRate == decimal.Zero) throw new NopException(string.Format("Exchange rate not found for currency [{0}]", SourceCurrencyCode.Name)); result = result / ExchangeRate; } return result; } /// <summary> /// Converts from primary exchange rate currency /// </summary> /// <param name="Amount">Amount</param> /// <param name="TargetCurrencyCode">Target currency code</param> /// <returns>Converted value</returns> public static Decimal ConvertFromPrimaryExchangeRateCurrency(Decimal Amount, Currency TargetCurrencyCode) { Decimal result = Amount; if (result != decimal.Zero && TargetCurrencyCode.CurrencyID != PrimaryExchangeRateCurrency.CurrencyID) { Decimal ExchangeRate = TargetCurrencyCode.Rate; if (ExchangeRate == decimal.Zero) throw new NopException(string.Format("Exchange rate not found for currency [{0}]", TargetCurrencyCode.Name)); result = result * ExchangeRate; } return result; } #endregion #region Property /// <summary> /// Gets or sets a primary store currency /// </summary> public static Currency PrimaryStoreCurrency { get { int primaryStoreCurrencyID = SettingManager.GetSettingValueInteger("Currency.PrimaryStoreCurrency"); return GetCurrencyByID(primaryStoreCurrencyID); } set { if (value != null) SettingManager.SetParam("Currency.PrimaryStoreCurrency", value.CurrencyID.ToString()); } } /// <summary> /// Gets or sets a primary exchange rate currency /// </summary> public static Currency PrimaryExchangeRateCurrency { get { int primaryExchangeRateCurrencyID = SettingManager.GetSettingValueInteger("Currency.PrimaryExchangeRateCurrency"); return GetCurrencyByID(primaryExchangeRateCurrencyID); } set { if (value != null) SettingManager.SetParam("Currency.PrimaryExchangeRateCurrency", value.CurrencyID.ToString()); } } /// <summary> /// Gets a value indicating whether cache is enabled /// </summary> public static bool CacheEnabled { get { return SettingManager.GetSettingValueBoolean("Cache.CurrencyManager.CacheEnabled"); } } #endregion } }